package com.ejie.ab61.comun.utilidades;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;

import javax.sql.rowset.serial.SerialClob;

public class ClobUtils {

	/**
	 * Transforma un campo Clob a String
	 * 
	 * @param clob
	 *            Clob la cual se desea transformar
	 * @return String Devuelve la cadena resultante de las transformaciones.
	 */
	public static String clobToString(Clob clob) {

		try {
			if (clob != null) {
				Reader reader = clob.getCharacterStream();
				CharArrayWriter writer = new CharArrayWriter();

				int i = 1;

				while ((i = reader.read()) != -1) {
					writer.write(i);
				}

				return new String(writer.toCharArray());
			} else {
				return null;
			}
		} catch (SQLException sqle) {
			return null;
		} catch (IOException ioe) {
			return null;
		}
	}

	/**
	 * Transforma un campo Clob a String
	 * 
	 * @param string
	 * @return String Devuelve la cadena resultante de las transformaciones.
	 * @throws SQLException
	 *             SQLException
	 * @throws IOException
	 *             IOException
	 */
	public static Clob stringToClob(String string) throws SQLException, IOException {

		if (string != null && !string.equals("")) {
			Clob clob = new SerialClob(string.toCharArray());
			clob.setString(1, string);

			return clob;
		} else {
			return null;
		}
	}

}