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.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.java

/**
 * Reads and parses a bundle from the BLOB in the given column of the
 * current row of the given result set. This is a helper method to
 * circumvent issues JCR-1039 and JCR-1474.
 *
 * @param id bundle identifier/*from w  ww.j av a  2 s. com*/
 * @param rs result set
 * @param column BLOB column
 * @return parsed bundle
 * @throws SQLException if the bundle can not be read or parsed
 */
private NodePropBundle readBundle(NodeId id, ResultSet rs, int column) throws SQLException {
    try {
        InputStream in;
        if (rs.getMetaData().getColumnType(column) == Types.BLOB) {
            in = rs.getBlob(column).getBinaryStream();
        } else {
            in = rs.getBinaryStream(column);
        }
        try {
            return binding.readBundle(in, id);
        } finally {
            in.close();
        }
    } catch (IOException e) {
        SQLException exception = new SQLException("Failed to parse bundle " + id);
        exception.initCause(e);
        throw exception;
    }
}

From source file:org.artifactory.storage.db.build.dao.BuildsDao.java

public <T> T getJsonBuild(long buildId, Class<T> clazz) throws SQLException {
    ResultSet rs = null;
    InputStream jsonStream = null;
    try {/*from   w  ww .  j  ava2s . c  o  m*/
        rs = jdbcHelper.executeSelect("SELECT build_info_json FROM build_jsons WHERE" + " build_id = ?",
                buildId);
        if (rs.next()) {
            jsonStream = rs.getBinaryStream(1);
            if (CharSequence.class.isAssignableFrom(clazz)) {
                //noinspection unchecked
                return (T) IOUtils.toString(jsonStream, Charsets.UTF_8.name());
            }
            return JacksonReader.streamAsClass(jsonStream, clazz);
        }
    } catch (IOException e) {
        throw new SQLException("Failed to read JSON data for build '" + buildId + "' due to: " + e.getMessage(),
                e);
    } finally {
        DbUtils.close(rs);
        IOUtils.closeQuietly(jsonStream);
    }
    return null;
}

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

/**
 * {@inheritDoc}//w ww .  j av a2 s.c  om
 */
public synchronized NodeReferences loadReferencesTo(NodeId targetId)
        throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    ResultSet rs = null;
    InputStream in = null;
    try {
        rs = conHelper.exec(nodeReferenceSelectSQL, getKey(targetId), false, 0);
        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);
        DbUtility.close(rs);
    }
}

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}/* www  .j  a  va  2 s .  c  o  m*/
 */
public NodeState load(NodeId id) throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    synchronized (nodeStateSelectSQL) {
        ResultSet rs = null;
        InputStream in = null;
        try {
            Statement stmt = executeStmt(nodeStateSelectSQL, new Object[] { id.toString() });
            rs = stmt.getResultSet();
            if (!rs.next()) {
                throw new NoSuchItemStateException(id.toString());
            }

            in = rs.getBinaryStream(1);
            NodeState state = createNew(id);
            Serializer.deserialize(state, in);

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

From source file:com.apatar.webdav.WebDavNode.java

@Override
protected void TransformTDBtoRDB(int mode) {
    try {/*from  w  w  w  .j  a  v  a 2 s.  c  om*/
        DataBaseTools.completeTransfer();
        TableInfo ti = getTiForConnection(IN_CONN_POINT_NAME);
        ResultSet rs = DataBaseTools.getRSWithAllFields(ti.getTableName(),
                ApplicationData.tempDataBase.getJdbcParams(), ApplicationData.getTempDataBaseInfo());

        WebdavResource resource = null;

        while (rs.next()) {
            boolean isFolder = rs.getBoolean("isFolder");

            resource = getBinding();
            // pathRes - path to resource
            String pathRes = convertHttpToString(resource.getHttpURL());
            // path - inner path from db
            String path = rs.getString("Path");

            if (path.length() > 0) {
                if (separator.equals(path.substring(0, 1)) || "\\".equals(path.substring(0, 1))) {
                    pathRes += path;
                } else {
                    pathRes = pathRes + separator + path;
                }
            }

            if (isFolder) {
                resource.mkcolMethod(pathRes);
            } else {
                InputStream in = rs.getBinaryStream("Content");
                if (null != in) {
                    resource.putMethod(pathRes, in);
                    in.close();
                } else {
                    // if Content field is null, but String_Content field is
                    // not null
                    String strContent = rs.getString("String_Content");
                    if (null != strContent && !"".equals(strContent)) {
                        byte[] bytes = strContent.getBytes();
                        resource.putMethod(pathRes, bytes);
                    } else {
                        resource.putMethod(pathRes, "");
                    }
                }
            }

            if (!ApplicationData.ProcessingProgress.Step()) {
                return;
            }

            ApplicationData.ProcessingProgress.Log("Uploading resource: " + pathRes);
        }

    } catch (Exception e1) {
        ApplicationData.ProcessingProgress.Log(e1);
        e1.printStackTrace();
    } finally {
        DataBaseTools.completeTransfer();
    }
}

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}/*from w w w.ja  va 2s.c  o  m*/
 */
public PropertyState load(PropertyId id) throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    synchronized (propertyStateSelectSQL) {
        ResultSet rs = null;
        InputStream in = null;
        try {
            Statement stmt = executeStmt(propertyStateSelectSQL, new Object[] { id.toString() });
            rs = stmt.getResultSet();
            if (!rs.next()) {
                throw new NoSuchItemStateException(id.toString());
            }

            in = rs.getBinaryStream(1);

            if (!externalBLOBs) {
                // JCR-1532: pre-fetch/buffer stream data
                ByteArrayInputStream bain = new ByteArrayInputStream(IOUtils.toByteArray(in));
                IOUtils.closeQuietly(in);
                in = bain;
            }

            PropertyState state = createNew(id);
            Serializer.deserialize(state, in, blobStore);

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

From source file:org.apache.jackrabbit.core.persistence.db.DatabasePersistenceManager.java

/**
 * {@inheritDoc}/*from   ww w  .j a  va  2s . co m*/
 */
public NodeReferences loadReferencesTo(NodeId targetId) throws NoSuchItemStateException, ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    synchronized (nodeReferenceSelectSQL) {
        ResultSet rs = null;
        InputStream in = null;
        try {
            Statement stmt = executeStmt(nodeReferenceSelectSQL, new Object[] { targetId.toString() });
            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 node references: " + targetId;
            log.error(msg, e);
            throw new ItemStateException(msg, e);
        } finally {
            IOUtils.closeQuietly(in);
            closeResultSet(rs);
        }
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Remove a precise number of captcha with a locale
 *
 * @param number The number of captchas to remove
 * @param locale The locale of the removed captchas
 *
 * @return a collection of captchas/* ww w . j  a  va  2  s.c om*/
 */
public Collection removeCaptcha(int number, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement psdel = null;
    ResultSet rs = null;
    Collection collection = new UnboundedFifoBuffer();
    Collection temp = new UnboundedFifoBuffer();
    if (number < 1) {
        return collection;
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("try to remove " + number + " captchas");
        }
        ;
        con = datasource.getConnection();

        ps = con.prepareStatement(
                "select *  from " + table + " where " + localeColumn + " = ? order by " + timeMillisColumn);

        psdel = con.prepareStatement(
                "delete from " + table + " where " + timeMillisColumn + "= ? and " + hashCodeColumn + "= ? ");//and " + localeColumn
        //+ "= ?");
        ps.setString(1, locale.toString());
        ps.setMaxRows(number);
        //read
        rs = ps.executeQuery();
        int i = 0;
        while (rs.next() && i < number) {
            try {
                i++;
                InputStream in = rs.getBinaryStream(captchaColumn);
                ObjectInputStream objstr = new ObjectInputStream(in);
                Object captcha = objstr.readObject();
                temp.add(captcha);
                //and delete
                long time = rs.getLong(timeMillisColumn);
                long hash = rs.getLong(hashCodeColumn);
                psdel.setLong(1, time);
                psdel.setLong(2, hash);
                //psdel.setString(3, rs.getString(localeColumn));
                psdel.addBatch();

                if (log.isDebugEnabled()) {
                    log.debug("remove captcha added to batch : " + time + ";" + hash);
                }

            } catch (IOException e) {
                log.error("error during captcha deserialization, "
                        + "check your class versions. removing row from database", e);
                psdel.execute();
            } catch (ClassNotFoundException e) {
                log.error("Serialized captcha class in database is not in your classpath!", e);
            }

        }
        //execute batch delete
        psdel.executeBatch();
        log.debug("batch executed");
        rs.close();
        //commit the whole stuff
        con.commit();
        log.debug("batch commited");
        //only add after commit
        collection.addAll(temp);
    } catch (SQLException e) {
        log.error(DB_ERROR, e);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
        }

    } finally {

        if (ps != null) {
            try {
                ps.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.close();
            } // rollback on error
            catch (SQLException e) {
            }
        }
    }
    return collection;
}

From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java

/**
 * {@inheritDoc}//from  w  w w .j a  va2 s  .  c  om
 */
public InputStream getInputStream(String filePath) throws FileSystemException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    FileSystemPathUtil.checkFormat(filePath);

    String parentDir = FileSystemPathUtil.getParentDir(filePath);
    String name = FileSystemPathUtil.getName(filePath);

    synchronized (selectDataSQL) {
        try {
            Statement stmt = executeStmt(selectDataSQL, new Object[] { parentDir, name });

            final ResultSet rs = stmt.getResultSet();
            if (!rs.next()) {
                throw new FileSystemException("no such file: " + filePath);
            }
            InputStream in = rs.getBinaryStream(1);
            /**
             * return an InputStream wrapper in order to
             * close the ResultSet when the stream is closed
             */
            return new FilterInputStream(in) {
                public void close() throws IOException {
                    super.close();
                    // close ResultSet
                    closeResultSet(rs);
                }
            };
        } catch (SQLException e) {
            String msg = "failed to retrieve data of file: " + filePath;
            log.error(msg, e);
            throw new FileSystemException(msg, e);
        }
    }
}

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

private InputStream getContentArchived(int contentID) throws RepositoryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    ResultSet result = null;
    PreparedStatement ps = null;/*from  ww w . ja 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, CurrentContext.getTenantId());
        result = ps.executeQuery();

        if (result.next()) {
            InputStream rawStream = result.getBinaryStream(DatabaseConstants.CONTENT_DATA_FIELD);
            if (rawStream != null) {
                return RepositoryUtils.getMemoryStream(rawStream);
            }
        }
    } catch (SQLException e) {
        String msg = "Failed to get the archived content " + contentID + ". " + 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 null;
}