List of usage examples for java.sql Clob getCharacterStream
java.io.Reader getCharacterStream() throws SQLException;
From source file:com.hangum.tadpole.rdb.core.editors.main.utils.TableToDataUtils.java
/** * ? ?? ./* w w w .jav a 2s .c o m*/ * * @param columnObject * @param intType * @param name * @return */ public static TableColumnDAO getTableData(Object columnObject, Integer intType, String name) { TableColumnDAO columnDao = new TableColumnDAO(); if (intType == null) intType = java.sql.Types.VARCHAR; String strType = RDBTypeToJavaTypeUtils.getRDBType(intType); columnDao.setName(name); columnDao.setType(strType); if (columnObject != null) { // ? ?? clob?? ? ?. if (columnObject instanceof java.sql.Clob) { Clob cl = (Clob) columnObject; StringBuffer clobContent = new StringBuffer(); String readBuffer = new String(); // ? ? clob ? ? ? ? . BufferedReader bufferedReader; try { bufferedReader = new java.io.BufferedReader(cl.getCharacterStream()); while ((readBuffer = bufferedReader.readLine()) != null) { clobContent.append(readBuffer); } columnDao.setCol_value(clobContent.toString()); } catch (Exception e) { logger.error("Clob column echeck", e); //$NON-NLS-1$ } } else if (columnObject instanceof java.sql.Blob) { try { Blob blob = (Blob) columnObject; columnDao.setCol_value(blob.getBinaryStream()); } catch (Exception e) { logger.error("Blob column echeck", e); //$NON-NLS-1$ } } else if (columnObject instanceof byte[]) { byte[] b = (byte[]) columnObject; StringBuffer str = new StringBuffer(); try { for (byte buf : b) { str.append(buf); } str.append("\n\nHex : " + new BigInteger(str.toString(), 2).toString(16)); //$NON-NLS-1$ columnDao.setCol_value(str.toString()); } catch (Exception e) { logger.error("Clob column echeck", e); //$NON-NLS-1$ } } else { columnDao.setCol_value(columnObject.toString()); } } else { columnDao.setCol_value(GetPreferenceGeneral.getResultNull()); } return columnDao; }
From source file:CSVWriter.java
private static String read(Clob c) throws SQLException, IOException { StringBuffer sb = new StringBuffer( (int) c.length()); Reader r = c.getCharacterStream(); char[] cbuf = new char[2048]; int n = 0;//w w w . jav a2 s . c om while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { if (n > 0) { sb.append(cbuf, 0, n); } } return sb.toString(); }
From source file:org.batoo.jpa.jdbc.ValueConverter.java
private static Object readLob(Object value, Class<?> javaType) { try {//from www .j a v a 2s . c o m if (value instanceof Clob) { final Clob clob = (Clob) value; if (javaType == String.class) { final StringWriter w = new StringWriter(); IOUtils.copy(clob.getAsciiStream(), w); value = w.toString(); } else { final CharArrayWriter w = new CharArrayWriter((int) clob.length()); IOUtils.copy(clob.getCharacterStream(), w); value = w.toCharArray(); } } else if (value instanceof byte[]) { if (javaType == String.class) { final StringWriter w = new StringWriter(); IOUtils.copy(new ByteArrayInputStream((byte[]) value), w); value = w.toString(); } else if (javaType == char[].class) { final byte[] byteArray = (byte[]) value; final char[] charArray = new char[byteArray.length]; for (int i = 0; i < charArray.length; i++) { charArray[i] = (char) byteArray[i]; } value = charArray; } else if (javaType != byte[].class) { final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value)); try { return is.readObject(); } finally { is.close(); } } } else if (value instanceof String) { return value; } else { final Blob blob = (Blob) value; if (javaType == byte[].class) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(blob.getBinaryStream(), os); value = os.toByteArray(); } else { final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream()); try { value = is.readObject(); } finally { is.close(); } } } return value; } catch (final Exception e) { throw new PersistenceException("Cannot read sql data", e); } }
From source file:CSVWriter.java
private static String read(Clob c) throws SQLException, IOException { StringBuilder sb = new StringBuilder((int) c.length()); Reader r = c.getCharacterStream(); char[] cbuf = new char[CLOBBUFFERSIZE]; int n;//from w w w. j a v a 2s . c o m while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { sb.append(cbuf, 0, n); } return sb.toString(); }
From source file:sernet.gs.ui.rcp.gsimport.TransferData.java
public static String convertClobToStringEncodingSave(Clob clob, String encoding) throws IOException { try {/*from w w w . j a v a 2 s .c o m*/ Reader reader = clob.getCharacterStream(); InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(reader, encoding)); if (in != null) { return InputUtil.streamToString(in, encoding); } else { return ""; } } catch (SQLException e) { LOG.error("Error while converting clob to String", e); throw new RuntimeException(e); } }
From source file:org.moqui.impl.entity.EntityJavaUtil.java
public static Object getResultSetValue(ResultSet rs, int index, FieldInfo fi, EntityFacade efi) throws EntityException { if (fi.typeValue == -1) throw new EntityException("No typeValue found for " + fi.entityName + "." + fi.name); Object value = null;//from w ww . java2s . com try { switch (fi.typeValue) { case 1: // getMetaData and the column type are somewhat slow (based on profiling), and String values are VERY // common, so only do for text-very-long if (fi.isTextVeryLong) { ResultSetMetaData rsmd = rs.getMetaData(); if (Types.CLOB == rsmd.getColumnType(index)) { // if the String is empty, try to get a text input stream, this is required for some databases // for larger fields, like CLOBs Clob valueClob = rs.getClob(index); Reader valueReader = null; if (valueClob != null) valueReader = valueClob.getCharacterStream(); if (valueReader != null) { // read up to 4096 at a time char[] inCharBuffer = new char[4096]; StringBuilder strBuf = new StringBuilder(); try { int charsRead; while ((charsRead = valueReader.read(inCharBuffer, 0, 4096)) > 0) { strBuf.append(inCharBuffer, 0, charsRead); } valueReader.close(); } catch (IOException e) { throw new EntityException("Error reading long character stream for field [" + fi.name + "] of entity [" + fi.entityName + "]", e); } value = strBuf.toString(); } } else { value = rs.getString(index); } } else { value = rs.getString(index); } break; case 2: try { value = rs.getTimestamp(index, efi.getCalendarForTzLc()); } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace( "Ignoring SQLException for getTimestamp(), leaving null (found this in MySQL with a date/time value of [0000-00-00 00:00:00]): " + e.toString()); } break; case 3: value = rs.getTime(index, efi.getCalendarForTzLc()); break; case 4: value = rs.getDate(index, efi.getCalendarForTzLc()); break; case 5: int intValue = rs.getInt(index); if (!rs.wasNull()) value = intValue; break; case 6: long longValue = rs.getLong(index); if (!rs.wasNull()) value = longValue; break; case 7: float floatValue = rs.getFloat(index); if (!rs.wasNull()) value = floatValue; break; case 8: double doubleValue = rs.getDouble(index); if (!rs.wasNull()) value = doubleValue; break; case 9: BigDecimal bigDecimalValue = rs.getBigDecimal(index); if (!rs.wasNull()) value = bigDecimalValue != null ? bigDecimalValue.stripTrailingZeros() : null; break; case 10: boolean booleanValue = rs.getBoolean(index); if (!rs.wasNull()) value = booleanValue; break; case 11: Object obj = null; byte[] originalBytes = rs.getBytes(index); InputStream binaryInput = null; if (originalBytes != null && originalBytes.length > 0) { binaryInput = new ByteArrayInputStream(originalBytes); } if (originalBytes != null && originalBytes.length <= 0) { logger.warn("Got byte array back empty for serialized Object with length [" + originalBytes.length + "] for field [" + fi.name + "] (" + index + ")"); } if (binaryInput != null) { ObjectInputStream inStream = null; try { inStream = new ObjectInputStream(binaryInput); obj = inStream.readObject(); } catch (IOException ex) { if (logger.isTraceEnabled()) logger.trace("Unable to read BLOB from input stream for field [" + fi.name + "] (" + index + "): " + ex.toString()); } catch (ClassNotFoundException ex) { if (logger.isTraceEnabled()) logger.trace("Class not found: Unable to cast BLOB data to an Java object for field [" + fi.name + "] (" + index + "); most likely because it is a straight byte[], so just using the raw bytes: " + ex.toString()); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { throw new EntityException("Unable to close binary input stream for field [" + fi.name + "] (" + index + "): " + e.toString(), e); } } } } if (obj != null) { value = obj; } else { value = originalBytes; } break; case 12: SerialBlob sblob = null; try { // NOTE: changed to try getBytes first because Derby blows up on getBlob and on then calling getBytes for the same field, complains about getting value twice byte[] fieldBytes = rs.getBytes(index); if (!rs.wasNull()) sblob = new SerialBlob(fieldBytes); // fieldBytes = theBlob != null ? theBlob.getBytes(1, (int) theBlob.length()) : null } catch (SQLException e) { if (logger.isTraceEnabled()) logger.trace("Ignoring exception trying getBytes(), trying getBlob(): " + e.toString()); Blob theBlob = rs.getBlob(index); if (!rs.wasNull()) sblob = new SerialBlob(theBlob); } value = sblob; break; case 13: value = new SerialClob(rs.getClob(index)); break; case 14: case 15: value = rs.getObject(index); break; } } catch (SQLException sqle) { logger.error("SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); throw new EntityException( "SQL Exception while getting value for field: [" + fi.name + "] (" + index + ")", sqle); } return value; }
From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java
/** * Retrieve a JDBC column value from a ResultSet, using the most appropriate * value type. The returned value should be a detached value object, not * having any ties to the active ResultSet: in particular, it should not be * a Blob or Clob object but rather a byte array respectively String * representation.// ww w .j ava 2s . co m * <p> * Uses the <code>getObject(index)</code> method, but includes additional * "hacks" to get around Oracle 10g returning a non-standard object for its * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns * leaving out the time portion: These columns will explicitly be extracted * as standard <code>java.sql.Timestamp</code> object. * * @param rs * is the ResultSet holding the data * @param index * is the column index * @param readStringsAsBytes TODO * @return the value object * @throws SQLException * if thrown by the JDBC API * @see java.sql.Blob * @see java.sql.Clob * @see java.sql.Timestamp */ public static Object getResultSetValue(ResultSet rs, int index, boolean readStringsAsBytes) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); Object obj = null; int jdbcType = metaData.getColumnType(index); if (readStringsAsBytes && TypeMap.isTextType(jdbcType)) { byte[] bytes = rs.getBytes(index); if (bytes != null) { obj = new String(bytes); } } else { obj = rs.getObject(index); } String className = null; if (obj != null) { className = obj.getClass().getName(); } if (obj instanceof Blob) { Blob blob = (Blob) obj; InputStream is = blob.getBinaryStream(); try { obj = IOUtils.toByteArray(is); } catch (IOException e) { throw new SqlException(e); } finally { IOUtils.closeQuietly(is); } } else if (obj instanceof Clob) { Clob clob = (Clob) obj; Reader reader = clob.getCharacterStream(); try { obj = IOUtils.toString(reader); } catch (IOException e) { throw new SqlException(e); } finally { IOUtils.closeQuietly(reader); } } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className))) { obj = rs.getTimestamp(index); } else if (className != null && "oracle.sql.TIMESTAMPTZ".equals(className)) { obj = rs.getString(index); } else if (className != null && "oracle.sql.TIMESTAMPLTZ".equals(className)) { obj = rs.getString(index); } else if (className != null && className.startsWith("oracle.sql.DATE")) { String metaDataClassName = metaData.getColumnClassName(index); if ("java.sql.Timestamp".equals(metaDataClassName) || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) { obj = rs.getTimestamp(index); } else { obj = rs.getDate(index); } } else if (obj instanceof java.sql.Date) { String metaDataClassName = metaData.getColumnClassName(index); if ("java.sql.Timestamp".equals(metaDataClassName)) { obj = rs.getTimestamp(index); } } else if (obj instanceof Timestamp) { String typeName = metaData.getColumnTypeName(index); if (typeName != null && typeName.equals("timestamptz")) { obj = rs.getString(index); } } return obj; }
From source file:com.adaptris.core.services.jdbc.types.ClobColumnTranslator.java
private void write(Clob blob, Writer out) throws SQLException, IOException { try (Reader input = blob.getCharacterStream()) { copy(input, out);/*from w w w. j a va 2 s.c o m*/ } }
From source file:org.xenei.jdbc4sparql.iface.TypeConverter.java
@SuppressWarnings("unchecked") public static <T> T extractData(final Object columnObject, final Class<T> resultingClass) throws SQLException { if (columnObject == null) { return (T) nullValueMap.get(resultingClass); }//from www .ja va 2 s.c o m // try the simple case if (resultingClass.isAssignableFrom(columnObject.getClass())) { return resultingClass.cast(columnObject); } // see if we can do a simple numeric assignment if (columnObject instanceof Number) { return fromNumber(columnObject, resultingClass); } // see if we can convert from a string if (columnObject instanceof String) { return fromString(columnObject, resultingClass); } if (columnObject instanceof Boolean) { final Boolean b = (Boolean) columnObject; return fromString(b ? "1" : "0", resultingClass); } if (columnObject instanceof byte[]) { try { if (resultingClass.isAssignableFrom(Clob.class)) { return resultingClass.cast( new SerialClob(IOUtils.toCharArray(new ByteArrayInputStream((byte[]) columnObject)))); } if (resultingClass.isAssignableFrom(Blob.class)) { return resultingClass.cast(new SerialBlob((byte[]) columnObject)); } if (resultingClass.isAssignableFrom(InputStream.class)) { return resultingClass.cast(new ByteArrayInputStream((byte[]) columnObject)); } final String s = new String((byte[]) columnObject); return fromString(s, resultingClass); } catch (final IOException e) { throw new SQLException(e.getMessage(), e); } } if (columnObject instanceof Blob) { try { final Blob b = (Blob) columnObject; if (resultingClass.isAssignableFrom(byte[].class)) { return resultingClass.cast(IOUtils.toByteArray(b.getBinaryStream())); } if (resultingClass.isAssignableFrom(Clob.class)) { return resultingClass.cast(new SerialClob(IOUtils.toCharArray(b.getBinaryStream()))); } if (resultingClass.isAssignableFrom(InputStream.class)) { return resultingClass.cast(b.getBinaryStream()); } final String s = new String(IOUtils.toByteArray(((Blob) columnObject).getBinaryStream())); return fromString(s, resultingClass); } catch (final IOException e) { throw new SQLException(e.getMessage(), e); } } if (columnObject instanceof Clob) { try { final Clob c = (Clob) columnObject; if (resultingClass.isAssignableFrom(byte[].class)) { return resultingClass.cast(IOUtils.toByteArray(c.getAsciiStream())); } if (resultingClass.isAssignableFrom(Blob.class)) { return resultingClass.cast(new SerialBlob(IOUtils.toByteArray(c.getAsciiStream()))); } if (resultingClass.isAssignableFrom(InputStream.class)) { return resultingClass.cast(c.getAsciiStream()); } final String s = String.valueOf(IOUtils.toCharArray(c.getCharacterStream())); return fromString(s, resultingClass); } catch (final IOException e) { throw new SQLException(e.getMessage(), e); } } if (columnObject instanceof InputStream) { try { final InputStream is = (InputStream) columnObject; if (resultingClass.isAssignableFrom(Clob.class)) { return resultingClass.cast(new SerialClob(IOUtils.toCharArray(is))); } if (resultingClass.isAssignableFrom(Blob.class)) { return resultingClass.cast(new SerialBlob(IOUtils.toByteArray(is))); } if (resultingClass.isAssignableFrom(byte[].class)) { return resultingClass.cast(IOUtils.toByteArray(is)); } return fromString(new String(IOUtils.toByteArray(is)), resultingClass); } catch (final IOException e) { throw new SQLException(e.getMessage(), e); } } throw new SQLException(String.format(" Can not cast %s (%s) to %s", columnObject.getClass(), columnObject.toString(), resultingClass)); }
From source file:com.mirth.connect.server.mule.transformers.ResultMapToXML.java
public Object doTransform(Object source) throws TransformerException { if (source instanceof Map) { Map data = (Map) source; try {/* ww w .j ava 2 s.co m*/ Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = document.createElement("result"); document.appendChild(root); for (Iterator iter = data.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); Element child = document.createElement(key); String value = new String(); Object objectValue = data.get(key); if (objectValue != null) { if (objectValue instanceof byte[]) { value = new String((byte[]) objectValue); } else if (objectValue instanceof java.sql.Clob) { // convert it to a string java.sql.Clob clobValue = (java.sql.Clob) objectValue; Reader reader = clobValue.getCharacterStream(); if (reader == null) { value = ""; } StringBuffer sb = new StringBuffer(); try { char[] charbuf = new char[(int) clobValue.length()]; for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) { sb.append(charbuf, 0, i); } } catch (IOException e) { logger.error("Error reading clob value.\n" + ExceptionUtils.getStackTrace(e)); } value = sb.toString(); } else if (objectValue instanceof java.sql.Blob) { try { java.sql.Blob blobValue = (java.sql.Blob) objectValue; value = new String(blobValue.getBytes(1, (int) blobValue.length())); } catch (Exception ex) { logger.error("Error reading blob value.\n" + ExceptionUtils.getStackTrace(ex)); } } else { value = objectValue.toString(); } } child.appendChild(document.createTextNode(value)); root.appendChild(child); } DocumentSerializer docSerializer = new DocumentSerializer(); return docSerializer.toXML(document); } catch (Exception e) { throw new TransformerException( org.mule.config.i18n.Message.createStaticMessage("Failed to parse result map"), this); } } else if (source instanceof String) { return source.toString(); } else { throw new TransformerException( org.mule.config.i18n.Message.createStaticMessage("Unregistered result type"), this); } }