List of usage examples for java.sql PreparedStatement setBlob
void setBlob(int parameterIndex, InputStream inputStream) throws SQLException;
InputStream
object. 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 w w w . j a v a 2 s . c om*/ * @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:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Truncates a blob by the specified length. * * @param table/*from w w w . ja v a2 s . c om*/ * @param columnName * @param id * @param length */ public void truncateBlob(String table, String columnName, String id, long length, Connection conn) { PreparedStatement prepared = null; Statement statement = null; ResultSet resultSet = null; try { // get the blob statement = conn.createStatement(); String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "' FOR UPDATE"; String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "'"; resultSet = statement.executeQuery(select); boolean resultSetFound = resultSet.next(); if (!resultSetFound) { return; } Blob blob = resultSet.getBlob(columnName); // null check if (blob != null) { blob.truncate(length); // modify the blob if (conn.getMetaData().locatorsUpdateCopy()) { // The current database needs to be manually updated (it doesn't // support auto blob updates) prepared = conn.prepareStatement(update); prepared.setBlob(1, blob); prepared.executeUpdate(); } } } catch (SQLException e) { this.throwDatabaseException(e); } finally { try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (prepared != null) prepared.close(); } catch (SQLException e) { this.throwDatabaseException(e); } } }
From source file:org.infoglue.cms.controllers.kernel.impl.simple.InstallationController.java
/** * This method issues special blob-inserts command to the db. * I had to build my own adoption of sql to make this feature. */// w ww . j av a2s . c om protected void issueSpecialBlobCommand(Connection conn, String originalSql) throws Exception { String sql = originalSql; //Logger.logInfo("SpecialBlob Command:" + sql); try { String valuesPart = sql.substring(sql.indexOf("VALUES") + 6).trim(); sql = sql.substring(0, sql.indexOf("VALUES") + 6); //logger.info("sql:" + sql); //logger.info("valuesPart:" + valuesPart); String tableName = null; int blobColumn = 0; List columns = null; List columnValues = null; StringTokenizer st = new StringTokenizer(sql, " "); int i = 0; while (st.hasMoreTokens()) { String part = st.nextToken(); //Logger.logInfo("Part: " + part); if (i == 1) blobColumn = new Integer(part).intValue(); if (i == 4) tableName = part; if (i == 5) { columns = parseColumns(part); } i++; } columnValues = parseValues(valuesPart); String columnsString = ""; String valuesString = ""; Iterator columnsIterator = columns.iterator(); while (columnsIterator.hasNext()) { columnsString += (columnsString.equals("")) ? (String) columnsIterator.next() : "," + columnsIterator.next(); valuesString += (valuesString.equals("")) ? "?" : ",?"; } sql = "INSERT INTO " + tableName + "(" + columnsString + ") VALUES (" + valuesString + ")"; PreparedStatement ps = conn.prepareStatement(sql); int index = 1; int loopCount = 0; Iterator columnValuesIterator = columnsIterator = columns.iterator(); while (columnsIterator.hasNext()) { columnsIterator.next(); String value = (String) columnValues.get(loopCount); if (index == 1 || value.indexOf("'") == -1) { ps.setInt(index, new Integer(value).intValue()); } else if (index == blobColumn) { //Logger.logInfo("value:" + value); value = value.substring(1, value.length() - 1); //Logger.logInfo("value:" + value); if (value.indexOf("assetBlob:") > -1) { String fileName = value.substring(10); FileInputStream fis = new FileInputStream(fileName); BLOB bl = BLOB.createTemporary(conn, true, BLOB.DURATION_CALL); bl.open(BLOB.MODE_READWRITE); BufferedOutputStream out = new BufferedOutputStream(bl.getBinaryOutputStream()); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) >= 0) out.write(buffer, 0, len); out.flush(); fis.close(); out.close(); ps.setBlob(index, bl); } else { CLOB cl = CLOB.createTemporary(conn, true, CLOB.DURATION_CALL); cl.putString(1, value); ps.setClob(index, cl); } } else if (value.indexOf("date:") > -1) { value = value.substring(6); Date date = parseDate(value, "yyyy-MM-dd HH:mm:ss"); ps.setDate(index, new java.sql.Date(date.getTime())); } else { //Logger.logInfo("value:" + value); value = value.substring(1, value.length() - 1); //Logger.logInfo("value:" + value); ps.setString(index, value); } index++; loopCount++; } ps.executeUpdate(); } catch (Exception ex) { logger.error("Command failed: " + ex.getMessage()); logger.error("SQL: " + originalSql); throw ex; } }
From source file:org.quartz.impl.jdbcjobstore.oracle.OracleDelegate.java
public int insertTrigger(Connection conn, Trigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException { byte[] data = null; if (trigger.getJobDataMap().size() > 0) { data = serializeJobData(trigger.getJobDataMap()).toByteArray(); }/*from w w w .j av a2s. co m*/ PreparedStatement ps = null; ResultSet rs = null; int insertResult = 0; try { ps = conn.prepareStatement(rtp(INSERT_TRIGGER)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); ps.setString(3, trigger.getJobName()); ps.setString(4, trigger.getJobGroup()); setBoolean(ps, 5, trigger.isVolatile()); ps.setString(6, trigger.getDescription()); ps.setBigDecimal(7, new BigDecimal(String.valueOf(trigger.getNextFireTime().getTime()))); long prevFireTime = -1; if (trigger.getPreviousFireTime() != null) { prevFireTime = trigger.getPreviousFireTime().getTime(); } ps.setBigDecimal(8, new BigDecimal(String.valueOf(prevFireTime))); ps.setString(9, state); if (trigger instanceof SimpleTrigger && ((SimpleTrigger) trigger).hasAdditionalProperties() == false) { ps.setString(10, TTYPE_SIMPLE); } else if (trigger instanceof CronTrigger && ((CronTrigger) trigger).hasAdditionalProperties() == false) { ps.setString(10, TTYPE_CRON); } else { ps.setString(10, TTYPE_BLOB); } ps.setBigDecimal(11, new BigDecimal(String.valueOf(trigger.getStartTime().getTime()))); long endTime = 0; if (trigger.getEndTime() != null) { endTime = trigger.getEndTime().getTime(); } ps.setBigDecimal(12, new BigDecimal(String.valueOf(endTime))); ps.setString(13, trigger.getCalendarName()); ps.setInt(14, trigger.getMisfireInstruction()); ps.setBinaryStream(15, null, 0); ps.setInt(16, trigger.getPriority()); insertResult = ps.executeUpdate(); if (data != null) { ps.close(); ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_EMPTY_BLOB)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement(rtp(SELECT_ORACLE_TRIGGER_JOB_DETAIL_BLOB)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); rs = ps.executeQuery(); int res = 0; Blob dbBlob = null; if (rs.next()) { dbBlob = writeDataToBlob(rs, 1, data); } else { return res; } rs.close(); ps.close(); ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_BLOB)); ps.setBlob(1, dbBlob); ps.setString(2, trigger.getName()); ps.setString(3, trigger.getGroup()); res = ps.executeUpdate(); } } finally { closeResultSet(rs); closeStatement(ps); } if (insertResult > 0) { String[] trigListeners = trigger.getTriggerListenerNames(); for (int i = 0; trigListeners != null && i < trigListeners.length; i++) { insertTriggerListener(conn, trigger, trigListeners[i]); } } return insertResult; }
From source file:org.quartz.impl.jdbcjobstore.oracle.OracleDelegate.java
public int updateTrigger(Connection conn, Trigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException { // save some clock cycles by unnecessarily writing job data blob ... boolean updateJobData = trigger.getJobDataMap().isDirty(); byte[] data = null; if (updateJobData && trigger.getJobDataMap().size() > 0) { data = serializeJobData(trigger.getJobDataMap()).toByteArray(); }/*from w w w .j ava 2 s. c om*/ PreparedStatement ps = null; PreparedStatement ps2 = null; ResultSet rs = null; int insertResult = 0; try { ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER)); ps.setString(1, trigger.getJobName()); ps.setString(2, trigger.getJobGroup()); setBoolean(ps, 3, trigger.isVolatile()); ps.setString(4, trigger.getDescription()); long nextFireTime = -1; if (trigger.getNextFireTime() != null) { nextFireTime = trigger.getNextFireTime().getTime(); } ps.setBigDecimal(5, new BigDecimal(String.valueOf(nextFireTime))); long prevFireTime = -1; if (trigger.getPreviousFireTime() != null) { prevFireTime = trigger.getPreviousFireTime().getTime(); } ps.setBigDecimal(6, new BigDecimal(String.valueOf(prevFireTime))); ps.setString(7, state); if (trigger instanceof SimpleTrigger && ((SimpleTrigger) trigger).hasAdditionalProperties() == false) { // updateSimpleTrigger(conn, (SimpleTrigger)trigger); ps.setString(8, TTYPE_SIMPLE); } else if (trigger instanceof CronTrigger && ((CronTrigger) trigger).hasAdditionalProperties() == false) { // updateCronTrigger(conn, (CronTrigger)trigger); ps.setString(8, TTYPE_CRON); } else { // updateBlobTrigger(conn, trigger); ps.setString(8, TTYPE_BLOB); } ps.setBigDecimal(9, new BigDecimal(String.valueOf(trigger.getStartTime().getTime()))); long endTime = 0; if (trigger.getEndTime() != null) { endTime = trigger.getEndTime().getTime(); } ps.setBigDecimal(10, new BigDecimal(String.valueOf(endTime))); ps.setString(11, trigger.getCalendarName()); ps.setInt(12, trigger.getMisfireInstruction()); ps.setInt(13, trigger.getPriority()); ps.setString(14, trigger.getName()); ps.setString(15, trigger.getGroup()); insertResult = ps.executeUpdate(); if (updateJobData) { ps.close(); ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_EMPTY_BLOB)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement(rtp(SELECT_ORACLE_TRIGGER_JOB_DETAIL_BLOB)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); rs = ps.executeQuery(); int res = 0; if (rs.next()) { Blob dbBlob = writeDataToBlob(rs, 1, data); ps2 = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_BLOB)); ps2.setBlob(1, dbBlob); ps2.setString(2, trigger.getName()); ps2.setString(3, trigger.getGroup()); res = ps2.executeUpdate(); } } } finally { closeResultSet(rs); closeStatement(ps); closeStatement(ps2); } if (insertResult > 0) { deleteTriggerListeners(conn, trigger.getName(), trigger.getGroup()); String[] trigListeners = trigger.getTriggerListenerNames(); for (int i = 0; trigListeners != null && i < trigListeners.length; i++) { insertTriggerListener(conn, trigger, trigListeners[i]); } } return insertResult; }
From source file:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Sets the value of this blob as the specified bytes. * * @param table//from ww w . ja v a 2 s . c om * @param columnName * @param id * @param bytes * @return The number of bytes written. */ public int setBlobAsBytes(String table, String columnName, String id, byte[] bytes) { Connection conn = Database.getConnection(); PreparedStatement prepared = null; Statement statement = null; ResultSet resultSet = null; int written = 0; try { // get the blob statement = conn.createStatement(); String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "' FOR UPDATE"; String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "'"; resultSet = statement.executeQuery(select); boolean resultSetFound = resultSet.next(); if (!resultSetFound) { return 0; } Blob blob = resultSet.getBlob(columnName); // null check if (blob == null) { // add the bytes directly prepared = conn.prepareStatement(update); prepared.setBytes(1, bytes); prepared.executeUpdate(); written = bytes.length; } else { // modify the blob written = blob.setBytes(1, bytes); if (conn.getMetaData().locatorsUpdateCopy()) { // The current database needs to be manually updated (it doesn't // support auto blob updates) prepared = conn.prepareStatement(update); prepared.setBlob(1, blob); prepared.executeUpdate(); } } } catch (SQLException e) { this.throwDatabaseException(e); } finally { try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (prepared != null) prepared.close(); this.closeConnection(conn); } catch (SQLException e) { this.throwDatabaseException(e); } } return written; }
From source file:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Sets the value of this blob as the specified bytes. This method works the * same as the Blob.setBytes(long pos, byte[], int offset, int length) as * specified in the JDBC 3.0 API. Because of this, the first element in the * bytes to write to is actually element 1 (as opposed to the standard array * treatment where the first element is at position 0). * * @param table// w ww . j a va 2 s .c om * @param columnName * @param id * @param pos * @param bytes * @param offset * @param length * @return */ public int setBlobAsBytes(String table, String columnName, String id, long pos, byte[] bytes, int offset, int length) { Connection conn = Database.getConnection(); PreparedStatement prepared = null; Statement statement = null; ResultSet resultSet = null; int written = 0; try { // get the blob statement = conn.createStatement(); String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "' FOR UPDATE"; String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN + " = '" + id + "'"; resultSet = statement.executeQuery(select); resultSet.next(); Blob blob = resultSet.getBlob(columnName); // null check if (blob == null) { // because this method is used to place byte in specific positions, it // wouldn't // make sense to insert the bytes into a null field as it defeats the // purpose of // this method. Just return a write count of 0 and don't do anything // else. return written; } else { // modify the blob written = blob.setBytes(pos, bytes, offset, length); if (conn.getMetaData().locatorsUpdateCopy()) { // The current database needs to be manually updated (it doesn't // support auto blob updates) prepared = conn.prepareStatement(update); prepared.setBlob(1, blob); prepared.executeUpdate(); } } } catch (SQLException e) { this.throwDatabaseException(e); } finally { try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (prepared != null) prepared.close(); this.closeConnection(conn); } catch (SQLException e) { this.throwDatabaseException(e); } } return written; }
From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java
/** * Runs SQL Statement "UPDATE" on the given tableName with attribute values * and where clause./*from w w w . j a va 2 s. c o m*/ * * @param tableName * @param attributeNameValue * @param whereClause * @return * @throws SQLException */ public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType) throws SQLException { StringBuffer stmt = new StringBuffer(); PreparedStatement prepStmt = null; int rowsUpdated = 0; Object attribute = null; Iterator itr = null; String[] key = new String[attributeNameValue.size()]; int count = 0; stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET "); itr = attributeNameValue.keySet().iterator(); while (itr.hasNext()) { key[count] = (String) itr.next(); stmt.append(key[count++] + " = ?,"); } /* * for (int i = 0; i < attributeNames.size(); i++) { * stmt.append(attributeNames.get(i) + " = ?,"); } */ stmt = stmt.deleteCharAt(stmt.length() - 1); if (whereClause != null && !"".equals(whereClause)) { stmt.append(" WHERE "); stmt.append(whereClause); } // stmt = stmt.deleteCharAt(stmt.length()); log.debug("************ UPDATE QUERY ************"); log.debug(stmt.toString()); log.debug("**************************************"); try { String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString()); prepStmt = sqlConnection_.prepareStatement(statement); itr = attributeNameValue.keySet().iterator(); for (count = 0; count < key.length; count++) { attribute = attributeNameValue.get(key[count]); if (attribute instanceof String) { prepStmt.setString(count + 1, (String) attribute); } else if (attribute instanceof Blob) { prepStmt.setBlob(count + 1, (Blob) attribute); } else if (attribute instanceof Boolean) { prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue()); } else if (attribute instanceof Byte) { prepStmt.setByte(count + 1, ((Byte) attribute).byteValue()); } else if (attribute instanceof byte[]) { prepStmt.setBytes(count + 1, (byte[]) attribute); } else if (attribute instanceof Date) { prepStmt.setDate(count + 1, (Date) attribute); } else if (attribute instanceof Double) { prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue()); } else if (attribute instanceof Float) { prepStmt.setFloat(count + 1, ((Float) attribute).floatValue()); } else if (attribute instanceof Integer) { prepStmt.setInt(count + 1, ((Integer) attribute).intValue()); } else if (attribute instanceof Long) { prepStmt.setLong(count + 1, ((Long) attribute).longValue()); } else if (attribute instanceof Short) { prepStmt.setShort(count + 1, ((Short) attribute).shortValue()); } else if (attribute instanceof Timestamp) { prepStmt.setTimestamp(count + 1, (Timestamp) attribute); } } rowsUpdated = prepStmt.executeUpdate(); } catch (Exception e) { log.error("Exception @ updateRow: " + e.getMessage()); } finally { prepStmt.close(); } return rowsUpdated; }
From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java
@RequiredPermission(Permission.MANAGE_REPOSITORIES) @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionTimeout(90 * 60)/*w w w. j a v a 2 s . c om*/ 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)//from ww w . ja v a2s .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; }