Example usage for java.sql ResultSet getBinaryStream

List of usage examples for java.sql ResultSet getBinaryStream

Introduction

In this page you can find the example usage for java.sql ResultSet getBinaryStream.

Prototype

java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a stream of uninterpreted bytes.

Usage

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

private InputStream getContentArchived(int contentID) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;// ww w .j a  v  a2 s . c  o m
    try {

        String resourceContentSQL = "SELECT REG_CONTENT_DATA  FROM  REG_CONTENT_HISTORY WHERE "
                + "REG_CONTENT_ID = ? AND REG_TENANT_ID=?";
        ps = conn.prepareStatement(resourceContentSQL);
        ps.setLong(1, contentID);
        ps.setInt(2, CurrentSession.getTenantId());
        result = ps.executeQuery();
        if (result.next()) {
            InputStream rawStream = result.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD);
            if (rawStream != null) {
                return RegistryUtils.getMemoryStream(rawStream);
            }
        }
    } catch (SQLException e) {

        String msg = "Failed to get the archived content " + contentID + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return null;
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClient.java

private Map<String, Object> internalGet(String keySpace, String columnFamily, String rid)
        throws StorageClientException {
    ResultSet body = null;
    Map<String, Object> result = Maps.newHashMap();
    PreparedStatement selectStringRow = null;
    try {/*from   w w  w .ja  v  a  2s  .c  o m*/
        selectStringRow = getStatement(keySpace, columnFamily, SQL_BLOCK_SELECT_ROW, rid, null);
        inc("A");
        selectStringRow.clearWarnings();
        selectStringRow.clearParameters();
        selectStringRow.setString(1, rid);
        body = selectStringRow.executeQuery();
        inc("B");
        if (body.next()) {
            Types.loadFromStream(rid, result, body.getBinaryStream(1), columnFamily);
        }
    } catch (SQLException e) {
        LOGGER.warn("Failed to perform get operation on  " + keySpace + ":" + columnFamily + ":" + rid, e);
        if (passivate != null) {
            LOGGER.warn("Was Pasivated ", passivate);
        }
        if (closed != null) {
            LOGGER.warn("Was Closed ", closed);
        }
        throw new StorageClientException(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.warn("Failed to perform get operation on  " + keySpace + ":" + columnFamily + ":" + rid, e);
        if (passivate != null) {
            LOGGER.warn("Was Pasivated ", passivate);
        }
        if (closed != null) {
            LOGGER.warn("Was Closed ", closed);
        }
        throw new StorageClientException(e.getMessage(), e);
    } finally {
        close(body, "B");
        close(selectStringRow, "A");
    }
    return result;
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public VersionRetriever getVersionList(long snapshotID) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;//from   www  .ja  va2s .  c om
    VersionRetriever versionRetriever = null;
    try {
        String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT WHERE "
                + "REG_SNAPSHOT_ID=? AND REG_TENANT_ID=?";
        ps = conn.prepareStatement(sql);
        ps.setLong(1, snapshotID);
        ps.setInt(2, CurrentSession.getTenantId());

        result = ps.executeQuery();

        if (result.next()) {
            InputStream resourceVIDStream = RegistryUtils
                    .getMemoryStream(result.getBinaryStream(DatabaseConstants.RESOURCE_VIDS_FIELD));
            versionRetriever = new VersionRetriever(resourceVIDStream);
        }
    } catch (Exception e) {

        String msg = "Failed to get version of the snapshot " + snapshotID + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return versionRetriever;
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceVersionDAO.java

public VersionRetriever getVersionList(long snapshotID) throws RepositoryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;//w w  w .  j  a  v a  2  s .c o m
    VersionRetriever versionRetriever = null;

    try {
        String sql = "SELECT REG_PATH_ID, REG_RESOURCE_VIDS FROM REG_SNAPSHOT WHERE "
                + "REG_SNAPSHOT_ID=? AND REG_TENANT_ID=?";
        ps = conn.prepareStatement(sql);
        ps.setLong(1, snapshotID);
        ps.setInt(2, CurrentContext.getTenantId());

        result = ps.executeQuery();

        if (result.next()) {
            InputStream resourceVIDStream = RepositoryUtils
                    .getMemoryStream(result.getBinaryStream(DatabaseConstants.RESOURCE_VIDS_FIELD));
            versionRetriever = new VersionRetriever(resourceVIDStream);
        }
    } catch (Exception e) {
        String msg = "Failed to get version of the snapshot " + snapshotID + ". " + e.getMessage();
        log.error(msg, e);
        throw new RepositoryDBException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                if (ps != null) {
                    ps.close();
                }
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
    return versionRetriever;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java

/**
 * {@inheritDoc}//from   w  w  w.  j  av a  2 s  .  c o m
 */
public synchronized NodeReferences load(NodeReferencesId targetId)
        throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    ResultSet rs = null;
    InputStream in = null;
    try {
        Statement stmt = connectionManager.executeStmt(nodeReferenceSelectSQL,
                getKey(targetId.getTargetId().getUUID()));
        rs = stmt.getResultSet();
        if (!rs.next()) {
            throw new NoSuchItemStateException(targetId.toString());
        }

        in = rs.getBinaryStream(1);
        NodeReferences refs = new NodeReferences(targetId);
        Serializer.deserialize(refs, in);

        return refs;
    } catch (Exception e) {
        if (e instanceof NoSuchItemStateException) {
            throw (NoSuchItemStateException) e;
        }
        String msg = "failed to read references: " + targetId;
        log.error(msg, e);
        throw new ItemStateException(msg, e);
    } finally {
        IOUtils.closeQuietly(in);
        closeResultSet(rs);
    }
}

From source file:org.wso2.carbon.repository.core.jdbc.dao.JDBCResourceVersionDAO.java

public void fillResourceContentArchived(ResourceImpl resourceImpl) throws RepositoryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result1 = null;
    PreparedStatement ps1 = null;

    try {// w  w  w.  java 2s. c  om
        String resourceContentSQL = "SELECT REG_CONTENT_DATA FROM REG_CONTENT_HISTORY WHERE "
                + "REG_CONTENT_ID = ? AND REG_TENANT_ID=?";
        ps1 = conn.prepareStatement(resourceContentSQL);
        int contentId = resourceImpl.getDbBasedContentID();
        ps1.setInt(1, contentId);
        ps1.setInt(2, CurrentContext.getTenantId());
        result1 = ps1.executeQuery();
        if (result1.next()) {
            resourceImpl.setContentStreamWithNoUpdate(RepositoryUtils
                    .getMemoryStream(result1.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD)));
        }
    } catch (SQLException ex) {
        String msg = "Failed in filling resource content for resource " + resourceImpl.getPath()
                + ex.getMessage();
        log.error(msg, ex);
        throw new RepositoryDBException(msg, ex);
    } finally {
        try {
            try {
                if (result1 != null) {
                    result1.close();
                }
            } finally {
                if (ps1 != null) {
                    ps1.close();
                }
            }
        } catch (SQLException ex) {
            String msg = InternalConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCResourceVersionDAO.java

public void fillResourceContentArchived(ResourceImpl resourceImpl) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result1 = null;
    PreparedStatement ps1 = null;
    try {/*from   w  ww. j  a v  a2 s.co  m*/
        // we can't use the UNION sql operator as some databases (derby) doesn't support
        // UNION with BLOB data
        // first check the current resource table
        String resourceContentSQL = "SELECT REG_CONTENT_DATA FROM REG_CONTENT_HISTORY WHERE "
                + "REG_CONTENT_ID = ? AND REG_TENANT_ID=?";
        ps1 = conn.prepareStatement(resourceContentSQL);
        int contentId = resourceImpl.getDbBasedContentID();
        ps1.setInt(1, contentId);
        ps1.setInt(2, CurrentSession.getTenantId());
        result1 = ps1.executeQuery();
        if (result1.next()) {
            resourceImpl.setContentStreamWithNoUpdate(RegistryUtils
                    .getMemoryStream(result1.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD)));
        }
    } catch (SQLException ex) {
        String msg = "Failed in filling resource content for resource " + resourceImpl.getPath()
                + ex.getMessage();
        log.error(msg, ex);
        throw new RegistryException(msg, ex);
    } finally {
        try {
            try {
                if (result1 != null) {
                    result1.close();
                }
            } finally {
                if (ps1 != null) {
                    ps1.close();
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java

public SessionContextDO getSessionContextData(String key, String type) {
    if (!enablePersist) {
        return null;
    }/* w w w. ja v a  2s .  c  o m*/
    Connection connection = null;
    try {
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return null;
    }
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        if (StringUtils.isBlank(sqlSelect)) {
            if (connection.getMetaData().getDriverName().contains("MySQL")
                    || connection.getMetaData().getDriverName().contains("H2")) {
                sqlSelect = SQL_DESERIALIZE_OBJECT_MYSQL;
            } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                sqlSelect = SQL_DESERIALIZE_OBJECT_DB2SQL;
            } else if (connection.getMetaData().getDriverName().contains("MS SQL")
                    || connection.getMetaData().getDriverName().contains("Microsoft")) {
                sqlSelect = SQL_DESERIALIZE_OBJECT_MSSQL;
            } else if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
                sqlSelect = SQL_DESERIALIZE_OBJECT_POSTGRESQL;
            } else if (connection.getMetaData().getDriverName().contains("Informix")) {
                // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server"
                sqlSelect = SQL_DESERIALIZE_OBJECT_INFORMIX;
            } else {
                sqlSelect = SQL_DESERIALIZE_OBJECT_ORACLE;
            }
        }
        preparedStatement = connection.prepareStatement(sqlSelect);
        preparedStatement.setString(1, key);
        preparedStatement.setString(2, type);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            String operation = resultSet.getString(1);
            if ((OPERATION_STORE.equals(operation))) {
                return new SessionContextDO(key, type, getBlobObject(resultSet.getBinaryStream(2)),
                        new Timestamp(resultSet.getLong(3)));
            }
        }
    } catch (ClassNotFoundException | IOException | SQLException | IdentityApplicationManagementException e) {
        log.error("Error while retrieving session data", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, preparedStatement);
    }
    return null;
}

From source file:com.flexive.core.storage.genericSQL.GenericBinarySQLStorage.java

/**
 * Retrieve a File handle and mime type for a binary transit entry
 *
 * @param binary binary descriptor/*from w ww  .j a  va  2 s .  c  o m*/
 * @return BinaryTransitFileInfo containing a File handle and the detected mime type
 * @throws FxApplicationException on errors
 */
@SuppressWarnings({ "ThrowFromFinallyBlock" })
protected BinaryTransitFileInfo getBinaryTransitFileInfo(BinaryDescriptor binary)
        throws FxApplicationException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    File binaryTransitFile = null;
    InputStream in = null;
    FileOutputStream fos = null;
    String mimeType = "unknown";
    byte[] header = null;
    boolean inDB;
    try {
        inDB = EJBLookup.getConfigurationEngine().get(SystemParameters.BINARY_TRANSIT_DB);
    } catch (FxApplicationException e) {
        throw e.asRuntimeException();
    }
    if (inDB) {
        Connection con = null;
        try {
            con = Database.getNonTXDataSource().getConnection();
            ps = con.prepareStatement(BINARY_TRANSIT_HEADER);
            ps.setString(1, binary.getHandle());

            rs = ps.executeQuery();
            if (!rs.next()) {
                throw new FxApplicationException(LOG, "ex.content.binary.transitNotFound", binary.getHandle());
            }

            binaryTransitFile = File.createTempFile("FXBIN_", "_TEMP");
            in = rs.getBinaryStream(1);
            mimeType = rs.getString(2);
            if (rs.wasNull())
                mimeType = FxMimeType.UNKNOWN;
            fos = new FileOutputStream(binaryTransitFile);
            byte[] buffer = new byte[4096];
            int read;
            while ((read = in.read(buffer)) != -1) {
                if (header == null && read > 0) {
                    header = new byte[read > 48 ? 48 : read];
                    System.arraycopy(buffer, 0, header, 0, read > 48 ? 48 : read);
                }
                fos.write(buffer, 0, read);
            }
            fos.close();
            fos = null;
            in.close();
            in = null;
        } catch (FileNotFoundException e) {
            throw new FxApplicationException(e, "ex.content.binary.transitNotFound", binary.getHandle());
        } catch (IOException e) {
            throw new FxApplicationException(e, "ex.content.binary.IOError", binary.getHandle());
        } catch (SQLException e) {
            throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
        } finally {
            FxSharedUtils.close(fos, in);
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException e) {
                //noinspection ThrowFromFinallyBlock
                throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
            }
            Database.closeObjects(GenericBinarySQLStorage.class, con, ps);
        }
    } else {
        binaryTransitFile = FxBinaryUtils.getTransitFile(FxContext.get().getDivisionId(), binary.getHandle());
        if (binaryTransitFile != null) {
            Connection con = null;
            try {
                con = Database.getNonTXDataSource().getConnection();
                ps = con.prepareStatement(BINARY_TRANSIT_MIMETYPE);
                ps.setString(1, binary.getHandle());
                ResultSet rsMime = ps.executeQuery();
                if (rsMime != null && rsMime.next()) {
                    mimeType = rsMime.getString(1);
                    if (rsMime.wasNull())
                        mimeType = FxMimeType.UNKNOWN;
                }
                in = new FileInputStream(binaryTransitFile);
                header = new byte[48];
                if (in.read(header, 0, 48) < 48)
                    header = null;
            } catch (SQLException e) {
                throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
            } catch (IOException e) {
                throw new FxApplicationException(e, "ex.content.binary.IOError", binary.getHandle());
            } finally {
                Database.closeObjects(GenericBinarySQLStorage.class, con, ps);
                try {
                    in.close();
                } catch (IOException e) {
                    throw new FxApplicationException(e, "ex.content.binary.IOError", binary.getHandle());
                }
            }
        } else
            throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
    }
    if (header != null) {
        String detectedMimeType = FxMediaEngine.detectMimeType(header, binary.getName());
        if (!FxMimeType.UNKNOWN.equalsIgnoreCase(detectedMimeType))
            mimeType = detectedMimeType;
    }

    if (binaryTransitFile == null || !binaryTransitFile.exists())
        throw new FxApplicationException("ex.content.binary.transitNotFound", binary.getHandle());
    return new BinaryTransitFileInfo(binaryTransitFile, mimeType, inDB);
}

From source file:org.wso2.carbon.apimgt.core.dao.impl.PolicyDAOImpl.java

/**
 * Creates a Subscription Policy from the results set
 *
 * @param identifier policy id//  w  ww .ja  v a  2 s  . c  om
 * @param rs         {@link ResultSet} instance
 * @return {@link SubscriptionPolicy} instance
 * @throws SQLException       if any error occurs while creating the Subscription Policy from the result set
 * @throws APIMgtDAOException if any error occurs while retrieving custom attributes for this Subscription Policy
 */
private SubscriptionPolicy createSubscriptionPolicyFromResultSet(String identifier, ResultSet rs)
        throws SQLException, APIMgtDAOException {

    SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(
            rs.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
    setCommonPolicyDetails(subscriptionPolicy, rs);
    InputStream binary = rs.getBinaryStream(APIMgtConstants.ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
    if (binary != null) {
        byte[] customAttrib;
        try {
            customAttrib = IOUtils.toByteArray(binary);
            if (customAttrib.length > 0) {
                subscriptionPolicy.setCustomAttributes(customAttrib);
            }
        } catch (IOException e) {
            String errorMsg = "An Error occurred while retrieving custom attributes for subscription policy with "
                    + "identifier: " + identifier;
            log.error(errorMsg, e);
            throw new APIMgtDAOException(errorMsg, e);
        }
    }
    return subscriptionPolicy;
}