List of usage examples for java.sql Clob getCharacterStream
java.io.Reader getCharacterStream() throws SQLException;
From source file:nz.co.gregs.dbvolution.datatypes.DBJavaObject.java
@SuppressWarnings("unchecked") private O getFromCLOB(ResultSet resultSet, String fullColumnName) throws SQLException { O returnValue = null;/* ww w. ja va 2s . c o m*/ Clob clob = resultSet.getClob(fullColumnName); if (resultSet.wasNull() || clob == null) { this.setToNull(); } else { try { BufferedReader input = new BufferedReader(clob.getCharacterStream()); try { List<byte[]> byteArrays = new ArrayList<byte[]>(); int totalBytesRead = 0; try { char[] resultSetBytes; resultSetBytes = new char[100000]; int bytesRead = input.read(resultSetBytes); while (bytesRead > 0) { totalBytesRead += bytesRead; byteArrays.add(String.valueOf(resultSetBytes).getBytes()); resultSetBytes = new char[100000]; bytesRead = input.read(resultSetBytes); } } catch (IOException ex) { Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex); } byte[] bytes = new byte[totalBytesRead]; int bytesAdded = 0; for (byte[] someBytes : byteArrays) { System.arraycopy(someBytes, 0, bytes, bytesAdded, Math.min(someBytes.length, bytes.length - bytesAdded)); bytesAdded += someBytes.length; } ObjectInputStream objectInput = new ObjectInputStream(new ByteArrayInputStream(bytes)); // this.setValue(objectInput.readObject()); returnValue = (O) objectInput.readObject(); } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex); } } return returnValue; }
From source file:org.springframework.jdbc.support.lob.OracleLobHandler.java
@Override public Reader getClobAsCharacterStream(ResultSet rs, int columnIndex) throws SQLException { logger.debug("Returning Oracle CLOB as character stream"); Clob clob = rs.getClob(columnIndex); initializeResourcesBeforeRead(rs.getStatement().getConnection(), clob); Reader retVal = (clob != null ? clob.getCharacterStream() : null); releaseResourcesAfterRead(rs.getStatement().getConnection(), clob); return retVal; }
From source file:org.apache.sqoop.lib.LargeObjectLoader.java
/** * Actually read a ClobRef instance from the ResultSet and materialize * the data either inline or to a file.// ww w . ja va2 s. c o m * * @param colNum the column of the ResultSet's current row to read. * @param r the ResultSet to read from. * @return a ClobRef encapsulating the data in this field. * @throws IOException if an error occurs writing to the FileSystem. * @throws SQLException if an error occurs reading from the database. */ public com.cloudera.sqoop.lib.ClobRef readClobRef(int colNum, ResultSet r) throws IOException, InterruptedException, SQLException { long maxInlineLobLen = conf.getLong(MAX_INLINE_LOB_LEN_KEY, DEFAULT_MAX_LOB_LENGTH); Clob c = r.getClob(colNum); if (null == c) { return null; } else if (c.length() > maxInlineLobLen) { // Deserialize large CLOB into separate file. long len = c.length(); LobFile.Writer lobWriter = getClobWriter(); long recordOffset = lobWriter.tell(); Reader reader = null; Writer w = lobWriter.writeClobRecord(len); try { reader = c.getCharacterStream(); copyAll(reader, w); } finally { if (null != w) { w.close(); } if (null != reader) { reader.close(); } // Mark the record as finished. lobWriter.finishRecord(); } return new com.cloudera.sqoop.lib.ClobRef(getRelativePath(lobWriter), recordOffset, len); } else { // This is a 1-based array. return new com.cloudera.sqoop.lib.ClobRef(c.getSubString(1, (int) c.length())); } }
From source file:nz.co.gregs.dbvolution.datatypes.DBByteArray.java
private byte[] getFromCLOB(ResultSet resultSet, String fullColumnName) throws SQLException { byte[] bytes = new byte[] {}; Clob clob = resultSet.getClob(fullColumnName); if (resultSet.wasNull() || clob == null) { this.setToNull(); } else {/*from ww w .j a v a 2 s .c o m*/ final Reader characterStream = clob.getCharacterStream(); try { BufferedReader input = new BufferedReader(characterStream); List<byte[]> byteArrays = new ArrayList<byte[]>(); int totalBytesRead = 0; try { char[] resultSetBytes; resultSetBytes = new char[100000]; try { int bytesRead = input.read(resultSetBytes); while (bytesRead > 0) { totalBytesRead += bytesRead; byteArrays.add(String.valueOf(resultSetBytes).getBytes()); resultSetBytes = new char[100000]; bytesRead = input.read(resultSetBytes); } } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex); } bytes = new byte[totalBytesRead]; int bytesAdded = 0; for (byte[] someBytes : byteArrays) { System.arraycopy(someBytes, 0, bytes, bytesAdded, Math.min(someBytes.length, bytes.length - bytesAdded)); bytesAdded += someBytes.length; } } finally { try { characterStream.close(); } catch (IOException ex) { Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex); } } // this.setValue(bytes); } return bytes; }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected String clobToString(Clob clob) throws JRException { try {/*from w w w .j a va 2 s . co m*/ int bufSize = 8192; char[] buf = new char[bufSize]; Reader reader = new BufferedReader(clob.getCharacterStream(), bufSize); StringBuilder str = new StringBuilder((int) clob.length()); for (int read = reader.read(buf); read > 0; read = reader.read(buf)) { str.append(buf, 0, read); } return str.toString(); } catch (SQLException e) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e); } catch (IOException e) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e); } }
From source file:com.liferay.portal.upgrade.util.Table.java
public Object getValue(ResultSet rs, String name, Integer type) throws Exception { Object value = null;/*from w ww . ja v a 2 s. co m*/ int t = type.intValue(); if (t == Types.BIGINT) { try { value = GetterUtil.getLong(rs.getLong(name)); } catch (SQLException e) { value = GetterUtil.getLong(rs.getString(name)); } } else if (t == Types.BOOLEAN) { value = GetterUtil.getBoolean(rs.getBoolean(name)); } else if (t == Types.CLOB) { try { Clob clob = rs.getClob(name); if (clob == null) { value = StringPool.BLANK; } else { UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(clob.getCharacterStream()); StringBundler sb = new StringBundler(); String line = null; while ((line = unsyncBufferedReader.readLine()) != null) { if (sb.length() != 0) { sb.append(SAFE_NEWLINE_CHARACTER); } sb.append(line); } value = sb.toString(); } } catch (Exception e) { // If the database doesn't allow CLOB types for the column // value, then try retrieving it as a String value = GetterUtil.getString(rs.getString(name)); } } else if (t == Types.DOUBLE) { value = GetterUtil.getDouble(rs.getDouble(name)); } else if (t == Types.FLOAT) { value = GetterUtil.getFloat(rs.getFloat(name)); } else if (t == Types.INTEGER) { value = GetterUtil.getInteger(rs.getInt(name)); } else if (t == Types.SMALLINT) { value = GetterUtil.getShort(rs.getShort(name)); } else if (t == Types.TIMESTAMP) { try { value = rs.getTimestamp(name); } catch (Exception e) { } if (value == null) { value = StringPool.NULL; } } else if (t == Types.VARCHAR) { value = GetterUtil.getString(rs.getString(name)); } else { throw new UpgradeException("Upgrade code using unsupported class type " + type); } return value; }
From source file:org.batoo.jpa.jdbc.AbstractColumn.java
private Object readLob(Object value) { try {// ww w .java 2 s .co m if (value instanceof Clob) { final Clob clob = (Clob) value; if (this.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 (this.javaType == String.class) { final StringWriter w = new StringWriter(); IOUtils.copy(new ByteArrayInputStream((byte[]) value), w); value = w.toString(); } else if (this.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 (this.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 (this.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:com.p5solutions.core.jpa.orm.ConversionUtilityImpl.java
/** * Convert clob.//from w w w. j av a 2 s . c o m * * @param clob * the clob * @param targetType * the target type * @return the object */ public Object convertCLOB(Clob clob, Class<?> targetType) { if (ReflectionUtility.isStringClass(targetType)) { // TODO charset needs to be passed in from the resultset, or defined // as // part of the transaction template??? try { // TODO THIS NEEDS TO BE APPENDED IN UTF-8 ??? based on the // character // setting of the database??? Reader reader = clob.getCharacterStream(); StringBuilder output = new StringBuilder(); int r = -1; while ((r = reader.read()) >= 0) { output.append((char) r); } return output.toString(); } catch (SQLException e) { // TODO log it throw new RuntimeException(e); } catch (IOException e) { // TODO log it throw new RuntimeException(e); } } else if (ReflectionUtility.isByteArray(targetType)) { } return clob; }
From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java
public Map<String, Object> queryForMap(final String sql, final Object... args) { logSql(sql, args);/* ww w . j a va2 s . co m*/ return execute(new IConnectionCallback<Map<String, Object>>() { @SuppressWarnings("resource") public Map<String, Object> execute(Connection con) throws SQLException { Map<String, Object> result = null; PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement(sql); ps.setQueryTimeout(settings.getQueryTimeout()); if (args != null && args.length > 0) { setValues(ps, args); } rs = ps.executeQuery(); if (rs.next()) { ResultSetMetaData meta = rs.getMetaData(); int colCount = meta.getColumnCount(); result = new LinkedCaseInsensitiveMap<Object>(colCount); for (int i = 1; i <= colCount; i++) { String key = meta.getColumnName(i); Object value = rs.getObject(i); if (value instanceof Blob) { Blob blob = (Blob) value; try { value = IOUtils.toByteArray(blob.getBinaryStream()); } catch (IOException e) { throw new IoException(e); } } else if (value instanceof Clob) { Clob clob = (Clob) value; try { value = IOUtils.toByteArray(clob.getCharacterStream()); } catch (IOException e) { throw new IoException(e); } } else if (value != null) { Class<?> clazz = value.getClass(); Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && superClazz.getName().equals("oracle.sql.Datum")) { try { Method method = superClazz.getMethod("toJdbc"); value = method.invoke(value); } catch (Exception e) { throw new IllegalStateException(e); } } } result.put(key, value); } } } finally { close(rs); close(ps); } return result; } }); }
From source file:org.pentaho.reporting.libraries.base.util.IOUtils.java
/** * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it. If * there are errors converting it, this method will log the cause and return null. * * @param clob the clob to be read as string. * @return the string or null in case of errors. *//*from w ww . ja va 2s . c om*/ public String readClob(final Clob clob) throws IOException, SQLException { final long length = clob.length(); if (length > Integer.MAX_VALUE) { logger.warn("This CLOB contains more than 2^31 characters. We cannot handle that."); throw new IOException("This CLOB contains more than 2^31 characters. We cannot handle that."); } final Reader inStream = clob.getCharacterStream(); final MemoryStringWriter outStream = new MemoryStringWriter((int) length, 65536); try { IOUtils.getInstance().copyWriter(inStream, outStream); } finally { try { inStream.close(); } catch (IOException e) { logger.warn("Failed to close input stream. No worries, we will be alright anyway.", e); } } return outStream.toString(); }