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.composite.resultdetail.ResultTableComposite.java
/** * select table column to editor/*w w w .ja v a 2 s.c o m*/ */ private TableColumnDAO selectColumnToEditor() { if (eventTableSelect == null) return null; final Table tableResult = tvQueryResult.getTable(); TableItem[] selection = tableResult.getSelection(); if (selection.length != 1) return null; TableColumnDAO columnDao = new TableColumnDAO(); TableItem item = tableResult.getSelection()[0]; for (int i = 0; i < tableResult.getColumnCount(); i++) { if (item.getBounds(i).contains(eventTableSelect.x, eventTableSelect.y)) { Map<Integer, Object> mapColumns = getRsDAO().getDataList().getData() .get(tableResult.getSelectionIndex()); // execute extension start =============================== IMainEditorExtension[] extensions = getRdbResultComposite().getRdbResultComposite().getMainEditor() .getMainEditorExtions(); for (IMainEditorExtension iMainEditorExtension : extensions) { iMainEditorExtension.resultSetDoubleClick(i, mapColumns); } // execute extension stop =============================== // ? ? ?? ? ? if (i == 0) { columnDao.setName(PublicTadpoleDefine.DEFINE_TABLE_COLUMN_BASE_ZERO); columnDao.setType(PublicTadpoleDefine.DEFINE_TABLE_COLUMN_BASE_ZERO_TYPE); for (int j = 1; j < tableResult.getColumnCount(); j++) { Object columnObject = mapColumns.get(j); boolean isNumberType = RDBTypeToJavaTypeUtils .isNumberType(getRsDAO().getColumnType().get(j)); if (isNumberType) { String strText = ""; //$NON-NLS-1$ // if select value is null can if (columnObject == null) strText = "0"; //$NON-NLS-1$ else strText = columnObject.toString(); columnDao.setCol_value(columnDao.getCol_value() + strText + ", "); } else if ("BLOB".equalsIgnoreCase(columnDao.getData_type())) { //$NON-NLS-1$ // ignore blob type } else { String strText = ""; //$NON-NLS-1$ // if select value is null can if (columnObject == null) strText = ""; //$NON-NLS-1$ else strText = columnObject.toString(); columnDao.setCol_value(columnDao.getCol_value() + SQLUtil.makeQuote(strText) + ", "); } } columnDao.setCol_value(StringUtils.removeEnd("" + columnDao.getCol_value(), ", ")); break; } else { // ? ?? ? ?? ? ? ? . Object columnObject = mapColumns.get(i); Integer intType = getRsDAO().getColumnType().get(i); if (intType == null) intType = java.sql.Types.VARCHAR; String strType = RDBTypeToJavaTypeUtils.getRDBType(intType); columnDao.setName(getRsDAO().getColumnName().get(i)); 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[]) {// (columnObject.getClass().getCanonicalName().startsWith("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 { String strText = ""; //$NON-NLS-1$ // if select value is null can if (columnObject == null) strText = ""; //$NON-NLS-1$ else strText = columnObject.toString(); columnDao.setCol_value(strText); } } // end object null } // end if first column break; } // for column index } // end for return columnDao; }
From source file:org.kawanfw.test.api.client.InsertAndUpdateClobTest.java
/** * Test that the blob was were correctly inserted * /*from www .j a va2 s. co m*/ * @param connection */ public void selectClobTestAlternateSyntax(Connection connection, String originalFileName, String shaHexa) throws Exception { int item_id; Clob clob; String sql = "select * from documentation where item_id >= ? "; PreparedStatement prepStatement = connection.prepareStatement(sql); int i = 1; prepStatement.setInt(i++, 1); ResultSet rs = prepStatement.executeQuery(); MessageDisplayer.display(""); Reader reader = null; Writer writer = null; while (rs.next()) { item_id = rs.getInt("item_id"); i = 1; item_id = rs.getInt(i++); clob = rs.getClob(i++); File originalFile = SqlTestParms.getFileFromUserHome(originalFileName); // String extension = "." // + StringUtils.substringAfterLast(originalFile.toString(), // "."); File file = InsertAndUpdateBlobTest.createTempFile(originalFile.toString()); try { reader = clob.getCharacterStream(); if (reader != null) { writer = new BufferedWriter(new FileWriter(file)); IOUtils.copy(reader, writer); } else { MessageDisplayer.display("item_doc column is null!"); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); try { clob.free(); } catch (Throwable e) { MessageDisplayer.display("clob.free() not done: " + e.toString()); } } MessageDisplayer.display(""); MessageDisplayer.display("item_id : " + item_id); // Compute the hash of the file Sha1Util sha1 = new Sha1Util(); String shaHexaNew = sha1.getHexFileHash(file); Assert.assertEquals(shaHexa, shaHexaNew); file.delete(); MessageDisplayer.display(""); MessageDisplayer.display("Ok, SHA-1 value of read file " + file + " is same as inserted file " + SqlTestParms.getFileFromUserHome(originalFileName)); } prepStatement.close(); rs.close(); MessageDisplayer.display("Select done!"); }
From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java
private String getClobString(Clob data, int maxClobSize) throws IOException, SQLException { if (data == null) { return null; }/*from www. j a v a 2 s . c o m*/ StringBuilder sb = new StringBuilder(); int bufLen = 1024; char[] cbuf = new char[bufLen]; // Read up to max clob length long maxRemaining = maxClobSize; int count; try (Reader r = data.getCharacterStream()) { while ((count = r.read(cbuf)) > -1 && maxRemaining > 0) { // If c is more then the remaining chars we want to read, read only as many are available if (count > maxRemaining) { count = (int) maxRemaining; } sb.append(cbuf, 0, count); // decrement available according to the number of chars we've read maxRemaining -= count; } } return sb.toString(); }
From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java
/** Try to extract an orderxmldoc from a given Clob. * This method is used by the read() method, which catches the * thrown DocumentException.//from w w w .j a v a 2s . c om * @param clob a given Clob returned from the database * @return a Document object based on the data in the Clob * @throws SQLException If data from the clob cannot be fetched. * @throws DocumentException If unable to create a Document object based on * the data in the Clob */ private Document getOrderXMLdocFromClob(Clob clob) throws SQLException, DocumentException { Document doc; try { SAXReader reader = new SAXReader(); doc = reader.read(clob.getCharacterStream()); } catch (DocumentException e) { log.warn("Failed to read the contents of the clob as XML:" + clob.getSubString(1, (int) clob.length())); throw e; } return doc; }
From source file:org.apache.oozie.tools.OozieDBCLI.java
private void convertClobToBlobinDerby(Connection conn, String startingVersion) throws Exception { if (conn == null) { return;/* w w w. j a v a 2s .c o m*/ } System.out.println("Converting clob columns to blob for all tables"); Statement statement = conn.createStatement(); for (Map.Entry<String, List<String>> tableClobColumnMap : getTableClobColumnMap().entrySet()) { String tableName = tableClobColumnMap.getKey(); List<String> columnNames = tableClobColumnMap.getValue(); for (String column : columnNames) { statement.executeUpdate(getAddColumnQuery(tableName, TEMP_COLUMN_PREFIX + column, "blob")); } ResultSet rs = statement.executeQuery(getSelectQuery(tableName, columnNames)); while (rs.next()) { for (String column : columnNames) { if (startingVersion.equals(DB_VERSION_PRE_4_0) && tableName.equals("COORD_ACTIONS") && column.equals("push_missing_dependencies")) { // The push_missing_depdencies column was added in DB_VERSION_FOR_4_0 as a CLOB and we're going to convert // it to BLOB in DB_VERSION_FOR_5_0. However, if Oozie 5 did the upgrade from DB_VERSION_PRE_4_0 to // DB_VERSION_FOR_4_0 (and is now doing it for DB_VERSION_FOR_5_0) push_missing_depdencies will already be a // BLOB because Oozie 5 created the column instead of Oozie 4; and the update query below will fail. continue; } Clob confClob = rs.getClob(column); if (confClob == null) { continue; } PreparedStatement ps = conn.prepareStatement( "update " + tableName + " set " + TEMP_COLUMN_PREFIX + column + "=? where id = ?"); byte[] data = IOUtils.toByteArray(confClob.getCharacterStream(), "UTF-8"); ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length); ps.setString(2, rs.getString(1)); ps.executeUpdate(); ps.close(); } } rs.close(); for (String column : columnNames) { statement.executeUpdate(getDropColumnQuery(tableName, column)); statement.executeUpdate( "RENAME COLUMN " + tableName + "." + TEMP_COLUMN_PREFIX + column + " TO " + column); } } statement.close(); System.out.println("DONE"); }
From source file:org.kawanfw.sql.jdbc.PreparedStatementHttp.java
@Override public void setClob(int parameterIndex, Clob x) throws SQLException { testIfClosed();/*from w w w.j a v a2s . c o m*/ // Clob creation is not optimized (other file creation) , because if // htmlEncoding is on we must rewrite the file Reader reader = x.getCharacterStream(); setCharacterStream(parameterIndex, reader); }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
@Override public Object getFieldValue(JRField field) throws JRException { Object objValue = null;/* ww w. j a v a 2 s . c o m*/ if (field != null && resultSet != null) { Integer columnIndex = getColumnIndex(field); Class<?> clazz = field.getValueClass(); try { if (clazz.equals(java.lang.Boolean.class)) { objValue = resultSet.getBoolean(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Byte.class)) { objValue = resultSet.getByte(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.util.Date.class) || clazz.equals(java.sql.Date.class)) { objValue = readDate(columnIndex, field); } else if (clazz.equals(java.sql.Timestamp.class)) { objValue = readTimestamp(columnIndex, field); } else if (clazz.equals(java.sql.Time.class)) { objValue = readTime(columnIndex, field); } else if (clazz.equals(java.lang.Double.class)) { objValue = resultSet.getDouble(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Float.class)) { objValue = resultSet.getFloat(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Integer.class)) { objValue = resultSet.getInt(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.io.InputStream.class)) { byte[] bytes = readBytes(columnIndex); if (bytes == null) { objValue = null; } else { objValue = new ByteArrayInputStream(bytes); } } else if (clazz.equals(java.lang.Long.class)) { objValue = resultSet.getLong(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.Short.class)) { objValue = resultSet.getShort(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.math.BigDecimal.class)) { objValue = resultSet.getBigDecimal(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(java.lang.String.class)) { int columnType = resultSet.getMetaData().getColumnType(columnIndex); switch (columnType) { case Types.CLOB: Clob clob = resultSet.getClob(columnIndex); if (resultSet.wasNull()) { objValue = null; } else { objValue = clobToString(clob); } break; default: objValue = resultSet.getString(columnIndex); if (resultSet.wasNull()) { objValue = null; } break; } } else if (clazz.equals(Clob.class)) { objValue = resultSet.getClob(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(Reader.class)) { Reader reader = null; long size = -1; int columnType = resultSet.getMetaData().getColumnType(columnIndex); switch (columnType) { case Types.CLOB: Clob clob = resultSet.getClob(columnIndex); if (!resultSet.wasNull()) { reader = clob.getCharacterStream(); size = clob.length(); } break; default: reader = resultSet.getCharacterStream(columnIndex); if (resultSet.wasNull()) { reader = null; } } if (reader == null) { objValue = null; } else { objValue = getArrayReader(reader, size); } } else if (clazz.equals(Blob.class)) { objValue = resultSet.getBlob(columnIndex); if (resultSet.wasNull()) { objValue = null; } } else if (clazz.equals(Image.class)) { byte[] bytes = readBytes(columnIndex); if (bytes == null) { objValue = null; } else { objValue = JRImageLoader.getInstance(jasperReportsContext).loadAwtImageFromBytes(bytes); } } else if (clazz.equals(byte[].class)) { objValue = readBytes(columnIndex); } else { objValue = resultSet.getObject(columnIndex); } } catch (Exception e) { throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_FIELD_VALUE_NOT_RETRIEVED, new Object[] { field.getName(), clazz.getName() }, e); } } return objValue; }
From source file:helma.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet./* w ww .j a v a2s .co m*/ */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(safe); for (int i = 0; i < columns.length; i++) { int columnNumber = i + 1 + offset; // set prototype? if (columns[i].isPrototypeField()) { String protoId = rs.getString(columnNumber); protoName = dbm.getPrototypeName(protoId); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError("No prototype defined for prototype mapping \"" + protoName + "\" - Using default prototype \"" + dbm.getTypeName() + "\"."); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(columnNumber); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(columnNumber); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: case Types.BOOLEAN: newprop.setBooleanValue(rs.getBoolean(columnNumber)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(columnNumber)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(columnNumber)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(columnNumber); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: newprop.setJavaObjectValue(rs.getBytes(columnNumber)); break; case Types.BLOB: case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(columnNumber); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(columnNumber)); } catch (SQLException x) { Reader in = rs.getCharacterStream(columnNumber); if (in == null) { newprop.setStringValue(null); break; } StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = in.read(buffer)) > -1) { out.append(buffer, 0, read); } newprop.setStringValue(out.toString()); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(columnNumber)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(columnNumber)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(columnNumber); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(columnNumber)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } else { Transactor tx = Transactor.getInstance(); if (tx != null) { // Check if the node is already registered with the transactor - // it may be in the process of being DELETED, but do return the // new node if the old one has been marked as INVALID. DbKey key = new DbKey(dbmap, id); Node dirtyNode = tx.getDirtyNode(key); if (dirtyNode != null && dirtyNode.getState() != Node.INVALID) { return dirtyNode; } } } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && rel.isPrimitiveOrReference()) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if (rel.isReference() && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel); } propMap.put(rel.propName, prop); } } node.init(dbmap, id, name, protoName, propMap); return node; }
From source file:axiom.objectmodel.db.NodeManager.java
/** * Create a new Node from a ResultSet./* w ww . jav a2 s . c o m*/ */ public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset) throws SQLException, IOException, ClassNotFoundException { HashMap propBuffer = new HashMap(); String id = null; String name = null; String protoName = dbm.getTypeName(); DbMapping dbmap = dbm; Node node = new Node(); for (int i = 0; i < columns.length; i++) { // set prototype? if (columns[i].isPrototypeField()) { protoName = rs.getString(i + 1 + offset); if (protoName != null) { dbmap = getDbMapping(protoName); if (dbmap == null) { // invalid prototype name! app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode") + "Invalid prototype name: " + protoName + " - using default"); dbmap = dbm; protoName = dbmap.getTypeName(); } } } // set id? if (columns[i].isIdField()) { id = rs.getString(i + 1 + offset); // if id == null, the object doesn't actually exist - return null if (id == null) { return null; } } // set name? if (columns[i].isNameField()) { name = rs.getString(i + 1 + offset); } Property newprop = new Property(node); switch (columns[i].getType()) { case Types.BIT: newprop.setBooleanValue(rs.getBoolean(i + 1 + offset)); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: newprop.setIntegerValue(rs.getLong(i + 1 + offset)); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: newprop.setFloatValue(rs.getDouble(i + 1 + offset)); break; case Types.DECIMAL: case Types.NUMERIC: BigDecimal num = rs.getBigDecimal(i + 1 + offset); if (num == null) { break; } if (num.scale() > 0) { newprop.setFloatValue(num.doubleValue()); } else { newprop.setIntegerValue(num.longValue()); } break; case Types.VARBINARY: case Types.BINARY: // newprop.setStringValue(rs.getString(i+1+offset)); newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset)); break; case Types.LONGVARBINARY: { InputStream in = rs.getBinaryStream(i + 1 + offset); if (in == null) { break; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int read; while ((read = in.read(buffer)) > -1) { bout.write(buffer, 0, read); } newprop.setJavaObjectValue(bout.toByteArray()); } break; case Types.LONGVARCHAR: try { newprop.setStringValue(rs.getString(i + 1 + offset)); } catch (SQLException x) { Reader in = rs.getCharacterStream(i + 1 + offset); char[] buffer = new char[2048]; int read = 0; int r; while ((r = in.read(buffer, read, buffer.length - read)) > -1) { read += r; if (read == buffer.length) { // grow input buffer char[] newBuffer = new char[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } newprop.setStringValue(new String(buffer, 0, read)); } break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: newprop.setStringValue(rs.getString(i + 1 + offset)); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: newprop.setDateValue(rs.getTimestamp(i + 1 + offset)); break; case Types.NULL: newprop.setStringValue(null); break; case Types.CLOB: Clob cl = rs.getClob(i + 1 + offset); if (cl == null) { newprop.setStringValue(null); break; } char[] c = new char[(int) cl.length()]; Reader isr = cl.getCharacterStream(); isr.read(c); newprop.setStringValue(String.copyValueOf(c)); break; default: newprop.setStringValue(rs.getString(i + 1 + offset)); break; } if (rs.wasNull()) { newprop.setStringValue(null); } propBuffer.put(columns[i].getName(), newprop); // mark property as clean, since it's fresh from the db newprop.dirty = false; } if (id == null) { return null; } Hashtable propMap = new Hashtable(); DbColumn[] columns2 = dbmap.getColumns(); for (int i = 0; i < columns2.length; i++) { Relation rel = columns2[i].getRelation(); if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) { Property prop = (Property) propBuffer.get(columns2[i].getName()); if (prop == null) { continue; } prop.setName(rel.propName); // if the property is a pointer to another node, change the property type to NODE if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) { // FIXME: References to anything other than the primary key are not supported prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer()); } propMap.put(rel.propName.toLowerCase(), prop); } } node.init(dbmap, id, name, protoName, propMap, safe); return node; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
protected static String clobToString(Clob clob) throws SQLException, IOException { if (clob == null) return null; StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(clob.getCharacterStream()); while (true) { String s = br.readLine(); if (s == null) break; sb.append(s);//from w ww . j a v a 2 s . c om } return sb.toString(); }