Example usage for java.sql ResultSet getBytes

List of usage examples for java.sql ResultSet getBytes

Introduction

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

Prototype

byte[] getBytes(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a byte array in the Java programming language.

Usage

From source file:org.quartz.impl.jdbcjobstore.CloudscapeDelegate.java

/**
 * <p>// w w w .jav a  2  s .  c o m
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;

    byte[] inputBytes = rs.getBytes(colName);

    if (null != inputBytes && inputBytes.length != 0) {
        ByteArrayInputStream bais = new ByteArrayInputStream(inputBytes);

        ObjectInputStream in = new ObjectInputStream(bais);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }

    return obj;
}

From source file:com.uit.anonymousidentity.Repository.Nonces.NonceJDBCTemplate.java

@Override
public Nonce find(BigInteger i) throws SQLException {
    String sql = "select * from " + TABLE_NAME + " where " + VALUE + " = ?";
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    Nonce n = new Nonce();
    pst.setBytes(1, i.toByteArray());/*from w ww  .j  a  v  a  2s. co m*/
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        n.setIssuerSid(rs.getString(SID));
        n.setByteArray(rs.getBytes(VALUE));
        n.setId(rs.getInt(ID));
        return n;
    } else
        return null;
}

From source file:org.sonar.db.version.v51.FeedFileSourcesBinaryDataTest.java

private DbFileSources.Data selectData(Connection connection, long fileSourceId) throws SQLException {
    PreparedStatement pstmt = connection.prepareStatement("select binary_data from file_sources where id=?");
    ResultSet rs = null;
    try {/*from  w  ww. jav  a 2s.c  om*/
        pstmt.setLong(1, fileSourceId);
        rs = pstmt.executeQuery();
        rs.next();
        return new FileSourceDto().decodeSourceData(rs.getBytes(1));
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pstmt);
    }
}

From source file:org.quartz.impl.jdbcjobstore.PostgreSQLDelegate.java

/**
 * <p>/*from   w w w.j a v a  2s.  com*/
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    InputStream binaryInput = null;
    byte[] bytes = rs.getBytes(colName);

    Object obj = null;

    if (bytes != null && bytes.length != 0) {
        binaryInput = new ByteArrayInputStream(bytes);

        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }

    }

    return obj;
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Get the notes associated to an NCube/*w  w w .  j  a  va2 s.  co  m*/
 *
 * @return String notes.
 */
public static String getNotes(Connection connection, String app, String name, String version, Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);

    if (sysDate == null) {
        sysDate = new Date();
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT notes_bin FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)");
        stmt.setString(1, app);
        stmt.setString(2, name);
        stmt.setString(3, version);
        stmt.setDate(4, systemDate);
        stmt.setDate(5, systemDate);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] notes = rs.getBytes("notes_bin");
            return new String(notes == null ? "".getBytes() : notes, "UTF-8");
        }
        throw new IllegalArgumentException("No NCube matching passed in parameters.");
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to fetch notes for NCube: " + name + ", app: " + app + ", version: " + version;
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

From source file:controller.LoadImageServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  www. j  ava  2 s  .c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String iid = request.getParameter("param1");
    byte[] sImageBytes;
    try {

        Connection con = JdbcConnection.getConnection();
        String Query = "SELECT image FROM user WHERE email ='" + iid + "';";
        System.out.println("Query is" + Query);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(Query);
        System.out.println("..........1");
        String name = "client_2";
        if (rs.next()) {

            sImageBytes = rs.getBytes("image");

            response.setContentType("image/jpeg");
            response.setContentLength(sImageBytes.length);
            // Give the name of the image in the name variable in the below line   
            response.setHeader("Content-Disposition", "inline; filename=\"" + name + "\"");

            BufferedInputStream input = new BufferedInputStream(new ByteArrayInputStream(sImageBytes));
            BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
                System.out.println(".......3");
            }
            output.flush();
        }
    } catch (Exception ex) {
        System.out.println("error :" + ex);
    }
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Get the Test Data associated to the NCube.
 *
 * @return String serialized JSON test data.  Use JsonReader to turn it back into
 * Java objects.// ww w.ja  va2 s.  co m
 */
public static String getTestData(Connection connection, String app, String name, String version, Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);

    if (sysDate == null) {
        sysDate = new Date();
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT test_data_bin FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)");
        stmt.setString(1, app);
        stmt.setString(2, name);
        stmt.setString(3, version);
        stmt.setDate(4, systemDate);
        stmt.setDate(5, systemDate);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] testData = rs.getBytes("test_data_bin");
            return new String(testData == null ? "".getBytes() : testData, "UTF-8");
        }
        throw new IllegalArgumentException("No NCube matching passed in parameters.");
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to fetch test data for NCube: " + name + ", app: " + app + ", version: " + version;
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

From source file:org.quartz.impl.jdbcjobstore.PostgreSQLDelegate.java

protected Object getJobDetailFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    if (canUseProperties()) {
        InputStream binaryInput = null;
        byte[] bytes = rs.getBytes(colName);
        if (bytes == null || bytes.length == 0) {
            return null;
        }//from ww  w  .  j a  v  a  2s .c  o m
        binaryInput = new ByteArrayInputStream(bytes);
        return binaryInput;
    }
    return getObjectFromBlob(rs, colName);
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Retrieve all cube names that are deeply referenced by the named app, cube (name), version, and status.
 *//* w  w  w.  j a v  a2s .  c  om*/
public static void getReferencedCubeNames(Connection connection, String app, String name, String version,
        String status, Date sysDate, Set<String> refs) {
    validate(connection, app, version);
    validateCubeName(name);
    validateStatus(status);

    if (sysDate == null) {
        sysDate = new Date();
    }
    if (refs == null) {
        throw new IllegalArgumentException("null passed in for Set to hold referenced n-cube names");
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT cube_value_bin FROM n_cube WHERE n_cube_nm = ? AND app_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?) AND version_no_cd = ? AND status_cd = ?");

        stmt.setString(1, name);
        stmt.setString(2, app);
        stmt.setDate(3, systemDate);
        stmt.setDate(4, systemDate);
        stmt.setString(5, version);
        stmt.setString(6, status);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] jsonBytes = rs.getBytes("cube_value_bin");
            String json = new String(jsonBytes, "UTF-8");
            NCube ncube = ncubeFromJson(json);

            if (rs.next()) {
                throw new IllegalStateException(
                        "More than one NCube matching name: " + ncube.getName() + ", app: " + app
                                + ", version: " + version + ", status: " + status + ", sysDate: " + sysDate);
            }

            Set<String> subCubeList = ncube.getReferencedCubeNames();
            refs.addAll(subCubeList);

            for (String cubeName : subCubeList) {
                if (!refs.contains(cubeName)) {
                    getReferencedCubeNames(connection, app, cubeName, version, status, sysDate, refs);
                }
            }
        }
    } catch (IllegalStateException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to load nNCube: " + name + ", app: " + app + ", version: " + version + ", status: "
                + status + ", sysDate: " + sysDate + " from database";
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not
 * having any ties to the active ResultSet: in particular, it should not be
 * a Blob or Clob object but rather a byte array respectively String
 * representation.//w w  w . j  av a 2  s .  c o m
 * <p>
 * Uses the <code>getObject(index)</code> method, but includes additional
 * "hacks" to get around Oracle 10g returning a non-standard object for its
 * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
 * leaving out the time portion: These columns will explicitly be extracted
 * as standard <code>java.sql.Timestamp</code> object.
 *
 * @param rs
 *            is the ResultSet holding the data
 * @param index
 *            is the column index
 * @param readStringsAsBytes TODO
 * @return the value object
 * @throws SQLException
 *             if thrown by the JDBC API
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 */
public static Object getResultSetValue(ResultSet rs, int index, boolean readStringsAsBytes)
        throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();
    Object obj = null;
    int jdbcType = metaData.getColumnType(index);
    if (readStringsAsBytes && TypeMap.isTextType(jdbcType)) {
        byte[] bytes = rs.getBytes(index);
        if (bytes != null) {
            obj = new String(bytes);
        }
    } else {
        obj = rs.getObject(index);
    }
    String className = null;
    if (obj != null) {
        className = obj.getClass().getName();
    }
    if (obj instanceof Blob) {
        Blob blob = (Blob) obj;
        InputStream is = blob.getBinaryStream();
        try {
            obj = IOUtils.toByteArray(is);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    } else if (obj instanceof Clob) {
        Clob clob = (Clob) obj;
        Reader reader = clob.getCharacterStream();
        try {
            obj = IOUtils.toString(reader);
        } catch (IOException e) {
            throw new SqlException(e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    } else if (className != null && ("oracle.sql.TIMESTAMP".equals(className))) {
        obj = rs.getTimestamp(index);
    } else if (className != null && "oracle.sql.TIMESTAMPTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && "oracle.sql.TIMESTAMPLTZ".equals(className)) {
        obj = rs.getString(index);
    } else if (className != null && className.startsWith("oracle.sql.DATE")) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)
                || "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        } else {
            obj = rs.getDate(index);
        }
    } else if (obj instanceof java.sql.Date) {
        String metaDataClassName = metaData.getColumnClassName(index);
        if ("java.sql.Timestamp".equals(metaDataClassName)) {
            obj = rs.getTimestamp(index);
        }
    } else if (obj instanceof Timestamp) {
        String typeName = metaData.getColumnTypeName(index);
        if (typeName != null && typeName.equals("timestamptz")) {
            obj = rs.getString(index);
        }
    }
    return obj;
}