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:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Load an NCube from the database (any joined sub-cubes will also be loaded).
 *
 * @return NCube that matches, or null if not found.
 *//*w  w w .  jav  a  2  s . co m*/
public static NCube loadCube(Connection connection, String app, String name, String version, String status,
        Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);
    if (sysDate == null) {
        sysDate = new Date();
    }

    synchronized (cubeList) {
        //  This is Java 7 specific, but will autoclose the statement
        //  when it leaves the try statement.  If you want to change to this
        //  let me know and I'll change the other instances.
        try (PreparedStatement 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 = ?")) {
            java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());

            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);
                }

                addCube(ncube, version);
                Set<String> subCubeList = ncube.getReferencedCubeNames();

                for (String cubeName : subCubeList) {
                    final String cacheKey = makeCacheKey(cubeName, version);
                    if (!cubeList.containsKey(cacheKey)) {
                        loadCube(connection, app, cubeName, version, status, sysDate);
                    }
                }
                return ncube;
            }
            return null; // Indicates not found
        } 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);
        }
    }
}

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

public Nonce getNonceById(Integer id) throws SQLException {
    String sql = "select * from " + TABLE_NAME + " where " + ID + " = " + id;
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    ResultSet rs = pst.executeQuery(sql);
    if (rs.next()) {
        //data valid
        Integer nonceID = rs.getInt(ID);
        String nonceSID = rs.getString(SID);
        byte[] nonceBytes = rs.getBytes(VALUE);
        Nonce nonce = new Nonce();
        nonce.setId(nonceID);//  w  w  w .  j av  a  2s .co m
        nonce.setIssuerSid(nonceSID);
        nonce.setByteArray(nonceBytes);
        return nonce;
    } else {
        return null;
    }

}

From source file:io.druid.db.DbConnector.java

public byte[] lookup(final String tableName, final String keyColumn, final String valueColumn,
        final String key) {
    final String selectStatement = String.format("SELECT %s FROM %s WHERE %s = :key", valueColumn, tableName,
            keyColumn);//from  w w  w  .ja  va  2 s.c  o m

    return dbi.withHandle(new HandleCallback<byte[]>() {
        @Override
        public byte[] withHandle(Handle handle) throws Exception {
            List<byte[]> matched = handle.createQuery(selectStatement).bind("key", key)
                    .map(new ResultSetMapper<byte[]>() {
                        @Override
                        public byte[] map(int index, ResultSet r, StatementContext ctx) throws SQLException {
                            return r.getBytes(valueColumn);
                        }
                    }).list();

            if (matched.isEmpty()) {
                return null;
            }

            if (matched.size() > 1) {
                throw new ISE("Error! More than one matching entry[%d] found for [%s]?!", matched.size(), key);
            }

            return matched.get(0);
        }
    });
}

From source file:com.xinferin.dao.DAOProductImpl.java

@Override
public List<Product> list() {
    String sql = "SELECT * FROM product";
    List<Product> list = jdbcTemplate.query(sql, new RowMapper<Product>() {
        @Override/*w  w  w  .  j a  v  a 2  s . co  m*/
        public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
            Product aProduct = new Product();

            aProduct.setId(rs.getInt("id"));
            aProduct.setName(rs.getString("name"));
            aProduct.setLicence_params(rs.getBytes("licence_params"));

            return aProduct;
        }
    });
    return list;
}

From source file:eu.europa.ec.markt.dss.validation.crl.JdbcCacheCRLSource.java

@Override
public X509CRL findCrl(X509Certificate certificate, X509Certificate issuerCertificate) throws IOException {

    OnlineCRLSource source = new OnlineCRLSource();
    String crlUrl = source.getCrlUri(certificate);

    if (crlUrl != null) {
        try {/* ww w .ja v  a2  s .  c om*/
            MessageDigest digest = MessageDigest.getInstance(DigestAlgorithm.SHA1.getName());
            String key = Hex.encodeHexString(digest.digest(crlUrl.getBytes()));

            List<CachedCRL> crls = getJdbcTemplate().query("SELECT * FROM CACHED_CRL WHERE ID = ?",
                    new Object[] { key }, new RowMapper<CachedCRL>() {
                        @Override
                        public CachedCRL mapRow(ResultSet rs, int rowNum) throws SQLException {
                            CachedCRL cached = new CachedCRL();
                            cached.setKey(rs.getString("ID"));
                            cached.setCrl(rs.getBytes("DATA"));
                            return cached;
                        }
                    });

            if (crls.size() == 0) {
                LOG.info("CRL not in cache");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                if (originalCRL != null) {
                    getJdbcTemplate().update("INSERT INTO CACHED_CRL (ID, DATA) VALUES (?,?) ", key,
                            originalCRL.getEncoded());
                    return originalCRL;
                } else {
                    return null;
                }
            }

            CachedCRL crl = crls.get(0);

            CertificateFactory factory = CertificateFactory.getInstance("X509");
            X509CRL x509crl = (X509CRL) factory.generateCRL(new ByteArrayInputStream(crl.getCrl()));
            if (x509crl.getNextUpdate().after(new Date())) {
                LOG.fine("CRL in cache");
                return x509crl;
            } else {
                LOG.info("CRL expired");
                X509CRL originalCRL = cachedSource.findCrl(certificate, issuerCertificate);
                getJdbcTemplate().update("UPDATE CACHED_CRL SET DATA = ?  WHERE ID = ? ",
                        originalCRL.getEncoded(), key);
                return originalCRL;
            }

        } catch (NoSuchAlgorithmException e) {
            LOG.info("Cannot instantiate digest for algorithm SHA1 !?");
        } catch (CRLException e) {
            LOG.info("Cannot serialize CRL");
        } catch (CertificateException e) {
            LOG.info("Cannot instanciate X509 Factory");
        }
    }

    return null;
}

From source file:com.azaptree.services.security.dao.HashedCredentialDAO.java

@Override
public boolean subjectHasCredential(final UUID subjectId, final String name, final byte[] hash) {
    Assert.notNull(subjectId, "subjectId is required");
    Assert.hasText(name, "name is required");
    Assert.isTrue(ArrayUtils.isNotEmpty(hash), "hash is required");
    final String sql = "select hash from t_hashed_credential where subject_id = ? and name = ?";
    final Object[] args = { subjectId, name };
    return jdbc.query(sql, args, new ResultSetExtractor<Boolean>() {

        @Override// w w  w .  j  a  v  a 2  s .  c o  m
        public Boolean extractData(final ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                return Arrays.equals(rs.getBytes(1), hash);
            }

            return false;
        }
    });
}

From source file:nz.co.gregs.dbvolution.datatypes.DBJavaObject.java

@SuppressWarnings("unchecked")
private O getFromGetBytes(ResultSet resultSet, String fullColumnName) throws SQLException {
    try {/*from  ww  w  .j  av a  2 s  .  co  m*/
        byte[] bytes = resultSet.getBytes(fullColumnName);
        ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes));
        //         this.setValue(input.readObject());
        return (O) input.readObject();
    } catch (IOException ex) {
        Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.osmdroid.server.jdk.TileFetcher.java

@GET //xyz no good
//zyx no good//w w  w  .  j a  va 2 s.co m
//zxy closer

@Path("/{source}/{z}/{x}/{y}.png")
@Produces("image/png")
@org.apache.cxf.jaxrs.model.wadl.Description("Returns png of the specific map tile from the database")
public byte[] getImage(@PathParam("source") String id, @PathParam("z") int z, @PathParam("x") int x,
        @PathParam("y") int y) throws WebApplicationException {

    Connection c = connections.get(id);
    if (c == null) {
        System.err.println(id + " isn't registered");
        throw new WebApplicationException(new Exception(id + " is not a valid tile source"), 400);
    }
    try {

        PreparedStatement prep = c.prepareStatement("Select tile from tiles where key=?;");

        long index = (((z << z) + x) << z) + y;
        System.out.println("Fetching tile " + id + z + "/" + x + "/" + y + " as " + index);
        prep.setLong(1, index);
        ResultSet executeQuery = prep.executeQuery();
        if (executeQuery.next()) {
            //Blob b= executeQuery.getBlob(1);
            //byte[] image=b.getBytes(0, (int)b.length());
            byte[] image2 = executeQuery.getBytes(1);
            //return image;
            return image2;
        }
        System.out.println(id + "Tile not found " + z + "/" + x + "/" + y + " as " + index);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

    }
    throw new WebApplicationException(404);

}

From source file:com.xinferin.dao.DAOProductImpl.java

@Override
public Product get(String product) {
    String sql = "SELECT * FROM product WHERE name = '" + product + "'";
    return jdbcTemplate.query(sql, new ResultSetExtractor<Product>() {

        @Override/*from   w  w  w.  jav  a 2 s. c  o  m*/
        public Product extractData(ResultSet rs) throws SQLException, DataAccessException {

            if (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setLicence_params(rs.getBytes("licence_params"));
                return product;
            }
            return null;
        }
    });
}

From source file:com.xinferin.dao.DAOProductImpl.java

@Override
public Product get(int productId) {

    // retrieve the details of this product including temp if it exists
    String sql = "SELECT * FROM product WHERE id=" + productId;
    return jdbcTemplate.query(sql, new ResultSetExtractor<Product>() {

        @Override/*  w  w  w.j a  va 2s .c om*/
        public Product extractData(ResultSet rs) throws SQLException, DataAccessException {

            if (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setLicence_params(rs.getBytes("licence_params"));

                if (rs.getString("temp") != null) {
                    product.setTemp(rs.getString("temp"));
                }
                return product;
            }
            return null;
        }
    });
}