Example usage for java.sql PreparedStatement setBytes

List of usage examples for java.sql PreparedStatement setBytes

Introduction

In this page you can find the example usage for java.sql PreparedStatement setBytes.

Prototype

void setBytes(int parameterIndex, byte x[]) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java array of bytes.

Usage

From source file:gov.nih.nci.cadsr.cadsrpasswordchange.test.TestPasswordReset.java

public void testEncryptionDecryptionWithOracleFunctions() {
    //TBD - this approach is currently not used, we had issue with "java.sql.SQLException: ORA-28232: invalid input length for obfuscation toolkit
    //ORA-06512: at "SYS.DBMS_OBFUSCATION_TOOLKIT_FFI", line 84
    //ORA-06512: at "SYS.DBMS_OBFUSCATION_TOOLKIT", line 255
    //ORA-06512: at "SBREXT.DECRYPT", line 7"
    //while invoking the database functions
    String key = "1234567890123456";
    String text = "testtest"; //data has to be in a multiples of 8 bytes
    String encryptedText = null;/*from  w  ww .j a va2  s. co m*/
    byte[] encryptedBytes = null;
    String decryptedText = null;
    byte[] decryptedBytes = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ByteArrayInputStream in = null;
    try {
        Connection conn = getConnection(ADMIN_ID, ADMIN_PASSWORD);
        String sql = "select sbrext.encrypt('" + key + "', ?) from dual";
        stmt = conn.prepareStatement(sql);
        stmt.setBytes(1, text.getBytes());
        rs = stmt.executeQuery();
        while (rs.next()) {
            //            encryptedText = rs.getString(1);
            in = (ByteArrayInputStream) rs.getBinaryStream(1);
            encryptedBytes = toBytes(in);
        }

        String sql2 = "select sbrext.decrypt('" + key + "', ?) from dual";
        stmt = conn.prepareStatement(sql2);
        stmt.setBytes(1, encryptedBytes);
        rs = stmt.executeQuery();
        while (rs.next()) {
            //            decryptedText = rs.getString(1);
            in = (ByteArrayInputStream) rs.getBinaryStream(1);
            decryptedBytes = toBytes(in);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(text.getBytes(), decryptedBytes);
}

From source file:org.josso.gateway.identity.service.store.db.IdentityDAO.java

public String loadUID(CredentialKey key) throws SSOIdentityException {
    PreparedStatement stmt = null;
    ResultSet result = null;// ww w.  ja v  a2s.co  m
    String uid = null;

    try {

        if (key instanceof CertificateUserKey) {
            X509Certificate certificate = ((CertificateUserKey) key).getCertificate();
            if (certificate != null) {
                stmt = createPreparedStatement(_uidQueryString);
                stmt.setBytes(1, certificate.getEncoded());
                // Use key id to narrow search scope?
                //stmt.setString(2, ((CertificateUserKey)key).getId());
                result = stmt.executeQuery();
                while (result.next()) {
                    uid = result.getString(1);
                    break;
                }
            }
        } else if (key instanceof SimpleUserKey) {
            uid = ((SimpleUserKey) key).getId();
        }

    } catch (SQLException sqlE) {
        logger.error("SQLException while finding UID", sqlE);
        throw new SSOIdentityException("During UID lookup: " + sqlE.getMessage());

    } catch (Exception e) {
        logger.error("Exception while finding UID", e);
        throw new SSOIdentityException("During UID lookup: " + e.getMessage());

    } finally {
        closeResultSet(result);
        closeStatement(stmt);
    }

    return uid;
}

From source file:com.bt.aloha.dao.StateInfoDaoTest.java

private SimpleTestInfo insertSimpleTestInfo(String id, String f1, String f2) {
    SimpleTestInfo sti = new SimpleTestInfo(id, f1, f2);
    byte[] stiBytes = null;
    try {/*from   w  w  w .  j a  v  a 2 s  .  c  o  m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(sti);
        oos.flush();
        oos.close();
        stiBytes = bos.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException("Unable to serialize SimpleTestInfo", e);
    }
    PreparedStatement s = null;
    try {
        s = connection.prepareStatement("insert into StateInfo"
                + "(object_id, object_type, object_version, last_use_time, is_dead, force_housekeep, object_value) values(?, 'Collection', ?, ?, ?, 0, ?)");
        s.setString(1, id);
        s.setString(2, "1");
        s.setLong(3, new java.util.Date().getTime());
        s.setInt(4, 0);
        s.setBytes(5, stiBytes);
        log.debug("Inserted row in Collection " + "for current SimpleTestInfo");
        s.execute();
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            throw new RuntimeException("Unable to rollback operation on SimpleTestInfo", e);
        }
        throw new RuntimeException("Unable to execute db operation on SimpleTestInfo. op rolledback", e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (SQLException e) {
                log.warn("Unable to close prepared statement", e);
            }
    }
    return sti;
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

private void migrateVNCPassword(Connection conn) {
    System.out.println("Begin migrate VNC password");
    PreparedStatement pstmt = null;
    ResultSet rs = null;//from  w  w  w .  j a va2s .co  m
    try {
        pstmt = conn.prepareStatement("select id, vnc_password from vm_instance");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            long id = rs.getLong(1);
            String value = rs.getString(2);
            if (value == null || value.isEmpty()) {
                continue;
            }
            String encryptedValue = migrateValue(value);
            pstmt = conn.prepareStatement("update vm_instance set vnc_password=? where id=?");
            pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
            pstmt.setLong(2, id);
            pstmt.executeUpdate();
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }
    System.out.println("End migrate VNC password");
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

private void migrateUserCredentials(Connection conn) {
    System.out.println("Begin migrate user credentials");
    PreparedStatement pstmt = null;
    ResultSet rs = null;/*from www. j av  a  2 s  .c o m*/
    try {
        pstmt = conn.prepareStatement("select id, secret_key from user");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            long id = rs.getLong(1);
            String secretKey = rs.getString(2);
            if (secretKey == null || secretKey.isEmpty()) {
                continue;
            }
            String encryptedSecretKey = migrateValue(secretKey);
            pstmt = conn.prepareStatement("update user set secret_key=? where id=?");
            pstmt.setBytes(1, encryptedSecretKey.getBytes("UTF-8"));
            pstmt.setLong(2, id);
            pstmt.executeUpdate();
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable update user secret key ", e);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable update user secret key ", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }
    System.out.println("End migrate user credentials");
}

From source file:dao.DirImageAddQuery.java

/**
* This method is used to add blobstreams for directory.
* @param conn - the connection/*from   w  w  w  .j  av a 2  s.com*/
* @param blobType - the blob type (1 - photos, 2-music, 3-video 4 - documents, 5 - archives)
* @param mimeType - the mime type (image/jpeg, application/octet-stream)
* @param btitle - the title for this blob
* @param bsize - the size of the blob
* @param zoom - the zoom for the blob (used for displaying for image/jpeg)
* @param directoryId - the directoryId
* @param loginId - the loginId
* @param caption - the caption
* @throws Dao Exception - when an error or exception occurs while inserting this blob in DB.
*
 **/
public void run(Connection conn, String entryid, int blobType, String mimeType, String btitle, long bsize,
        int zoom, String directoryId, String loginId, String caption, boolean convertEntryId)
        throws BaseDaoException {

    byte[] capBytes = { ' ' };
    if (!RegexStrUtil.isNull(caption)) {
        capBytes = caption.getBytes();
    }

    PreparedStatement s = null;
    String stmt = null;
    if (convertEntryId) {
        stmt = "insert into dirimages values(?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?)";
    } else {
        stmt = "insert into dirimages values(?, " + "LAST_INSERT_ID()"
                + ", ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?, ?, ?)";
    }
    try {
        s = conn.prepareStatement(stmt);
        if (convertEntryId) {
            s.setLong(1, 0);
            s.setLong(2, new Long(entryid));
            s.setLong(3, new Long(directoryId));
            s.setLong(4, new Long(loginId));
            s.setInt(5, new Integer(blobType));
            s.setString(6, mimeType);
            s.setString(7, btitle);
            s.setLong(8, bsize);
            s.setInt(9, new Integer(zoom));
            s.setBytes(10, capBytes);
        } else {
            s.setLong(1, 0);
            s.setLong(2, new Long(directoryId));
            s.setLong(3, new Long(loginId));
            s.setInt(4, new Integer(blobType));
            s.setString(5, mimeType);
            s.setString(6, btitle);
            s.setLong(7, bsize);
            s.setInt(8, new Integer(zoom));
            s.setBytes(9, capBytes);
        }
        s.executeUpdate();
    } catch (Exception e) {
        throw new BaseDaoException("Error inserting into dirimages query, " + stmt, e);
    }
}

From source file:org.wso2.carbon.identity.workflow.mgt.dao.WorkflowRequestDAO.java

/**
 * Persists WorkflowRequest to be used when workflow is completed
 *
 * @param workflow    The workflow object to be persisted
 * @param currentUser Currently logged in user
 * @param tenantId    Tenant ID of the currently Logged user.
 * @throws WorkflowException//from ww w .jav  a2s  .  c o m
 */
public void addWorkflowEntry(WorkflowRequest workflow, String currentUser, int tenantId)
        throws WorkflowException {
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement prepStmt = null;
    String query = SQLConstants.ADD_WORKFLOW_REQUEST_QUERY;
    try {
        Timestamp createdDateStamp = new Timestamp(System.currentTimeMillis());
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, workflow.getUuid());
        prepStmt.setString(2, currentUser);
        prepStmt.setString(3, workflow.getEventType());
        prepStmt.setTimestamp(4, createdDateStamp);
        prepStmt.setTimestamp(5, createdDateStamp);
        prepStmt.setBytes(6, serializeWorkflowRequest(workflow));
        prepStmt.setString(7, WorkflowRequestStatus.PENDING.toString());
        prepStmt.setInt(8, tenantId);
        prepStmt.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        throw new InternalWorkflowException("Error when executing the sql query:" + query, e);
    } catch (IOException e) {
        throw new InternalWorkflowException("Error when serializing the workflow request: " + workflow, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
}

From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java

private void migrateHostDetails(Connection conn) {
    System.out.println("Begin migrate host details");
    PreparedStatement pstmt = null;
    ResultSet rs = null;/*from   w ww . ja v a2  s. co  m*/
    try {
        pstmt = conn.prepareStatement("select id, value from host_details where name = 'password'");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            long id = rs.getLong(1);
            String value = rs.getString(2);
            if (value == null || value.isEmpty()) {
                continue;
            }
            String encryptedValue = migrateValue(value);
            pstmt = conn.prepareStatement("update host_details set value=? where id=?");
            pstmt.setBytes(1, encryptedValue.getBytes("UTF-8"));
            pstmt.setLong(2, id);
            pstmt.executeUpdate();
        }
    } catch (SQLException e) {
        throw new CloudRuntimeException("Unable update host_details values ", e);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable update host_details values ", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }

            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
    }
    System.out.println("End migrate host details");
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.GenericFeatureDAOImpl.java

@Override
public List<ProfileFeature> addProfileFeatures(List<ProfileFeature> features, int profileId)
        throws FeatureManagerDAOException {

    Connection conn;/*  w  w w  .ja v a 2s  .c  o m*/
    PreparedStatement stmt = null;
    ResultSet generatedKeys = null;
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_PROFILE_FEATURES (PROFILE_ID, FEATURE_CODE, DEVICE_TYPE, CONTENT, "
                + "TENANT_ID) VALUES (?, ?, ?, ?, ?)";
        stmt = conn.prepareStatement(query, new String[] { "id" });

        for (ProfileFeature feature : features) {
            stmt.setInt(1, profileId);
            stmt.setString(2, feature.getFeatureCode());
            stmt.setString(3, feature.getDeviceType());
            // if (conn.getMetaData().getDriverName().contains("H2")) {
            //    stmt.setBytes(4, PolicyManagerUtil.getBytes(feature.getContent()));
            // } else {
            stmt.setBytes(4, PolicyManagerUtil.getBytes(feature.getContent()));
            //}
            stmt.setInt(5, tenantId);
            stmt.addBatch();
            //Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
        }
        stmt.executeBatch();

        generatedKeys = stmt.getGeneratedKeys();
        int i = 0;

        while (generatedKeys.next()) {
            features.get(i).setId(generatedKeys.getInt(1));
            i++;
        }

    } catch (SQLException | IOException e) {
        throw new FeatureManagerDAOException("Error occurred while adding the feature list to the database.",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
    }
    return features;
}

From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java

private SAML2IDP retrieveBySourceID(byte[] baSourceID) throws OAException {
    Connection connection = null;
    PreparedStatement pSelect = null;
    ResultSet resultSet = null;//from  www. j  a v  a2  s .  c  o m
    SAML2IDP saml2IDP = null;

    IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId);

    try {
        connection = _dataSource.getConnection();

        pSelect = connection.prepareStatement(_sQuerySelectOnSourceID);
        pSelect.setBoolean(1, true);
        pSelect.setBytes(2, baSourceID);
        resultSet = pSelect.executeQuery();
        if (resultSet.next()) {
            boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX);

            Boolean boolAllowCreate = null;
            String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE);
            if (sAllowCreate != null) {
                boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE);
                boolAllowCreate = new Boolean(bAllowCreate);
            }

            boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING);
            boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY);
            boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF);
            boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO);

            Date dLastModified = null;
            try {
                dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED);
            } catch (Exception e) {
                _oLogger.info("No " + COLUMN_DATELASTMODIFIED + " column found for SAML2IDP with sourceid '"
                        + baSourceID + "'; ignoring.");
            }

            saml2IDP = new SAML2IDP(resultSet.getString(COLUMN_ID), baSourceID,
                    resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE),
                    resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT),
                    bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy,
                    resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP,
                    dLastModified, oMPM.getId());
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _oLogger.fatal("Internal error during retrieval of organization with SourceID: " + baSourceID, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        try {
            if (pSelect != null)
                pSelect.close();
        } catch (Exception e) {
            _oLogger.error("Could not close select statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            _oLogger.error("Could not close connection", e);
        }
    }
    return saml2IDP;
}