List of usage examples for java.sql Blob getBinaryStream
java.io.InputStream getBinaryStream() throws SQLException;
From source file:org.infoglue.calendar.controllers.ResourceController.java
private void dumpResource(Resource resource, int width, int height) { File outputFile = getResourceFile(resource, width, height); log.debug("Will generate thumbnail with file name: " + outputFile.getName()); Blob blob = resource.getResource(); if (blob != null) { ThumbnailGenerator tg = ThumbnailGenerator.getInstance(); try {/*from ww w . j a v a 2 s .c o m*/ tg.transform(blob.getBinaryStream(), outputFile, width, height, 100); } catch (SQLException ex) { log.error("SQLException when dumping calendar resource thumbnail to disk. " + resource.getFileName() + ". Exception message: " + ex.getMessage()); log.warn("SQLException when dumping calendar resource thumbnail to disk. " + resource.getFileName(), ex); } catch (IOException ex) { log.error("IOException when dumping calendar resource thumbnail to disk. " + resource.getFileName() + ". Exception message: " + ex.getMessage()); log.warn("IOException when dumping calendar resource thumbnail to disk. " + resource.getFileName(), ex); } if (log.isInfoEnabled()) { log.info("File was generated successfully: " + outputFile.exists()); } } }
From source file:org.jboss.bqt.client.results.xml.XMLCompareResults.java
/** * Compare actual results, identifiers and types with expected. <br> * <strong>Note </strong>: result list are expected to match element for * element.</br>/*w ww.j a va 2s . c o m*/ * * @param actualResults * @param actualDatatypes * @param actualIdentifiers * @param expectedResults * @param expectedDatatypes * @param expectedIdentifiers * @param eMsg * @throws QueryTestFailedException * If comparison fails. */ private static void compareResultSets(final List actualResults, final List actualDatatypes, final List actualIdentifiers, final List expectedResults, final List expectedDatatypes, final List expectedIdentifiers, final String eMsg) throws QueryTestFailedException { // Compare column names and types compareIdentifiers(actualIdentifiers, expectedIdentifiers, actualDatatypes, expectedDatatypes); // Walk through records and compare actual against expected final int actualRowCount = actualResults.size(); final int expectedRowCount = expectedResults.size(); final int actualColumnCount = actualIdentifiers.size(); // Check for less records than in expected results if (actualRowCount < expectedRowCount) { throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$ " records but received only " + actualRowCount); //$NON-NLS-1$ } else if (actualRowCount > expectedRowCount) { // Check also for more records than expected throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$ " records but received " + actualRowCount); //$NON-NLS-1$ } // DEBUG: // debugOut.println("================== Compariing Rows ==================="); // Loop through rows for (int row = 0; row < actualRowCount; row++) { // Get actual record final List actualRecord = (List) actualResults.get(row); // Get expected record final List expectedRecord = (List) expectedResults.get(row); // DEBUG: // debugOut.println("Row: " + (row + 1)); // debugOut.println(" expectedRecord: " + expectedRecord); // debugOut.println(" actualRecord: " + actualRecord); // Loop through columns // Compare actual elements with expected elements column by column // in this row for (int col = 0; col < actualColumnCount; col++) { // Get actual value Object actualValue = actualRecord.get(col); // Get expected value Object expectedValue = expectedRecord.get(col); // DEBUG: // debugOut.println(" Col: " +(col +1) + ": expectedValue:[" + // expectedValue + "] actualValue:[" + actualValue + // "]"); // Compare these values if ((expectedValue == null && actualValue != null) || (actualValue == null && expectedValue != null)) { // Compare nulls throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$ + " and column " + (col + 1) //$NON-NLS-1$ + ": expected = [" //$NON-NLS-1$ + (expectedValue != null ? expectedValue : "null") + "], actual = [" //$NON-NLS-1$ + (actualValue != null ? actualValue : "null") + "]"); //$NON-NLS-1$ } if (expectedValue == null && actualValue == null) { continue; } if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) { if (actualValue instanceof Clob) { Clob c = (Clob) actualValue; try { actualValue = ObjectConverterUtil.convertToString(c.getAsciiStream()); } catch (Throwable e) { // TODO Auto-generated catch block throw new QueryTestFailedException(e); } } else if (actualValue instanceof Blob) { Blob b = (Blob) actualValue; try { byte[] ba = ObjectConverterUtil.convertToByteArray(b.getBinaryStream()); actualValue = String.valueOf(ba.length); // actualValue = // ObjectConverterUtil.convertToString(b.getBinaryStream()); } catch (Throwable e) { // TODO Auto-generated catch block throw new QueryTestFailedException(e); } } else if (actualValue instanceof SQLXML) { SQLXML s = (SQLXML) actualValue; try { actualValue = ObjectConverterUtil.convertToString(s.getBinaryStream()); } catch (Throwable e) { // TODO Auto-generated catch block throw new QueryTestFailedException(e); } } if (!(expectedValue instanceof String)) { expectedValue = expectedValue.toString(); } } // Compare values with equals if (!expectedValue.equals(actualValue)) { // DEBUG: if (expectedValue instanceof java.sql.Date) { expectedValue = expectedValue.toString(); actualValue = actualValue.toString(); } else if (expectedValue instanceof java.sql.Time) { expectedValue = expectedValue.toString(); actualValue = actualValue.toString(); } if (expectedValue instanceof String) { final String expectedString = (String) expectedValue; if (!(actualValue instanceof String)) { throw new QueryTestFailedException(eMsg + "Value (types) mismatch at row " + (row + 1) //$NON-NLS-1$ + " and column " + (col + 1) //$NON-NLS-1$ + ": expected = [" //$NON-NLS-1$ + expectedValue + ", (String) ], actual = [" //$NON-NLS-1$ + actualValue + ", (" + actualValue.getClass().getName() + ") ]"); //$NON-NLS-1$ } // Check for String difference assertStringsMatch(expectedString, (String) actualValue, (row + 1), (col + 1), eMsg); } else { throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$ + " and column " + (col + 1) //$NON-NLS-1$ + ": expected = [" //$NON-NLS-1$ + expectedValue + "], actual = [" //$NON-NLS-1$ + actualValue + "]"); //$NON-NLS-1$ } } } // end loop through columns } // end loop through rows }
From source file:org.jboss.bqt.client.xml.XMLQueryVisitationStrategy.java
/** * Produce an XML message for an instance of the Object. * <br>// www .ja v a2s. co m * @param object the instance for which the message is to be produced. * @param parent the XML element that is to be the parent of the produced XML message. * @return the root element of the XML segment that was produced. * @exception JDOMException if there is an error producing the message. * @throws SQLException */ private Element produceObject(Object object, Element parent) throws JDOMException, SQLException { // ---------------------- // Create the Object element ... // ---------------------- Element objectElement = new Element(TagNames.Elements.OBJECT); String result = null; if (object instanceof Blob || object instanceof Clob || object instanceof SQLXML) { if (object instanceof Clob) { Clob c = (Clob) object; try { result = ObjectConverterUtil.convertToString(c.getAsciiStream()); } catch (Throwable e) { // TODO Auto-generated catch block throw new SQLException(e); } } else if (object instanceof Blob) { Blob b = (Blob) object; try { byte[] ba = ObjectConverterUtil.convertToByteArray(b.getBinaryStream()); result = String.valueOf(ba.length); } catch (Throwable e) { // TODO Auto-generated catch block throw new SQLException(e); } } else if (object instanceof SQLXML) { SQLXML s = (SQLXML) object; try { result = ObjectConverterUtil.convertToString(s.getBinaryStream()); } catch (Throwable e) { // TODO Auto-generated catch block throw new SQLException(e); } } } else { result = object.toString(); } objectElement.setText(result); if (parent != null) { objectElement = parent.addContent(objectElement); } return objectElement; }
From source file:org.jesterj.ingest.scanners.JdbcScanner.java
private byte[] getContentBytes(ResultSet rs) throws SQLException { byte[] rawBytes = null; // If the content column was specified if (StringUtils.isNotBlank(contentColumn)) { // Get its value. Object content = rs.getObject(contentColumn); if (content != null) { // Clob if (content instanceof Clob) { Clob clob = (Clob) content; try (Reader reader = clob.getCharacterStream()) { rawBytes = CharStreams.toString(reader).getBytes(); } catch (IOException ex) { String msg = String.format("I/O error while reading value of content column '%s'.", contentColumn); log.error(msg, ex);//w w w . j a v a 2s. c o m } } // Blob else if (content instanceof Blob) { Blob blob = (Blob) content; try (InputStream stream = blob.getBinaryStream()) { rawBytes = IOUtils.toByteArray(stream); } catch (IOException ex) { String msg = String.format("I/O error while reading value of content column '%s'.", contentColumn); log.error(msg, ex); } } // Date (unlikely, but) else if (content instanceof Date) { rawBytes = convertDateToString(content).getBytes(); } // Anything else else { rawBytes = content.toString().getBytes(); } } } return rawBytes; }
From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java
public Map<String, Object> queryForMap(final String sql, final Object... args) { logSql(sql, args);/*w w w . j av a2 s .c o 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.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.//from ww w. j a v a2 s . c o 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:org.jumpmind.db.sql.Row.java
protected byte[] toBytes(Object obj) { if (obj != null) { if (obj instanceof byte[]) { return (byte[]) obj; } else if (obj instanceof Blob) { Blob blob = (Blob) obj; try { return IOUtils.toByteArray(blob.getBinaryStream()); } catch (IOException e) { throw new IoException(e); } catch (SQLException e) { throw new SqlException(e); }// w w w.j a v a2s .c o m } else if (obj instanceof String) { return obj.toString().getBytes(); } else { throw new IllegalStateException( String.format("Cannot translate a %s into a byte[]", obj.getClass().getName())); } } else { return null; } }
From source file:org.kawanfw.sql.jdbc.PreparedStatementHttp.java
@Override public void setBlob(int parameterIndex, Blob x) throws SQLException { testIfClosed();/* ww w. ja va 2s . c om*/ if (x instanceof BlobHttp) { BlobHttp blobHttp = (BlobHttp) x; // Close the underlying output stream, cleaner: blobHttp.close(); String rawRemoteFileName = blobHttp.getFile().getName(); debug("blobHttp.getFile(): " + blobHttp.getFile()); debug("rawRemoteFileName : " + rawRemoteFileName); addFiles(blobHttp.getFile(), rawRemoteFileName); // Ok. File is successfully uploaded! // Set the parameter using the file name InputStream inputStream = new TransportInputStream(rawRemoteFileName); // parameterValues.put(parameterIndex, inputStream); statementHolder.setParameter(parameterIndex, inputStream); } else { InputStream in = x.getBinaryStream(); setBinaryStream(parameterIndex, in, x.length()); } }
From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTest.java
/** * Test that the blob was were correctly inserted * /*from w ww . jav a 2s .c o m*/ * @param connection */ public void selectBlobTestAlternateSyntax(Connection connection, String originalFileName, String shaHexa) throws Exception { int customer_id; int item_id; String description; BigDecimal cost_price; Date date_placed; Timestamp date_shipped; Blob blob; boolean is_delivered; int quantity; String sql = "select * from orderlog where customer_id >= ? and item_id >= ? "; PreparedStatement prepStatement = connection.prepareStatement(sql); int i = 1; prepStatement.setInt(i++, 1); prepStatement.setInt(i++, 1); ResultSet rs = prepStatement.executeQuery(); MessageDisplayer.display(""); InputStream in = null; OutputStream out = null; SqlUtil sqlUtil = new SqlUtil(connection); while (rs.next()) { customer_id = rs.getInt("customer_id"); item_id = rs.getInt("item_id"); description = rs.getString("description"); cost_price = rs.getBigDecimal("cost_price"); date_placed = rs.getDate("date_placed"); date_shipped = rs.getTimestamp("date_shipped"); blob = rs.getBlob("jpeg_image"); if (sqlUtil.isIngres()) { is_delivered = (rs.getInt("is_delivered") == 1) ? true : false; } else { is_delivered = rs.getBoolean("is_delivered"); } quantity = rs.getInt("quantity"); i = 1; customer_id = rs.getInt(i++); item_id = rs.getInt(i++); description = rs.getString(i++); cost_price = rs.getBigDecimal(i++); date_placed = rs.getDate(i++); date_shipped = rs.getTimestamp(i++); File originalBlobFile = SqlTestParms.getFileFromUserHome(originalFileName); // String extension = "." // + StringUtils.substringAfterLast( // originalBlobFile.toString(), "."); File file = createTempFile(originalBlobFile.toString()); try { in = blob.getBinaryStream(); if (in != null) { out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } else { MessageDisplayer.display("jpeg_image column is null!"); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { blob.free(); } catch (Throwable e) { MessageDisplayer.display("blob.free() not done: " + e.toString()); } } i++; if (sqlUtil.isIngres()) { is_delivered = (rs.getInt(i++) == 1) ? true : false; } else { is_delivered = rs.getBoolean(i++); } quantity = rs.getInt(i++); MessageDisplayer.display(""); MessageDisplayer.display("customer_id : " + customer_id); MessageDisplayer.display("item_id : " + item_id); MessageDisplayer.display("description : " + description); MessageDisplayer.display("cost_price : " + cost_price); MessageDisplayer.display("date_placed : " + date_placed); MessageDisplayer.display("date_shipped: " + date_shipped); MessageDisplayer.display("jpeg_image : " + "content stored in file: " + file); MessageDisplayer.display("is_delivered: " + is_delivered); MessageDisplayer.display("quantity : " + quantity); // 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:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java
/** * Test that the blob was were correctly inserted * //w w w .ja va 2 s .c o m * @param connection */ public void selectGetBlobSyntax(Connection connection, String originalFileName, String shaHexa) throws Exception { int customer_id; int item_id; String description; BigDecimal cost_price; Date date_placed; Timestamp date_shipped; Blob blob; boolean is_delivered; int quantity; String sql = "select * from orderlog where customer_id >= ? and item_id >= ? "; PreparedStatement prepStatement = connection.prepareStatement(sql); int i = 1; prepStatement.setInt(i++, 1); prepStatement.setInt(i++, 1); ResultSet rs = prepStatement.executeQuery(); MessageDisplayer.display(""); InputStream in = null; OutputStream out = null; SqlUtil sqlUtil = new SqlUtil(connection); while (rs.next()) { customer_id = rs.getInt("customer_id"); item_id = rs.getInt("item_id"); description = rs.getString("description"); cost_price = rs.getBigDecimal("cost_price"); date_placed = rs.getDate("date_placed"); date_shipped = rs.getTimestamp("date_shipped"); blob = rs.getBlob("jpeg_image"); if (sqlUtil.isIngres()) { is_delivered = (rs.getInt("is_delivered") == 1) ? true : false; } else { is_delivered = rs.getBoolean("is_delivered"); } quantity = rs.getInt("quantity"); i = 1; customer_id = rs.getInt(i++); item_id = rs.getInt(i++); description = rs.getString(i++); cost_price = rs.getBigDecimal(i++); date_placed = rs.getDate(i++); date_shipped = rs.getTimestamp(i++); File originalBlobFile = SqlTestParms.getFileFromUserHome(originalFileName); File file = createTempFile(originalBlobFile.toString()); try { in = blob.getBinaryStream(); if (in != null) { out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } else { MessageDisplayer.display("jpeg_image column is null!"); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { blob.free(); } catch (Throwable e) { MessageDisplayer.display("blob.free() not done: " + e.toString()); } } i++; if (sqlUtil.isIngres()) { is_delivered = (rs.getInt(i++) == 1) ? true : false; } else { is_delivered = rs.getBoolean(i++); } quantity = rs.getInt(i++); MessageDisplayer.display(""); MessageDisplayer.display("customer_id : " + customer_id); MessageDisplayer.display("item_id : " + item_id); MessageDisplayer.display("description : " + description); MessageDisplayer.display("cost_price : " + cost_price); MessageDisplayer.display("date_placed : " + date_placed); MessageDisplayer.display("date_shipped: " + date_shipped); MessageDisplayer.display("jpeg_image : " + "content stored in file: " + file); MessageDisplayer.display("is_delivered: " + is_delivered); MessageDisplayer.display("quantity : " + quantity); // 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!"); }