List of usage examples for java.sql Blob getBinaryStream
java.io.InputStream getBinaryStream() throws SQLException;
From source file:gobblin.metastore.MysqlStateStore.java
@Override public T get(String storeName, String tableName, String stateId) throws IOException { try (Connection connection = dataSource.getConnection(); PreparedStatement queryStatement = connection.prepareStatement(SELECT_JOB_STATE_SQL)) { int index = 0; queryStatement.setString(++index, storeName); queryStatement.setString(++index, tableName); try (ResultSet rs = queryStatement.executeQuery()) { if (rs.next()) { Blob blob = rs.getBlob(1); Text key = new Text(); try (InputStream is = StreamUtils.isCompressed(blob.getBytes(1, 2)) ? new GZIPInputStream(blob.getBinaryStream()) : blob.getBinaryStream(); DataInputStream dis = new DataInputStream(is)) { // keep deserializing while we have data while (dis.available() > 0) { T state = this.stateClass.newInstance(); key.readFields(dis); state.readFields(dis); if (key.toString().equals(stateId)) { return state; }//from w w w . j a va 2 s . co m } } catch (EOFException e) { // no more data. GZIPInputStream.available() doesn't return 0 until after EOF. } } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IOException( "failure retrieving state from storeName " + storeName + " tableName " + tableName, e); } return null; }
From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java
@Test public void testInsertBlob() throws Exception { InputStream fin = new FileInputStream(getResourceDirectory() + "order_line_500K.csv"); PreparedStatement ps = methodWatcher.prepareStatement("insert into FILES (name, doc) values (?,?)"); ps.setString(1, "csv_file"); ps.setBinaryStream(2, fin);//from w ww .ja v a 2 s .co m ps.execute(); ResultSet rs = methodWatcher.executeQuery("SELECT doc FROM FILES WHERE name = 'csv_file'"); byte buff[] = new byte[1024]; while (rs.next()) { Blob ablob = rs.getBlob(1); File newFile = new File(getBaseDirectory() + "/target/order_line_500K.csv"); if (newFile.exists()) { newFile.delete(); } newFile.createNewFile(); InputStream is = ablob.getBinaryStream(); FileOutputStream fos = new FileOutputStream(newFile); for (int b = is.read(buff); b != -1; b = is.read(buff)) { fos.write(buff, 0, b); } is.close(); fos.close(); } File file1 = new File(getResourceDirectory() + "order_line_500K.csv"); File file2 = new File(getBaseDirectory() + "/target/order_line_500K.csv"); Assert.assertTrue("The files contents are not equivalent", FileUtils.contentEquals(file1, file2)); }
From source file:org.apache.syncope.core.util.ImportExport.java
private String getValues(final ResultSet rs, final String columnName, final Integer columnType) throws SQLException { String res = null;/*ww w. jav a2s . co m*/ try { switch (columnType) { case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: final InputStream is = rs.getBinaryStream(columnName); if (is != null) { res = new String(Hex.encode(IOUtils.toByteArray(is))); } break; case Types.BLOB: final Blob blob = rs.getBlob(columnName); if (blob != null) { res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream()))); } break; case Types.BIT: case Types.BOOLEAN: if (rs.getBoolean(columnName)) { res = "1"; } else { res = "0"; } break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnName); if (timestamp != null) { res = DATE_FORMAT.get().format(new Date(timestamp.getTime())); } break; default: res = rs.getString(columnName); } } catch (IOException e) { LOG.error("Error retrieving hexadecimal string", e); } return res; }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected byte[] readBytes(Integer columnIndex) throws SQLException, IOException { InputStream is = null;/*from www .ja v a 2 s. com*/ long size = -1; int columnType = resultSet.getMetaData().getColumnType(columnIndex); switch (columnType) { case Types.BLOB: Blob blob = resultSet.getBlob(columnIndex); if (!resultSet.wasNull()) { is = blob.getBinaryStream(); size = blob.length(); } break; default: is = resultSet.getBinaryStream(columnIndex); if (resultSet.wasNull()) { is = null; } } byte[] bytes = null; if (is != null) { bytes = readBytes(is, size); } return bytes; }
From source file:com.hangum.tadpole.rdb.core.editors.main.composite.resultdetail.ResultTableComposite.java
/** * select table column to editor/*from w ww.j a v a 2 s. com*/ */ 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:com.p5solutions.core.json.JsonSerializer.java
protected void serializeBlob(Blob blob, OutputStream output, Charset charset) throws IOException { if (blob == null) { return;/*from w w w . j a v a2 s .co m*/ } try { output.write('"'); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(blob.getBinaryStream(), bos); IOUtils.copy(new ByteArrayInputStream(escape(new String(bos.toByteArray(), charset)).getBytes(charset)), output); output.write('"'); } catch (SQLException e) { throw new IOException("Cannot serialize the blob.", e); } }
From source file:com.sun.licenseserver.License.java
/** * Retrieve a license from the database that belongs to the given * userID, contentID and shopID combination. * /*from w w w .j a va 2 s. c om*/ * @param userID * @param contentID * @param shopID * @return * @throws LicenseServerException */ public static License getLicenseFromDatabase(String userID, String contentID, String shopID) throws LicenseServerException { m_log.finer("Entering Function.."); m_log.fine("Find license for user=[" + userID + "]contentID=[" + contentID + "]shopID=[" + shopID + "]"); ResultSet rs = null; License lic = null; Blob license = null; String id = ""; String mime = ""; String expression = "select license, id, mime from sunLsLicenses where contentId= '" + contentID + "' and shopId='" + shopID + "' and userId='" + userID + "'"; DatabaseHelper dbh = DatabaseHelper.getDatabaseHelper(); rs = dbh.executeStatementWithResults(expression); // The check below is not working. // We need to invoke the beforeFirst() function on the // result set after we have counted the number of entries in the result set. // The beforeFirst() method does not works and throws an exception. // A work around has to be found to reinstate this test. // // if (dbh.countNumberInResultSet(rs) > 1) { // m_log.severe("More than one license retrieved for a given userID, contentID and shopID combo"); // throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE, // "More than one license retrieved for a given userID, contentID and shopID combo"); // } try { if (rs != null && rs.next()) { ; license = rs.getBlob("license"); id = rs.getObject("id").toString(); mime = rs.getObject("mime").toString(); id = id == null ? "" : id; mime = mime == null ? "" : mime; lic = new License(id, userID, contentID, shopID, mime, license.getBinaryStream()); } dbh.releaseResultSetResources(rs); } catch (SQLException e) { m_log.severe("Error in retrieveing license from result set"); e.printStackTrace(); throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE, "Error in retrieveing license from result set"); } m_log.finer("Leaving Function.."); return lic; }
From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java
public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField, Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter) throws Exception { if (rs == null) { return 0; }/*w ww.j a v a 2 s . co m*/ int rowCounter = 0; Element docRoot = doc.getDocumentElement(); ResultSetMetaData metadata = rs.getMetaData(); buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter); boolean noKey = ((keyField == null) || keyField.isEmpty()); boolean isKeyCol = false; boolean isNull = false; Element data = null; Element row = null; Element col = null; Text text = null; String textVal = null; String precKey = null; String colKey = null; Map<String, Element> keyCols = new TreeMap<String, Element>(); while (rs.next()) { if (rowCounter % 10 == 0) { ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger); } row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS); parser.setAttribute(row, AbstractDBO.ID_NAME, id); for (int j = 1; j <= metadata.getColumnCount(); j++) { FieldFormatter fF = fFormatters[j]; String colName = colNames[j]; isKeyCol = (!noKey && keyField.contains(new Integer(j))); isNull = false; col = parser.createElementNS(doc, colName, NS); if (isKeyCol) { parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j)); } switch (metadata.getColumnType(j)) { case Types.DATE: case Types.TIME: case Types.TIMESTAMP: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE); Timestamp dateVal = rs.getTimestamp(j); isNull = dateVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT); textVal = ""; } else { if (fF != null) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat()); textVal = fF.formatDate(dateVal); } else { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT); textVal = dateFormatter.format(dateVal); } } } break; case Types.DOUBLE: case Types.FLOAT: case Types.REAL: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); float numVal = rs.getFloat(j); parser.setAttribute(col, AbstractDBO.NULL_NAME, "false"); if (fF != null) { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat()); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator()); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator()); textVal = fF.formatNumber(numVal); } else { parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator); textVal = numberFormatter.format(numVal); } } break; case Types.BIGINT: case Types.INTEGER: case Types.NUMERIC: case Types.SMALLINT: case Types.TINYINT: { BigDecimal bigdecimal = rs.getBigDecimal(j); isNull = bigdecimal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); } textVal = ""; } else { if (fF != null) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat()); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator()); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator()); textVal = fF.formatNumber(bigdecimal); } else if (metadata.getScale(j) > 0) { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE); parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat); parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator); parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator); textVal = numberFormatter.format(bigdecimal); } else { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE); textVal = bigdecimal.toString(); } } } break; case Types.NCHAR: case Types.NVARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE); textVal = rs.getNString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } break; case Types.CHAR: case Types.VARCHAR: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE); textVal = rs.getString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } break; case Types.NCLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE); NClob clob = rs.getNClob(j); isNull = clob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } } break; case Types.CLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE); Clob clob = rs.getClob(j); isNull = clob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { Reader is = clob.getCharacterStream(); StringWriter str = new StringWriter(); IOUtils.copy(is, str); is.close(); textVal = str.toString(); } } break; case Types.BLOB: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE); Blob blob = rs.getBlob(j); isNull = blob == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } else { InputStream is = blob.getBinaryStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); is.close(); try { byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length()); textVal = Base64.getEncoder().encodeToString(buffer); } catch (SQLFeatureNotSupportedException exc) { textVal = Base64.getEncoder().encodeToString(baos.toByteArray()); } } } break; default: { parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE); textVal = rs.getString(j); isNull = textVal == null; parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull)); if (isNull) { textVal = ""; } } } if (textVal != null) { text = doc.createTextNode(textVal); col.appendChild(text); } if (isKeyCol) { if (textVal != null) { if (colKey == null) { colKey = textVal; } else { colKey += "##" + textVal; } keyCols.put(String.valueOf(j), col); } } else { row.appendChild(col); } } if (noKey) { if (data == null) { data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS); parser.setAttribute(data, AbstractDBO.ID_NAME, id); } } else if ((colKey != null) && !colKey.equals(precKey)) { if (data != null) { docRoot.appendChild(data); } data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS); parser.setAttribute(data, AbstractDBO.ID_NAME, id); Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS); data.appendChild(key); for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) { key.appendChild(keyColsEntry.getValue()); } keyCols.clear(); precKey = colKey; } colKey = null; data.appendChild(row); rowCounter++; } if (data != null) { docRoot.appendChild(data); } return rowCounter; }
From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java
@Override public String getImportLog(int databaseId) throws DAOException { ArrayList<Object> params = new ArrayList<Object>(); params.add(Integer.valueOf(databaseId)); ResultSet rs = null;// w w w . java2s . c om Statement stmt = null; Connection conn = null; try { conn = getSQLConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(GET_IMPORT_LOG_SQL.replace("?", String.valueOf(databaseId))); if (rs.next()) { Blob blob = rs.getBlob(1); if (blob != null) { try { return blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream()); } catch (IOException e) { LOGGER.warn("Could not retreive import log of database #" + databaseId + ": " + e); return null; } } else { return null; } } else { return null; } } catch (SQLException e) { throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(rs); SQLUtil.close(stmt); SQLUtil.close(conn); } }
From source file:eionet.cr.dao.virtuoso.VirtuosoStagingDatabaseDAO.java
@Override public String getExportLog(int exportId) throws DAOException { ArrayList<Object> params = new ArrayList<Object>(); params.add(Integer.valueOf(exportId)); ResultSet rs = null;/* w w w .j a v a2 s. c o m*/ Statement stmt = null; Connection conn = null; try { conn = getSQLConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(GET_EXPORT_LOG_SQL.replace("?", String.valueOf(exportId))); if (rs.next()) { Blob blob = rs.getBlob(1); if (blob != null) { try { return blob.length() == 0 ? "" : IOUtils.toString(blob.getBinaryStream()); } catch (IOException e) { LOGGER.warn("Could not retreive log of the RDF export with id = " + exportId + ": " + e); return null; } } else { return null; } } else { return null; } } catch (SQLException e) { throw new DAOException(e.getMessage(), e); } finally { SQLUtil.close(rs); SQLUtil.close(stmt); SQLUtil.close(conn); } }