List of usage examples for java.sql Blob setBinaryStream
java.io.OutputStream setBinaryStream(long pos) throws SQLException;
From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java
/** * Insert a blob/* ww w.j av a2s . c o m*/ * * @throws Exception * it any Exception occurs */ public void insertLoopPrepStatement(Connection connection, int numberToInsert, File blobFile) throws Exception { // We can now use our Remote JDBC Connection as a regular Connection! connection.setAutoCommit(false); // We will do all our remote insert in a SQL Transaction try { String sql = "insert into orderlog values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )"; // Create a new Prepared Statement PreparedStatement prepStatement = null; MessageDisplayer.display(""); MessageDisplayer.display("Inserting " + numberToInsert + " orderlog..."); for (int customerId = 1; customerId < numberToInsert + 1; customerId++) { int i = 1; long theTime = new java.util.Date().getTime(); // We will insert a Blob (the image of the product). // The transfer will be done in streaming both on the client // and on the Servlet Server: we can upload/download very big // files. InputStream in = null; OutputStream out = null; try { in = new FileInputStream(blobFile); Blob blob = connection.createBlob(); out = blob.setBinaryStream(1); IOUtils.copy(in, out); prepStatement = connection.prepareStatement(sql); prepStatement.setInt(i++, customerId); prepStatement.setInt(i++, customerId); prepStatement.setString(i++, "Item Description No " + customerId); prepStatement.setBigDecimal(i++, new BigDecimal(customerId)); prepStatement.setDate(i++, new java.sql.Date(theTime)); prepStatement.setTimestamp(i++, new Timestamp(theTime)); prepStatement.setBlob(i++, blob); SqlUtil sqlUtil = new SqlUtil(connection); if (sqlUtil.isIngres()) { prepStatement.setInt(i++, 0); } else { prepStatement.setBoolean(i++, false); } prepStatement.setInt(i++, customerId); // SystemOutHandle.display("Before executeUpdate..."); prepStatement.executeUpdate(); // Close and free are important to delete temp files prepStatement.close(); blob.free(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } // We do either everything in a single transaction or nothing connection.commit(); // Commit is propagated on Server MessageDisplayer.display("Remote Commit Done on AceQL Server!"); } catch (Exception e) { connection.rollback(); throw e; } finally { connection.setAutoCommit(true); } }
From source file:org.opencms.db.oracle.CmsUserDriver.java
/** * Generates an Output stream that writes to a blob, also truncating the existing blob if required.<p> * /*from ww w.j a v a 2 s . c o m*/ * Apparently Oracle requires some non-standard handling here.<p> * * @param res the result set where the blob is located in * @param name the name of the database column where the blob is located * @return an Output stream from a blob * @throws SQLException if something goes wring */ @SuppressWarnings("deprecation") public static OutputStream getOutputStreamFromBlob(ResultSet res, String name) throws SQLException { // TODO: perform blob check only once and store Oracle version in a static private member // TODO: best do this during system startup / db init phase once Blob blob = res.getBlob(name); try { // jdbc standard blob.truncate(0); return blob.setBinaryStream(0L); } catch (SQLException e) { // oracle 9 & 8 (if using the same jdbc driver as provided by oracle9: ojdbc14.jar) ((oracle.sql.BLOB) blob).trim(0); return ((oracle.sql.BLOB) blob).getBinaryOutputStream(); } }
From source file:org.pentaho.di.jdbc.Support.java
/** * Convert an existing data object to the specified JDBC type. * * @param callerReference an object reference to the caller of this method; * must be a <code>Connection</code>, * <code>Statement</code> or <code>ResultSet</code> * @param x the data object to convert * @param jdbcType the required type constant from * <code>java.sql.Types</code> * @return the converted data object/*from ww w . j av a2s . c om*/ * @throws SQLException if the conversion is not supported or fails */ static Object convert(Object callerReference, Object x, int jdbcType, String charSet) throws SQLException { try { switch (jdbcType) { case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: if (x == null) { return INTEGER_ZERO; } else if (x instanceof Integer) { return x; } else if (x instanceof Byte) { return new Integer(((Byte) x).byteValue() & 0xFF); } else if (x instanceof Number) { return new Integer(((Number) x).intValue()); } else if (x instanceof String) { return new Integer(((String) x).trim()); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO; } break; case java.sql.Types.BIGINT: if (x == null) { return LONG_ZERO; } else if (x instanceof Long) { return x; } else if (x instanceof Byte) { return new Long(((Byte) x).byteValue() & 0xFF); } else if (x instanceof Number) { return new Long(((Number) x).longValue()); } else if (x instanceof String) { return new Long(((String) x).trim()); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO; } break; case java.sql.Types.REAL: if (x == null) { return FLOAT_ZERO; } else if (x instanceof Float) { return x; } else if (x instanceof Byte) { return new Float(((Byte) x).byteValue() & 0xFF); } else if (x instanceof Number) { return new Float(((Number) x).floatValue()); } else if (x instanceof String) { return new Float(((String) x).trim()); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO; } break; case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: if (x == null) { return DOUBLE_ZERO; } else if (x instanceof Double) { return x; } else if (x instanceof Byte) { return new Double(((Byte) x).byteValue() & 0xFF); } else if (x instanceof Number) { return new Double(((Number) x).doubleValue()); } else if (x instanceof String) { return new Double(((String) x).trim()); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO; } break; case java.sql.Types.NUMERIC: case java.sql.Types.DECIMAL: if (x == null) { return null; } else if (x instanceof BigDecimal) { return x; } else if (x instanceof Number) { return new BigDecimal(x.toString()); } else if (x instanceof String) { return new BigDecimal((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO; } break; case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: if (x == null) { return null; } else if (x instanceof String) { return x; } else if (x instanceof Number) { return x.toString(); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? "1" : "0"; } else if (x instanceof Clob) { Clob clob = (Clob) x; long length = clob.length(); if (length > Integer.MAX_VALUE) { throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000"); } return clob.getSubString(1, (int) length); } else if (x instanceof Blob) { Blob blob = (Blob) x; long length = blob.length(); if (length > Integer.MAX_VALUE) { throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000"); } x = blob.getBytes(1, (int) length); } if (x instanceof byte[]) { return toHex((byte[]) x); } return x.toString(); // Last hope! case java.sql.Types.BIT: case java.sql.Types.BOOLEAN: if (x == null) { return Boolean.FALSE; } else if (x instanceof Boolean) { return x; } else if (x instanceof Number) { return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE; } else if (x instanceof String) { String tmp = ((String) x).trim(); return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE; } break; case java.sql.Types.VARBINARY: case java.sql.Types.BINARY: if (x == null) { return null; } else if (x instanceof byte[]) { return x; } else if (x instanceof Blob) { Blob blob = (Blob) x; return blob.getBytes(1, (int) blob.length()); } else if (x instanceof Clob) { Clob clob = (Clob) x; long length = clob.length(); if (length > Integer.MAX_VALUE) { throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000"); } x = clob.getSubString(1, (int) length); } if (x instanceof String) { // // Strictly speaking this conversion is not required by // the JDBC standard but jTDS has always supported it. // if (charSet == null) { charSet = "ISO-8859-1"; } try { return ((String) x).getBytes(charSet); } catch (UnsupportedEncodingException e) { return ((String) x).getBytes(); } } else if (x instanceof UniqueIdentifier) { return ((UniqueIdentifier) x).getBytes(); } break; case java.sql.Types.TIMESTAMP: if (x == null) { return null; } else if (x instanceof DateTime) { return ((DateTime) x).toTimestamp(); } else if (x instanceof java.sql.Timestamp) { return x; } else if (x instanceof java.sql.Date) { return new java.sql.Timestamp(((java.sql.Date) x).getTime()); } else if (x instanceof java.sql.Time) { return new java.sql.Timestamp(((java.sql.Time) x).getTime()); } else if (x instanceof java.lang.String) { return java.sql.Timestamp.valueOf(((String) x).trim()); } break; case java.sql.Types.DATE: if (x == null) { return null; } else if (x instanceof DateTime) { return ((DateTime) x).toDate(); } else if (x instanceof java.sql.Date) { return x; } else if (x instanceof java.sql.Time) { return DATE_ZERO; } else if (x instanceof java.sql.Timestamp) { synchronized (cal) { cal.setTime((java.util.Date) x); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); // VM1.4+ only return new java.sql.Date(cal.getTimeInMillis()); return new java.sql.Date(cal.getTime().getTime()); } } else if (x instanceof java.lang.String) { return java.sql.Date.valueOf(((String) x).trim()); } break; case java.sql.Types.TIME: if (x == null) { return null; } else if (x instanceof DateTime) { return ((DateTime) x).toTime(); } else if (x instanceof java.sql.Time) { return x; } else if (x instanceof java.sql.Date) { return TIME_ZERO; } else if (x instanceof java.sql.Timestamp) { synchronized (cal) { // VM 1.4+ only cal.setTimeInMillis(((java.sql.Timestamp)x).getTime()); cal.setTime((java.util.Date) x); cal.set(Calendar.YEAR, 1970); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 1); // VM 1.4+ only return new java.sql.Time(cal.getTimeInMillis());*/ return new java.sql.Time(cal.getTime().getTime()); } } else if (x instanceof java.lang.String) { return java.sql.Time.valueOf(((String) x).trim()); } break; case java.sql.Types.OTHER: return x; case java.sql.Types.JAVA_OBJECT: throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)), "22005"); case java.sql.Types.LONGVARBINARY: case java.sql.Types.BLOB: if (x == null) { return null; } else if (x instanceof Blob) { return x; } else if (x instanceof byte[]) { return new BlobImpl(getConnection(callerReference), (byte[]) x); } else if (x instanceof Clob) { // // Convert CLOB to BLOB. Not required by the standard but we will // do it anyway. // Clob clob = (Clob) x; try { if (charSet == null) { charSet = "ISO-8859-1"; } Reader rdr = clob.getCharacterStream(); BlobImpl blob = new BlobImpl(getConnection(callerReference)); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(blob.setBinaryStream(1), charSet)); // TODO Use a buffer to improve performance int c; while ((c = rdr.read()) >= 0) { out.write(c); } out.close(); rdr.close(); return blob; } catch (UnsupportedEncodingException e) { // Unlikely to happen but fall back on in memory copy x = clob.getSubString(1, (int) clob.length()); } catch (IOException e) { throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()), "HY000"); } } if (x instanceof String) { // // Strictly speaking this conversion is also not required by // the JDBC standard but jTDS has always supported it. // BlobImpl blob = new BlobImpl(getConnection(callerReference)); String data = (String) x; if (charSet == null) { charSet = "ISO-8859-1"; } try { blob.setBytes(1, data.getBytes(charSet)); } catch (UnsupportedEncodingException e) { blob.setBytes(1, data.getBytes()); } return blob; } break; case java.sql.Types.LONGVARCHAR: case java.sql.Types.CLOB: if (x == null) { return null; } else if (x instanceof Clob) { return x; } else if (x instanceof Blob) { // // Convert BLOB to CLOB // Blob blob = (Blob) x; try { InputStream is = blob.getBinaryStream(); ClobImpl clob = new ClobImpl(getConnection(callerReference)); Writer out = clob.setCharacterStream(1); // TODO Use a buffer to improve performance int b; // These reads/writes are buffered by the undelying blob buffers while ((b = is.read()) >= 0) { out.write(hex[b >> 4]); out.write(hex[b & 0x0F]); } out.close(); is.close(); return clob; } catch (IOException e) { throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()), "HY000"); } } else if (x instanceof Boolean) { x = ((Boolean) x).booleanValue() ? "1" : "0"; } else if (!(x instanceof byte[])) { x = x.toString(); } if (x instanceof byte[]) { ClobImpl clob = new ClobImpl(getConnection(callerReference)); clob.setString(1, toHex((byte[]) x)); return clob; } else if (x instanceof String) { return new ClobImpl(getConnection(callerReference), (String) x); } break; default: throw new SQLException( BaseMessages.getString(PKG, "error.convert.badtypeconst", getJdbcTypeName(jdbcType)), "HY004"); } throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)), "22005"); } catch (NumberFormatException nfe) { throw new SQLException( BaseMessages.getString(PKG, "error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000"); } }
From source file:org.rhq.enterprise.server.content.ContentManagerBean.java
/** Takes an input stream and copies it into the PackageBits table using Hibernate * Blob mechanism with PreparedStatements. As all content into Bits are not stored as type OID, t * * @param stream//from ww w .j a v a 2s . c o m * @param contentDetails Map to store content details in used in PackageVersioning */ @SuppressWarnings("unused") public void updateBlobStream(InputStream stream, PackageBits bits, Map<String, String> contentDetails) { //TODO: are there any db specific limits that we should check/verify here before stuffing // the contents of a stream into the db? Should we just let the db complain and take care of // input validation? if (stream == null) { return; // no stream content to update. } bits = initializePackageBits(bits); //locate the existing PackageBitsBlob instance bits = entityManager.find(PackageBits.class, bits.getId()); PackageBitsBlob blob = bits.getBlob(); //Create prepared statements to work with Blobs and hibernate. Connection conn = null; PreparedStatement ps = null; PreparedStatement ps2 = null; try { conn = dataSource.getConnection(); //we are loading the PackageBits saved in the previous step //we need to lock the row which will be updated so we are using FOR UPDATE ps = conn.prepareStatement("SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE"); ps.setInt(1, bits.getId()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { //We can not create a blob directly because BlobImpl from Hibernate is not acceptable //for oracle and Connection.createBlob is not working on postgres. //This blob will be not empty because we saved there PackageBits.EMPTY_BLOB Blob blb = rs.getBlob(1); //copy the stream to the Blob long transferred = copyAndDigest(stream, blb.setBinaryStream(1), false, contentDetails); stream.close(); //populate the prepared statement for update ps2 = conn.prepareStatement("UPDATE " + PackageBits.TABLE_NAME + " SET bits = ? where id = ?"); ps2.setBlob(1, blb); ps2.setInt(2, bits.getId()); //initiate the update. if (ps2.execute()) { throw new Exception("Unable to upload the package bits to the DB:"); } ps2.close(); } } finally { rs.close(); } ps.close(); conn.close(); } catch (Exception e) { log.error("An error occurred while updating Blob with stream for PackageBits[" + bits.getId() + "], " + e.getMessage()); e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + bits.getId() + "]"); } } if (ps2 != null) { try { ps2.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + bits.getId() + "]"); } } if (conn != null) { try { conn.close(); } catch (Exception e) { log.warn("Failed to close connection for package bits [" + bits.getId() + "]"); } } if (stream != null) { try { stream.close(); } catch (Exception e) { log.warn("Failed to close stream to package bits located at [" + +bits.getId() + "]"); } } } // not sure this merge (or others like it in this file are necessary... entityManager.merge(bits); entityManager.flush(); }
From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java
@RequiredPermission(Permission.MANAGE_REPOSITORIES) @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionTimeout(90 * 60)/*from w w w . ja va2 s . c o m*/ public PackageBits downloadPackageBits(Subject subject, PackageVersionContentSource pvcs) { PackageVersionContentSourcePK pk = pvcs.getPackageVersionContentSourcePK(); int contentSourceId = pk.getContentSource().getId(); int packageVersionId = pk.getPackageVersion().getId(); String packageVersionLocation = pvcs.getLocation(); switch (pk.getContentSource().getDownloadMode()) { case NEVER: { return null; // no-op, our content source was told to never download package bits } case DATABASE: { log.debug("Downloading package bits to DB for package located at [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); break; } case FILESYSTEM: { log.debug("Downloading package bits to filesystem for package located at [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); break; } default: { throw new IllegalStateException(" Unknown download mode - this is a bug, please report it: " + pvcs); } } InputStream bitsStream = null; PackageBits packageBits = null; try { ContentServerPluginContainer pc = ContentManagerHelper.getPluginContainer(); bitsStream = pc.getAdapterManager().loadPackageBits(contentSourceId, packageVersionLocation); Connection conn = null; PreparedStatement ps = null; PreparedStatement ps2 = null; try { packageBits = createPackageBits(pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE); PackageVersion pv = entityManager.find(PackageVersion.class, packageVersionId); pv.setPackageBits(packageBits); // associate the entities entityManager.flush(); // may not be necessary if (pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE) { conn = dataSource.getConnection(); // The blob has been initialized to EMPTY_BLOB already by createPackageBits... // we need to lock the row which will be updated so we are using FOR UPDATE ps = conn.prepareStatement( "SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE"); ps.setInt(1, packageBits.getId()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { //We can not create a blob directly because BlobImpl from Hibernate is not acceptable //for oracle and Connection.createBlob is not working on postgres. //This blob will be not empty because we saved there a bytes from String("a"). Blob blb = rs.getBlob(1); StreamUtil.copy(bitsStream, blb.setBinaryStream(1), true); ps2 = conn.prepareStatement( "UPDATE " + PackageBits.TABLE_NAME + " SET bits = ? where id = ?"); ps2.setBlob(1, blb); ps2.setInt(2, packageBits.getId()); if (ps2.execute()) { throw new Exception("Did not download the package bits to the DB for "); } ps2.close(); } } finally { rs.close(); } ps.close(); conn.close(); } else { // store content to local file system File outputFile = getPackageBitsLocalFileAndCreateParentDir(pv.getId(), pv.getFileName()); log.info("OutPutFile is located at: " + outputFile); boolean download = false; if (outputFile.exists()) { // hmmm... it already exists, maybe we already have it? // if the MD5's match, just ignore this download request and continue on // If they are different we re-download String expectedMD5 = (pv.getMD5() != null) ? pv.getMD5() : "<unspecified MD5>"; String actualMD5 = MessageDigestGenerator.getDigestString(outputFile); if (!expectedMD5.trim().toLowerCase().equals(actualMD5.toLowerCase())) { log.error("Already have package bits for [" + pv + "] located at [" + outputFile + "] but the MD5 hashcodes do not match. Expected MD5=[" + expectedMD5 + "], Actual MD5=[" + actualMD5 + "] - redownloading package"); download = true; } else { log.info("Asked to download package bits but we already have it at [" + outputFile + "] with matching MD5 of [" + actualMD5 + "]"); download = false; } } else { download = true; } if (download) { StreamUtil.copy(bitsStream, new FileOutputStream(outputFile), true); bitsStream = null; } } } finally { if (ps != null) { try { ps.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } if (ps2 != null) { try { ps2.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } if (conn != null) { try { conn.close(); } catch (Exception e) { log.warn("Failed to close connection for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } } } catch (Throwable t) { // put the cause in here using ThrowableUtil because it'll dump SQL nextException messages too throw new RuntimeException("Did not download the package bits for [" + pvcs + "]. Cause: " + ThrowableUtil.getAllMessages(t), t); } finally { if (bitsStream != null) { try { bitsStream.close(); } catch (Exception e) { log.warn("Failed to close stream to package bits located at [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } } return packageBits; }
From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @TransactionTimeout(40 * 60)/* ww w . ja va 2 s . co m*/ private PackageBits preparePackageBits(Subject subject, InputStream bitsStream, PackageVersionContentSource pvcs) { PackageVersionContentSourcePK pk = pvcs.getPackageVersionContentSourcePK(); int contentSourceId = pk.getContentSource().getId(); int packageVersionId = pk.getPackageVersion().getId(); String packageVersionLocation = pvcs.getLocation(); PackageBits packageBits = null; try { Connection conn = null; PreparedStatement ps = null; PreparedStatement ps2 = null; try { packageBits = createPackageBits(pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE); PackageVersion pv = entityManager.find(PackageVersion.class, packageVersionId); pv.setPackageBits(packageBits); // associate entities entityManager.flush(); // not sure this is necessary if (pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE) { packageBits = entityManager.find(PackageBits.class, packageBits.getId()); conn = dataSource.getConnection(); //we are loading the PackageBits saved in the previous step //we need to lock the row which will be updated so we are using FOR UPDATE ps = conn.prepareStatement( "SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE"); ps.setInt(1, packageBits.getId()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { //We can not create a blob directly because BlobImpl from Hibernate is not acceptable //for oracle and Connection.createBlob is not working on postgres. //This blob will be not empty because we saved there a bytes from String("a"). Blob blb = rs.getBlob(1); StreamUtil.copy(bitsStream, blb.setBinaryStream(1), false); bitsStream.close(); ps2 = conn.prepareStatement( "UPDATE " + PackageBits.TABLE_NAME + " SET bits = ? where id = ?"); ps2.setBlob(1, blb); ps2.setInt(2, packageBits.getId()); if (ps2.execute()) { throw new Exception("Did not download the package bits to the DB for "); } ps2.close(); } } finally { rs.close(); } ps.close(); conn.close(); } else { //CONTENT IS ALLREADY LOADED } } finally { if (ps != null) { try { ps.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } if (ps2 != null) { try { ps2.close(); } catch (Exception e) { log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } if (conn != null) { try { conn.close(); } catch (Exception e) { log.warn("Failed to close connection for package bits [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } } } catch (Throwable t) { // put the cause in here using ThrowableUtil because it'll dump SQL nextException messages too throw new RuntimeException("Did not download the package bits for [" + pvcs + "]. Cause: " + ThrowableUtil.getAllMessages(t), t); } finally { if (bitsStream != null) { try { bitsStream.close(); } catch (Exception e) { log.warn("Failed to close stream to package bits located at [" + packageVersionLocation + "] on content source [" + contentSourceId + "]"); } } } return packageBits; }
From source file:org.springframework.jdbc.support.lob.TemporaryLobCreator.java
@Override public void setBlobAsBinaryStream(PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength) throws SQLException { if (binaryStream != null) { Blob blob = ps.getConnection().createBlob(); try {/*from ww w . ja v a 2 s .c o m*/ FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); } catch (IOException ex) { throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); } this.temporaryBlobs.add(blob); ps.setBlob(paramIndex, blob); } else { ps.setBlob(paramIndex, (Blob) null); } if (logger.isDebugEnabled()) { logger.debug( binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength : "Set BLOB to null"); } }
From source file:org.xsystem.sql2.dml.DmlCommand.java
Blob setBlob(Connection con, byte[] data) throws SQLException { Blob myBlob = con.createBlob(); OutputStream os = myBlob.setBinaryStream(0); try {/*from ww w . j a v a 2 s . c om*/ IOUtils.write(data, os); os.flush(); return myBlob; } catch (IOException ex) { throw new SQLException(ex); } finally { Auxilary.close(os); } }
From source file:richtercloud.document.scanner.it.BlobStorageIT.java
@Test @Ignore//from ww w.j a v a2 s . c om //fails due to //``` //[EL Warning]: 2017-07-31 00:11:40.03--UnitOfWork(178575564)--Exception [EclipseLink-32] (Eclipse Persistence Services - 2.6.4.v20160829-44060b6): org.eclipse.persistence.exceptions.DescriptorException //Exception Description: Trying to set value [[B@44550792] for instance variable [data] of type [java.sql.Blob] in the object. The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed. //Internal Exception: java.lang.IllegalArgumentException: Can not set java.sql.Blob field richtercloud.document.scanner.it.entities.EntityBlob.data to [B //Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[data-->ENTITYBLOB.DATA] //Descriptor: RelationalDescriptor(richtercloud.document.scanner.it.entities.EntityBlob --> [DatabaseTable(ENTITYBLOB)]) //``` public void testBlobStorage() throws IOException, SQLException, StorageConfValidationException, StorageCreationException, InterruptedException, StorageException, FieldOrderValidationException { LOGGER.info("testBlobStorage"); PersistenceStorage<Long> storage = null; try { IssueHandler issueHandler = new LoggerIssueHandler(LOGGER); Set<Class<?>> entityClasses = new HashSet<>(Arrays.asList(EntityImageWrapper.class)); File databaseDir = Files.createTempDirectory("document-scanner-blob-it").toFile(); FileUtils.forceDelete(databaseDir); //databaseDir mustn't exist for MySQL File schemeChecksumFile = File.createTempFile("document-scanner-blob-it", null); schemeChecksumFile.delete(); String persistenceUnitName = "document-scanner-it"; String username = "document-scanner"; String password = "document-scanner"; String databaseName = "document-scanner"; //Testing PostgreSQL doesn't make sense because it doesn't implement //java.sql.Connection.createBlob (see persistence.xml in //document-scanner) // PostgresqlAutoPersistenceStorageConf storageConf = new PostgresqlAutoPersistenceStorageConf(entityClasses, // username, // schemeChecksumFile, // databaseDir.getAbsolutePath()); //Apache Derby is extremely slow // DerbyEmbeddedPersistenceStorageConf storageConf = new DerbyEmbeddedPersistenceStorageConf(entityClasses, // databaseName, // schemeChecksumFile); File myCnfFile = File.createTempFile("document-scanner-it-blob-it", null); myCnfFile.delete(); //need to delete in order to trigger creation of //my.cnf MySQLAutoPersistenceStorageConf storageConf = new MySQLAutoPersistenceStorageConf(entityClasses, "localhost", //hostname username, databaseName, databaseDir.getAbsolutePath(), schemeChecksumFile); storageConf.setBaseDir( new File(DocumentScannerConf.CONFIG_DIR_DEFAULT, "mysql-5.7.16-linux-glibc2.5-x86_64") .getAbsolutePath()); storageConf.setMyCnfFilePath(myCnfFile.getAbsolutePath()); FieldRetriever fieldRetriever = new JPAOrderedCachedFieldRetriever( Constants.QUERYABLE_AND_EMBEDDABLE_CLASSES); storage = new MySQLAutoPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount issueHandler, fieldRetriever); storage.start(); long randomSeed = System.currentTimeMillis(); LOGGER.debug(String.format("random seed is %d", randomSeed)); Random random = new Random(randomSeed); int entityCount = 20; for (int i = 0; i < entityCount; i++) { int mbSize = random.nextInt(256); //256 MB max. int byteCount = 1024 * 1024 * mbSize; LOGGER.debug(String.format("generating %d MB random bytes", mbSize)); byte[] largeRandomBytes = new byte[byteCount]; random.nextBytes(largeRandomBytes); EntityManager entityManager = storage.retrieveEntityManager(); entityManager.getTransaction().begin(); Blob blob = entityManager.unwrap(Connection.class).createBlob(); OutputStream blobOutputStream = blob.setBinaryStream(1 //pos (begin //at 1) ); ByteArrayInputStream largeRandomBytesInputStream = new ByteArrayInputStream(largeRandomBytes); IOUtils.copy(largeRandomBytesInputStream, blobOutputStream); EntityBlob entity1 = new EntityBlob(blob); LOGGER.debug(String.format("storing large binary entity (%d of %d)", i, entityCount)); storage.store(entity1); entityManager.getTransaction().commit(); } //shutdown and restart storage in order to simulate persistence //across application starts storage.shutdown(); Thread.sleep(5000); //workaround for remaining storage process after shutdown storage = new MySQLAutoPersistenceStorage(storageConf, persistenceUnitName, 1, //parallelQueryCount issueHandler, fieldRetriever); storage.start(); LOGGER.debug("querying large binary entity"); List<EntityBlob> queryResults = storage.runQueryAll(EntityBlob.class); LOGGER.debug(String.format("query completed with %d results", queryResults.size())); int i = 0; for (EntityBlob queryResult : queryResults) { int mbSize = (int) (queryResult.getData().length() / 1024 / 1024); LOGGER.debug(String.format("query result %d has length %d bytes", i, mbSize)); i++; } } finally { if (storage != null) { storage.shutdown(); } } }