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:nl.b3p.catalog.arcgis.ArcSDE9xJDBCHelper.java

@Override
public String getMetadata(ArcSDEJDBCDataset dataset) throws NamingException, SQLException, IOException {
    Connection c = getConnection();
    try {/*w w  w.ja va 2 s .  co m*/
        String sql = "select xml from " + getTableName(TABLE_USERMETADATA) + " where name = ? and owner = ?";
        sql += databaseNameSQL(dataset);

        ResultSetHandler<String> h = new ResultSetHandler<String>() {
            public String handle(ResultSet rs) throws SQLException {
                String xml = DocumentHelper.EMPTY_METADATA;
                if (rs.next()) {
                    try {
                        xml = IOUtils.toString(rs.getBinaryStream(1), ENCODING);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                return xml;
            }
        };
        if (dataset.getDatabaseName() != null) {
            return new QueryRunner().query(c, sql, h, dataset.getName(), dataset.getOwner(),
                    dataset.getDatabaseName());
        } else {
            return new QueryRunner().query(c, sql, h, dataset.getName(), dataset.getOwner());
        }
    } finally {
        DbUtils.closeQuietly(c);
    }

}

From source file:de.whs.poodle.repositories.FileRepository.java

public void writeFileToHttpResponse(int fileId, HttpServletResponse response) {
    jdbc.query("SELECT filename,mimetype,data FROM uploaded_file WHERE id = ?", new Object[] { fileId },

            // use ResultSetExtractor, so we can check whether the row even exists (NotFoundException)
            new ResultSetExtractor<Void>() {

                @Override//from w  w  w  . ja v a  2  s  . co  m
                public Void extractData(ResultSet rs) throws SQLException {
                    if (!rs.next())
                        throw new NotFoundException();

                    String filename = rs.getString("filename");
                    String mimeType = rs.getString("mimetype");

                    response.setHeader("Content-Disposition", "filename=\"" + filename + "\"");
                    response.setContentType(mimeType);

                    try (InputStream in = rs.getBinaryStream("data");
                            OutputStream out = response.getOutputStream();) {
                        StreamUtils.copy(in, out);
                        response.flushBuffer();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    return null;
                }
            });
}

From source file:com.nabla.wapp.report.server.StreamResolvingResourceLocator.java

@Override
public @Nullable URL findResource(@SuppressWarnings("unused") final ModuleHandle moduleHandle,
        final String fileName, final int type,
        @SuppressWarnings({ "rawtypes", "unused" }) final Map appContext) {
    if (log.isDebugEnabled())
        log.debug("requesting report resource '" + fileName + "' of type " + type);
    try {/*w  w w.j av  a  2  s.  co m*/
        final PreparedStatement stmt = StatementFormat.prepare(conn,
                "SELECT content" + " FROM report_resource" + " WHERE name=? AND report_id=?;", fileName,
                reportId);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isErrorEnabled())
                        log.error("fail to find report resource '" + fileName + "'");
                    return null;
                }
                try {
                    return new URL(null, "birtres://" + reportId + "//" + fileName,
                            getURLStreamHandler(rs.getBinaryStream(1)));
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("error generating URL to report resource '" + fileName + "'", e);
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled())
            log.error("fail to find report resource '" + fileName + "'", e);
    }
    return null;
}

From source file:org.apache.sandesha2.storage.jdbc.PersistentStorageManager.java

public MessageContext retrieveMessageContext(String key, ConfigurationContext configContext)
        throws SandeshaStorageException {
    log.debug("Enter retrieveMessageContext for key " + key);
    /**///  w  ww.java 2 s.c o  m
    if (storageMap.containsKey(key)) {
        log.debug("retrieveMessageContext get from cache");
        return (MessageContext) storageMap.get(key);
    }
    /**/
    try {
        Statement stmt = getDbConnection().createStatement();
        /**/
        ResultSet rs = stmt.executeQuery("select * from wsrm_msgctx where ctx_key='" + key + "'");
        rs.next();
        MessageContext msgCtx = new MessageContext();
        msgCtx.readExternal(new ObjectInputStream(rs.getBinaryStream("ctx")));
        msgCtx.activate(configContext);
        msgCtx.setProperty(Sandesha2Constants.POST_FAILURE_MESSAGE, Sandesha2Constants.VALUE_TRUE);
        rs.close();
        stmt.close();
        log.debug("RetrieveMessageContext get from DB");
        return msgCtx;
    } catch (Exception ex) {
        log.error("RetrieveMessageContext exception " + ex);
        throw new SandeshaStorageException(ex);
    }
}

From source file:com.nabla.wapp.report.server.ReportManager.java

public ReportTemplate open(final ResultSet rs, final IUserSessionContext ctx)
        throws SQLException, DispatchException {
    try {/* w  ww .  ja v a  2 s  . c o  m*/
        final Integer id = rs.getInt("id");
        return new ReportTemplate(id,
                engine.openReportDesign(rs.getString("name"), rs.getBinaryStream("content"),
                        new StreamResolvingResourceLocator(ctx.getReadConnection(), id)));
    } catch (EngineException e) {
        throw new InternalErrorException(Util.formatInternalErrorDescription(e));
    }
}

From source file:org.springframework.jdbc.support.lob.DefaultLobHandler.java

@Override
@Nullable/*from   www  .j a v a 2s.  c o  m*/
public InputStream getBlobAsBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning BLOB as binary stream");
    if (this.wrapAsLob) {
        Blob blob = rs.getBlob(columnIndex);
        return blob.getBinaryStream();
    } else {
        return rs.getBinaryStream(columnIndex);
    }
}

From source file:org.wso2.carbon.identity.core.DatabaseCertificateRetriever.java

/**
 * @param certificateId Database identifier of the certificate.
 * @param tenant        Tenant where the certificate belongs to. But in this implementation the passed tenant is
 *                      not considered since the database id is already there.
 * @return The certificate for the given database identifier.
 * @throws CertificateRetrievingException
 *///w  ww .jav a2s  .  co  m
@Override
public X509Certificate getCertificate(String certificateId, Tenant tenant)
        throws CertificateRetrievingException {

    Connection connection;
    try {
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        throw new CertificateRetrievingException("Couldn't get a database connection.", e);
    }

    PreparedStatement statementToGetApplicationCertificate = null;
    ResultSet queryResults = null;

    try {
        statementToGetApplicationCertificate = connection
                .prepareStatement(QUERY_TO_GET_APPLICATION_CERTIFICATE);
        statementToGetApplicationCertificate.setInt(1, Integer.parseInt(certificateId));

        queryResults = statementToGetApplicationCertificate.executeQuery();

        String certificateContent = null;
        while (queryResults.next()) {
            certificateContent = getBlobValue(queryResults.getBinaryStream(1));
        }

        if (StringUtils.isNotBlank(certificateContent)) {
            return (X509Certificate) IdentityUtil.convertPEMEncodedContentToCertificate(certificateContent);
        }
    } catch (SQLException e) {
        String errorMessage = String.format("An error occurred while retrieving the certificate content from "
                + "the database for the ID '%s'", certificateId);
        throw new CertificateRetrievingException(errorMessage, e);
    } catch (CertificateException e) {
        String errorMessage = String.format("An error occurred while build a certificate using the certificate "
                + "content from the database for the ID '%s'", certificateId);
        throw new CertificateRetrievingException(errorMessage, e);
    } catch (IOException e) {
        String errorMessage = String.format(
                "An error occurred while reading the certificate blob from the " + "database for the ID '%s'",
                certificateId);
        throw new CertificateRetrievingException(errorMessage, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, queryResults,
                statementToGetApplicationCertificate);
    }

    return null;
}

From source file:bboss.org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader.java

/**
 * Get an InputStream so that the Runtime can build a
 * template with it.// w ww.j a  v  a  2 s.  c  om
 *
 *  @param name name of template
 *  @return InputStream containing template
 * @throws ResourceNotFoundException
 */
public synchronized InputStream getResourceStream(final String name) throws ResourceNotFoundException {
    if (org.apache.commons.lang.StringUtils.isEmpty(name)) {
        throw new ResourceNotFoundException("DataSourceResourceLoader: Template name was empty or null");
    }

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
        conn = openDbConnection();
        ps = getStatement(conn, templateColumn, name);
        rs = ps.executeQuery();

        if (rs.next()) {
            InputStream stream = rs.getBinaryStream(templateColumn);
            if (stream == null) {
                throw new ResourceNotFoundException(
                        "DataSourceResourceLoader: " + "template column for '" + name + "' is null");
            }

            return new BufferedInputStream(stream);
        } else {
            throw new ResourceNotFoundException(
                    "DataSourceResourceLoader: " + "could not find resource '" + name + "'");

        }
    } catch (SQLException sqle) {
        String msg = "DataSourceResourceLoader: database problem while getting resource '" + name + "': ";

        log.error(msg, sqle);
        throw new ResourceNotFoundException(msg);
    } catch (NamingException ne) {
        String msg = "DataSourceResourceLoader: database problem while getting resource '" + name + "': ";

        log.error(msg, ne);
        throw new ResourceNotFoundException(msg);
    } finally {
        closeResultSet(rs);
        closeStatement(ps);
        closeDbConnection(conn);
    }
}

From source file:org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader.java

/**
 * Get an InputStream so that the Runtime can build a
 * template with it./*from   www. j av  a 2  s. c o  m*/
 *
 *  @param name name of template
 *  @return InputStream containing template
 * @throws ResourceNotFoundException
 */
public synchronized InputStream getResourceStream(final String name) throws ResourceNotFoundException {
    if (org.apache.commons.lang.StringUtils.isEmpty(name)) {
        throw new ResourceNotFoundException("DataSourceResourceLoader: Template name was empty or null");
    }

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    try {
        conn = openDbConnection();
        ps = getStatement(conn, templateColumn, name);
        rs = ps.executeQuery();

        if (rs.next()) {
            InputStream stream = rs.getBinaryStream(templateColumn);
            if (stream == null) {
                throw new ResourceNotFoundException(
                        "DataSourceResourceLoader: " + "template column for '" + name + "' is null");
            }

            return new BufferedInputStream(stream);
        } else {
            throw new ResourceNotFoundException(
                    "DataSourceResourceLoader: " + "could not find resource '" + name + "'");

        }
    } catch (SQLException sqle) {
        String msg = "DataSourceResourceLoader: database problem while getting resource '" + name + "': ";

        Logger.error(this, msg, sqle);
        throw new ResourceNotFoundException(msg);
    } catch (NamingException ne) {
        String msg = "DataSourceResourceLoader: database problem while getting resource '" + name + "': ";

        Logger.error(this, msg, ne);
        throw new ResourceNotFoundException(msg);
    } finally {
        closeResultSet(rs);
        closeStatement(ps);
        closeDbConnection(conn);
    }
}

From source file:com.nabla.wapp.server.xml.Importer.java

public <T> T read(final Class<T> clazz, final Integer dataId, final String userSessionId)
        throws DispatchException, SQLException {
    final PreparedStatement stmt = StatementFormat.prepare(conn, sql, dataId);
    try {/* ww  w  . j a v a 2  s.  c o  m*/
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next()) {
                errors.add(CommonServerErrors.NO_DATA);
                return null;
            }
            if (!userSessionId.equals(rs.getString("userSessionId"))) {
                if (log.isTraceEnabled())
                    log.trace("invalid user session ID");
                errors.add(CommonServerErrors.ACCESS_DENIED);
                return null;
            }
            try {
                return impl.read(clazz, rs.getBinaryStream("content"));
            } catch (final InvocationTargetException e) {
                if (log.isDebugEnabled())
                    log.debug("exception thrown from a validate(). assume error was added to list", e);
            } catch (final ValueRequiredException e) {
                if (log.isDebugEnabled())
                    log.debug("required value", e);
                errors.add(Util.extractLine(e), Util.extractFieldName(e), CommonServerErrors.REQUIRED_VALUE);
            } catch (final ElementException e) {
                errors.add(Util.extractFieldName(e), e.getLocalizedMessage());
            } catch (final PersistenceException e) {
                if (log.isDebugEnabled())
                    log.debug("deserialization error", e);
                errors.add(Util.extractLine(e), Util.extractFieldName(e), CommonServerErrors.INVALID_VALUE);
            } catch (final XMLStreamException e) {
                if (log.isDebugEnabled())
                    log.debug("XML error", e);
                errors.add(Util.extractLine(e), e.getLocalizedMessage());
            } catch (final Exception e) {
                if (log.isDebugEnabled())
                    log.debug("error", e);
                errors.add(Util.extractLine(e), e.getLocalizedMessage());
            }
            return null;
        } finally {
            Database.close(rs);
        }
    } finally {
        Database.close(stmt);
    }
}