List of usage examples for java.sql ResultSet getBlob
Blob getBlob(String columnLabel) throws SQLException;
ResultSet
object as a Blob
object in the Java programming language. From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java
/** * {@inheritDoc}//from w ww.j av a2 s. com */ public void checkConsistency(String[] uuids, boolean recursive, boolean fix) { log.info("{}: checking workspace consistency...", name); int count = 0; int total = 0; Collection modifications = new ArrayList(); if (uuids == null) { // get all node bundles in the database with a single sql statement, // which is (probably) faster than loading each bundle and traversing the tree ResultSet rs = null; DataInputStream din = null; try { String sql; if (getStorageModel() == SM_BINARY_KEYS) { sql = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE"; } else { sql = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE"; } Statement stmt = connectionManager.executeStmt(sql, new Object[0]); rs = stmt.getResultSet(); // iterate over all nodebundles in the db while (rs.next()) { NodeId id; Blob blob; if (getStorageModel() == SM_BINARY_KEYS) { id = new NodeId(new UUID(rs.getBytes(1))); blob = rs.getBlob(2); } else { id = new NodeId(new UUID(rs.getLong(1), rs.getLong(2))); blob = rs.getBlob(3); } din = new DataInputStream(blob.getBinaryStream()); try { // parse and check bundle // check bundle will log any problems itself if (binding.checkBundle(din)) { // reset stream for readBundle() din = new DataInputStream(blob.getBinaryStream()); NodePropBundle bundle = binding.readBundle(din, id); checkBundleConsistency(id, bundle, fix, modifications); } else { log.error("invalid bundle '" + id + "', see previous BundleBinding error log entry"); } } catch (Exception e) { log.error("Error in bundle " + id + ": " + e); } count++; if (count % 1000 == 0) { log.info(name + ": checked " + count + " bundles..."); } } } catch (Exception e) { log.error("Error loading bundle", e); } finally { IOUtils.closeQuietly(din); closeResultSet(rs); total = count; } } else { // check only given uuids, handle recursive flag // 1) convert uuid array to modifiable list // 2) for each uuid do // a) load node bundle // b) check bundle, store any bundle-to-be-modified in collection // c) if recursive, add child uuids to list of uuids List uuidList = new ArrayList(uuids.length); // convert uuid string array to list of UUID objects for (int i = 0; i < uuids.length; i++) { try { uuidList.add(new UUID(uuids[i])); } catch (IllegalArgumentException e) { log.error("Invalid uuid for consistency check, skipping: '" + uuids[i] + "': " + e); } } // iterate over UUIDs (including ones that are newly added inside the loop!) for (int i = 0; i < uuidList.size(); i++) { final UUID uuid = (UUID) uuidList.get(i); try { // load the node from the database NodeId id = new NodeId(uuid); NodePropBundle bundle = loadBundle(id, true); if (bundle == null) { log.error("No bundle found for uuid '" + uuid + "'"); continue; } checkBundleConsistency(id, bundle, fix, modifications); if (recursive) { Iterator iter = bundle.getChildNodeEntries().iterator(); while (iter.hasNext()) { NodePropBundle.ChildNodeEntry entry = (NodePropBundle.ChildNodeEntry) iter.next(); uuidList.add(entry.getId().getUUID()); } } count++; if (count % 1000 == 0) { log.info(name + ": checked " + count + "/" + uuidList.size() + " bundles..."); } } catch (ItemStateException e) { // problem already logged (loadBundle called with logDetailedErrors=true) } } total = uuidList.size(); } // repair collected broken bundles if (consistencyFix && !modifications.isEmpty()) { log.info(name + ": Fixing " + modifications.size() + " inconsistent bundle(s)..."); Iterator iterator = modifications.iterator(); while (iterator.hasNext()) { NodePropBundle bundle = (NodePropBundle) iterator.next(); try { log.info(name + ": Fixing bundle '" + bundle.getId() + "'"); bundle.markOld(); // use UPDATE instead of INSERT storeBundle(bundle); } catch (ItemStateException e) { log.error(name + ": Error storing fixed bundle: " + e); } } } log.info(name + ": checked " + count + "/" + total + " bundles."); }
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 . ja va 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:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
private String getValueFromResultSet(int columnType, String column, ResultSet resultSet) throws SQLException { String paramValue;//from w ww . j a v a 2 s .com switch (columnType) { case Types.INTEGER: /* fall through */ case Types.TINYINT: /* fall through */ case Types.SMALLINT: paramValue = ConverterUtil.convertToString(resultSet.getInt(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.DOUBLE: paramValue = ConverterUtil.convertToString(resultSet.getDouble(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.VARCHAR: /* fall through */ case Types.CHAR: /* fall through */ case Types.CLOB: /* fall through */ case Types.LONGVARCHAR: paramValue = resultSet.getString(column); break; case Types.BOOLEAN: /* fall through */ case Types.BIT: paramValue = ConverterUtil.convertToString(resultSet.getBoolean(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.BLOB: Blob sqlBlob = resultSet.getBlob(column); if (sqlBlob != null) { paramValue = this.getBase64StringFromInputStream(sqlBlob.getBinaryStream()); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.BINARY: /* fall through */ case Types.LONGVARBINARY: /* fall through */ case Types.VARBINARY: InputStream binInStream = resultSet.getBinaryStream(column); if (binInStream != null) { paramValue = this.getBase64StringFromInputStream(binInStream); } else { paramValue = null; } break; case Types.DATE: Date sqlDate = resultSet.getDate(column); if (sqlDate != null) { paramValue = ConverterUtil.convertToString(sqlDate); } else { paramValue = null; } break; case Types.DECIMAL: /* fall through */ case Types.NUMERIC: BigDecimal bigDecimal = resultSet.getBigDecimal(column); if (bigDecimal != null) { paramValue = ConverterUtil.convertToString(bigDecimal); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.FLOAT: paramValue = ConverterUtil.convertToString(resultSet.getFloat(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.TIME: Time sqlTime = resultSet.getTime(column); if (sqlTime != null) { paramValue = this.convertToTimeString(sqlTime); } else { paramValue = null; } break; case Types.LONGNVARCHAR: /* fall through */ case Types.NCHAR: /* fall through */ case Types.NCLOB: /* fall through */ case Types.NVARCHAR: paramValue = resultSet.getNString(column); break; case Types.BIGINT: paramValue = ConverterUtil.convertToString(resultSet.getLong(column)); paramValue = resultSet.wasNull() ? null : paramValue; break; case Types.TIMESTAMP: Timestamp sqlTimestamp = resultSet.getTimestamp(column); if (sqlTimestamp != null) { paramValue = this.convertToTimestampString(sqlTimestamp); } else { paramValue = null; } paramValue = resultSet.wasNull() ? null : paramValue; break; /* handle all other types as strings */ default: paramValue = resultSet.getString(column); paramValue = resultSet.wasNull() ? null : paramValue; break; } return paramValue; }
From source file:org.sakaiproject.db.impl.BasicSqlService.java
/** * Read a single field BLOB from the db from one record, and update it's bytes with content. * // w ww .j ava2s . c om * @param sql * The sql statement to select the BLOB. * @param content * The new bytes for the BLOB. */ public void dbReadBlobAndUpdate(String sql, byte[] content) { // Note: does not support TRANSACTION_CONNECTION -ggolden if (LOG.isDebugEnabled()) { LOG.debug("dbReadBlobAndUpdate(String " + sql + ", byte[] " + Arrays.toString(content) + ")"); } if (!sqlServiceSql.canReadAndUpdateBlob()) { throw new UnsupportedOperationException( "BasicSqlService.dbReadBlobAndUpdate() is not supported by the " + getVendor() + " database."); } // for DEBUG long start = 0; long connectionTime = 0; int lenRead = 0; if (LOG.isDebugEnabled()) { String userId = usageSessionService().getSessionId(); LOG.debug("Sql.dbReadBlobAndUpdate(): " + userId + "\n" + sql); } Connection conn = null; Statement stmt = null; ResultSet result = null; ResultSetMetaData meta = null; Object blob = null; OutputStream os = null; try { if (m_showSql) start = System.currentTimeMillis(); conn = borrowConnection(); if (m_showSql) connectionTime = System.currentTimeMillis() - start; if (m_showSql) start = System.currentTimeMillis(); stmt = conn.createStatement(); result = stmt.executeQuery(sql); if (result.next()) { blob = result.getBlob(1); } if (blob != null) { // %%% not supported? b.truncate(0); // int len = b.setBytes(0, content); try { // Use reflection to remove compile time dependency on oracle driver Class[] paramsClasses = new Class[0]; Method getBinaryOutputStreamMethod = blob.getClass().getMethod("getBinaryOutputStream", paramsClasses); Object[] params = new Object[0]; os = (OutputStream) getBinaryOutputStreamMethod.invoke(blob, params); os.write(content); } catch (NoSuchMethodException ex) { LOG.warn("Oracle driver error: " + ex); } catch (IllegalAccessException ex) { LOG.warn("Oracle driver error: " + ex); } catch (InvocationTargetException ex) { LOG.warn("Oracle driver error: " + ex); } catch (IOException e) { LOG.warn("Oracle driver error: " + e); } } } catch (SQLException e) { LOG.warn("Sql.dbReadBlobAndUpdate(): " + e); } finally { if (null != os) { try { os.close(); } catch (IOException e) { LOG.warn("Sql.dbRead(): " + e); } } if (null != result) { try { result.close(); } catch (SQLException e) { LOG.warn("Sql.dbRead(): " + e); } } if (null != stmt) { try { stmt.close(); } catch (SQLException e) { LOG.warn("Sql.dbRead(): " + e); } } if (null != conn) { // if we commit on read if (m_commitAfterRead) { try { conn.commit(); } catch (SQLException e) { LOG.warn("Sql.dbRead(): " + e); } } returnConnection(conn); } } if (m_showSql) debug("sql dbReadBlobAndUpdate: len: " + lenRead + " time: " + connectionTime + " / " + (System.currentTimeMillis() - start), sql, null); }
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//from w ww . j a v a 2 s .c o m * @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:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Truncates a blob by the specified length. * * @param table//from w ww .j av a 2s .c o m * @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:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Sets the value of this blob as the specified bytes. * * @param table/*from w w w.jav a 2s . com*/ * @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.streamsets.pipeline.lib.jdbc.JdbcUtil.java
public Field resultToField(ResultSetMetaData md, ResultSet rs, int columnIndex, int maxClobSize, int maxBlobSize, DataType userSpecifiedType, UnknownTypeAction unknownTypeAction, boolean timestampToString) throws SQLException, IOException, StageException { Field field;/* www. ja v a 2s . c o m*/ if (userSpecifiedType != DataType.USE_COLUMN_TYPE) { // If user specifies the data type, overwrite the column type returned by database. field = Field.create(Field.Type.valueOf(userSpecifiedType.getLabel()), rs.getObject(columnIndex)); } else { // All types as of JDBC 2.0 are here: // https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.sql.Types.ARRAY // Good source of recommended mappings is here: // http://www.cs.mun.ca/java-api-1.5/guide/jdbc/getstart/mapping.html switch (md.getColumnType(columnIndex)) { case Types.BIGINT: field = Field.create(Field.Type.LONG, rs.getObject(columnIndex)); break; case Types.BINARY: case Types.LONGVARBINARY: case Types.VARBINARY: field = Field.create(Field.Type.BYTE_ARRAY, rs.getBytes(columnIndex)); break; case Types.BIT: case Types.BOOLEAN: field = Field.create(Field.Type.BOOLEAN, rs.getObject(columnIndex)); break; case Types.CHAR: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: case Types.NCHAR: case Types.NVARCHAR: case Types.VARCHAR: field = Field.create(Field.Type.STRING, rs.getObject(columnIndex)); break; case Types.CLOB: case Types.NCLOB: field = Field.create(Field.Type.STRING, getClobString(rs.getClob(columnIndex), maxClobSize)); break; case Types.BLOB: field = Field.create(Field.Type.BYTE_ARRAY, getBlobBytes(rs.getBlob(columnIndex), maxBlobSize)); break; case Types.DATE: field = Field.create(Field.Type.DATE, rs.getDate(columnIndex)); break; case Types.DECIMAL: case Types.NUMERIC: field = Field.create(Field.Type.DECIMAL, rs.getBigDecimal(columnIndex)); field.setAttribute(HeaderAttributeConstants.ATTR_SCALE, String.valueOf(rs.getMetaData().getScale(columnIndex))); field.setAttribute(HeaderAttributeConstants.ATTR_PRECISION, String.valueOf(rs.getMetaData().getPrecision(columnIndex))); break; case Types.DOUBLE: field = Field.create(Field.Type.DOUBLE, rs.getObject(columnIndex)); break; case Types.FLOAT: case Types.REAL: field = Field.create(Field.Type.FLOAT, rs.getObject(columnIndex)); break; case Types.INTEGER: field = Field.create(Field.Type.INTEGER, rs.getObject(columnIndex)); break; case Types.ROWID: field = Field.create(Field.Type.STRING, rs.getRowId(columnIndex).toString()); break; case Types.SMALLINT: case Types.TINYINT: field = Field.create(Field.Type.SHORT, rs.getObject(columnIndex)); break; case Types.TIME: field = Field.create(Field.Type.TIME, rs.getObject(columnIndex)); break; case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnIndex); if (timestampToString) { field = Field.create(Field.Type.STRING, timestamp == null ? null : timestamp.toString()); } else { field = Field.create(Field.Type.DATETIME, timestamp); if (timestamp != null) { final long actualNanos = timestamp.getNanos() % NANOS_TO_MILLIS_ADJUSTMENT; if (actualNanos > 0) { field.setAttribute(FIELD_ATTRIBUTE_NANOSECONDS, String.valueOf(actualNanos)); } } } break; // Ugly hack until we can support LocalTime, LocalDate, LocalDateTime, etc. case Types.TIME_WITH_TIMEZONE: OffsetTime offsetTime = rs.getObject(columnIndex, OffsetTime.class); field = Field.create(Field.Type.TIME, Date.from(offsetTime.atDate(LocalDate.MIN).toInstant())); break; case Types.TIMESTAMP_WITH_TIMEZONE: OffsetDateTime offsetDateTime = rs.getObject(columnIndex, OffsetDateTime.class); field = Field.create(Field.Type.ZONED_DATETIME, offsetDateTime.toZonedDateTime()); break; //case Types.REF_CURSOR: // JDK8 only case Types.SQLXML: case Types.STRUCT: case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.NULL: case Types.OTHER: case Types.REF: default: if (unknownTypeAction == null) { return null; } switch (unknownTypeAction) { case STOP_PIPELINE: throw new StageException(JdbcErrors.JDBC_37, md.getColumnType(columnIndex), md.getColumnLabel(columnIndex)); case CONVERT_TO_STRING: Object value = rs.getObject(columnIndex); if (value != null) { field = Field.create(Field.Type.STRING, rs.getObject(columnIndex).toString()); } else { field = Field.create(Field.Type.STRING, null); } break; default: throw new IllegalStateException("Unknown action: " + unknownTypeAction); } } } return field; }
From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @TransactionTimeout(40 * 60)//from w ww. j a 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.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 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; }