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:org.apache.synapse.message.store.impl.jdbc.JDBCMessageStore.java

/**
 * Process statements that do not give a ResultSet
 *
 * @param stmnt - Statement to process/*  w w  w  . j a v a2s  .co  m*/
 * @return - Success or Failure of the process
 */
private boolean processNonResultingStatement(Statement stmnt) throws SynapseException {
    Connection con = null;
    boolean result = false;
    PreparedStatement ps = null;

    try {
        con = jdbcConfiguration.getConnection();
        ps = con.prepareStatement(stmnt.getRawStatement());
        int index = 1;
        for (Object param : stmnt.getParameters()) {
            if (param instanceof String) {
                ps.setString(index, (String) param);
            } else if (param instanceof StorableMessage) {
                //Serialize the object into byteArray and update the statement
                ps.setBytes(index, serialize(param));
            }
            index++;
        }
        ps.execute();
        result = true;
    } catch (SQLException e) {
        throw new SynapseException("Processing Statement failed : " + stmnt.getRawStatement()
                + " against DataSource : " + jdbcConfiguration.getDSName(), e);
    } catch (IOException ex) {
        throw new SynapseException("Processing Statement failed : " + stmnt.getRawStatement()
                + " against DataSource : " + jdbcConfiguration.getDSName(), ex);
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                logger.error("Error while closing prepared statement", e);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                logger.error("Error while closing connection", e);
            }
        }
    }
    return result;
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.ProfileOperationDAOImpl.java

public int addOperation(Operation operation) throws OperationManagementDAOException {
    PreparedStatement stmt = null;
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos = null;

    int operationId;
    try {/*from   w ww  . j a v a 2 s. c om*/
        operationId = super.addOperation(operation);
        operation.setCreatedTimeStamp(new Timestamp(new java.util.Date().getTime()).toString());
        operation.setId(operationId);
        operation.setEnabled(true);
        //ProfileOperation profileOp = (ProfileOperation) operation;
        Connection conn = OperationManagementDAOFactory.getConnection();
        stmt = conn.prepareStatement(
                "INSERT INTO DM_PROFILE_OPERATION(OPERATION_ID, OPERATION_DETAILS) " + "VALUES(?, ?)");

        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(operation);

        stmt.setInt(1, operationId);
        stmt.setBytes(2, bao.toByteArray());
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new OperationManagementDAOException("Error occurred while adding profile operation", e);
    } catch (IOException e) {
        throw new OperationManagementDAOException("Error occurred while serializing profile operation object",
                e);
    } finally {
        if (bao != null) {
            try {
                bao.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                log.warn("Error occurred while closing ObjectOutputStream", e);
            }
        }
        OperationManagementDAOUtil.cleanupResources(stmt);
    }
    return operationId;
}

From source file:org.openecomp.sdnc.sli.resource.sql.SqlResource.java

private String decryptColumn(String tableName, String colName, byte[] colValue, DbLibService dblibSvc) {
    String strValue = new String(colValue);

    if (StringUtils.isAsciiPrintable(strValue)) {

        // If printable, not encrypted
        return (strValue);
    } else {/*from ww  w  . java  2s  . co m*/
        PreparedStatement stmt = null;
        Connection conn = null;
        ResultSet results = null;
        try {
            // CachedRowSet results =
            // dblibSvc.getData("SELECT
            // CAST(AES_DECRYPT('"+strValue+"','"+CRYPT_KEY+"') AS CHAR(50))
            // FROM DUAL",
            // null, null);
            conn = ((DBResourceManager) dblibSvc).getConnection();

            stmt = conn.prepareStatement("SELECT CAST(AES_DECRYPT(?, ?) AS CHAR(50)) FROM DUAL");

            stmt.setBytes(1, colValue);
            stmt.setString(2, getCryptKey());

            results = stmt.executeQuery();

            if ((results != null) && results.next()) {
                strValue = results.getString(1);
                LOG.debug("Decrypted value is " + strValue);
            } else {
                LOG.warn("Cannot decrypt " + tableName + "." + colName);
            }
        } catch (Exception e) {
            LOG.error("Caught exception trying to decrypt " + tableName + "." + colName, e);
        } finally {
            try {
                if (results != null) {
                    results.close();
                    results = null;
                }
            } catch (Exception exc) {

            }

            try {
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
            } catch (Exception exc) {

            }

            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (Exception exc) {

            }

        }
    }
    return (strValue);
}

From source file:org.openmrs.util.databasechange.CopyFormMetadataChangeSet.java

/**
 * @see CustomTaskChange#execute(Database)
 *//*from w  w w.  ja v a2  s.c  om*/
public void execute(Database database) throws CustomChangeException, UnsupportedChangeException {
    DatabaseConnection connection = database.getConnection();

    String getFormMetadataSql = "SELECT form_id, xslt, template FROM form";

    StringBuilder insertFormMetadataSql = new StringBuilder();
    insertFormMetadataSql.append("INSERT INTO form_resource");
    insertFormMetadataSql.append(" (form_id, owner, name, value, uuid)");
    insertFormMetadataSql.append(" VALUES (?, ?, ?, ?, ?)");

    PreparedStatement insertStatement = null;

    try {
        insertStatement = connection.prepareStatement(insertFormMetadataSql.toString());

        // iterate over deleted HL7s
        ResultSet forms = connection.createStatement().executeQuery(getFormMetadataSql);
        while (forms.next()) {

            // define the xslt object
            byte[] xslt = forms.getString(2) == null ? null : forms.getString(2).getBytes();

            // define the template object
            byte[] template = forms.getString(3) == null ? null : forms.getString(3).getBytes();

            // add xslt
            if (xslt != null) {
                insertStatement.setInt(1, forms.getInt(1));
                insertStatement.setString(2, FormConstants.FORM_RESOURCE_FORMENTRY_OWNER);
                insertStatement.setString(3, FormConstants.FORM_RESOURCE_FORMENTRY_XSLT);
                insertStatement.setBytes(4, xslt);
                insertStatement.setString(5, UUID.randomUUID().toString());
                insertStatement.executeUpdate();
            }

            // add template
            if (template != null) {
                insertStatement.setInt(1, forms.getInt(1));
                insertStatement.setString(2, FormConstants.FORM_RESOURCE_FORMENTRY_OWNER);
                insertStatement.setString(3, FormConstants.FORM_RESOURCE_FORMENTRY_TEMPLATE);
                insertStatement.setBytes(4, template);
                insertStatement.setString(5, UUID.randomUUID().toString());
                insertStatement.executeUpdate();
            }
        }

        // cleanup
        if (insertStatement != null)
            insertStatement.close();

    } catch (SQLException e) {
        throw new CustomChangeException("Unable to copy form metadata to form attributes table", e);
    }
}

From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationMappingDAOImpl.java

@Override
public void addApplicationMappingsWithApps(int deviceId, int enrolmentId, List<Application> applications,
        int tenantId) throws DeviceManagementDAOException {

    Connection conn;/*from  w  w  w  .ja  va 2 s . c  o  m*/
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos = null;

    try {
        conn = this.getConnection();
        String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, ENROLMENT_ID, APPLICATION_ID, "
                + "APP_PROPERTIES, MEMORY_USAGE, IS_ACTIVE, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)";

        conn.setAutoCommit(false);
        stmt = conn.prepareStatement(sql);

        for (Application application : applications) {
            stmt.setInt(1, deviceId);
            stmt.setInt(2, enrolmentId);
            stmt.setInt(3, application.getId());

            bao = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bao);
            oos.writeObject(application.getAppProperties());
            stmt.setBytes(4, bao.toByteArray());

            stmt.setInt(5, application.getMemoryUsage());
            stmt.setBoolean(6, application.isActive());

            stmt.setInt(7, tenantId);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        throw new DeviceManagementDAOException("Error occurred while adding device application mappings", e);
    } catch (IOException e) {
        throw new DeviceManagementDAOException("Error occurred while serializing application properties object",
                e);
    } finally {
        if (bao != null) {
            try {
                bao.close();
            } catch (IOException e) {
                log.error("Error occurred while closing ByteArrayOutputStream", e);
            }
        }
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                log.error("Error occurred while closing ObjectOutputStream", e);
            }
        }
        DeviceManagementDAOUtil.cleanupResources(stmt, rs);
    }

}

From source file:org.sonar.db.version.v50.FeedFileSourcesTest.java

@Test
public void migrate_sources_with_invalid_duplication() throws Exception {
    db.prepareDbUnit(getClass(), "before.xml");

    Connection connection = null;
    PreparedStatement duplicationDataStmt = null;
    try {/*from  w w  w .j ava  2s  .  c  o  m*/
        connection = db.openConnection();

        connection
                .prepareStatement("insert into snapshot_sources " + "(snapshot_id, data, updated_at) "
                        + "values " + "(6, 'class Foo {\r\n  // Empty\r\n}\r\n', '2014-10-31 16:44:02.000')")
                .executeUpdate();

        db.executeUpdateSql("insert into snapshot_sources " + "(snapshot_id, data, updated_at) " + "values "
                + "(7, '', '2014-10-31 16:44:02.000')");

        duplicationDataStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, text_value) " + "values " + "(13, 6, ?)");
        duplicationDataStmt.setBytes(1,
                "<duplications><g><b s=\"1\" l=\"1\" r=\"MyProject:src/main/xoo/prj/MyFile.xoo\"/><b s=\"2\" l=\"1\" r=\"MyProject:src/main/xoo/prj/MyFile.xoo\"/><b s=\"3\" l=\"1\" r=\"MyProject:src/main/xoo/prj/AnotherFile.xoo\"/"
                        .getBytes(StandardCharsets.UTF_8));
        duplicationDataStmt.executeUpdate();
    } finally {
        DbUtils.close(duplicationDataStmt);
        DbUtils.commitAndCloseQuietly(connection);
    }

    migration.execute();

    // db.assertDbUnit(getClass(), "after-with-invalid-duplication.xml", "file_sources");

    List<Map<String, Object>> results = getFileSources();
    assertThat(results).hasSize(2);

    assertThat(results.get(0).get("projectUuid")).isEqualTo("uuid-MyProject");
    assertThat(results.get(0).get("fileUuid")).isEqualTo("uuid-Migrated.xoo");
    assertThat(results.get(0).get("data")).isEqualTo("");
    assertThat(results.get(0).get("lineHashes")).isEqualTo("");
    assertThat(results.get(0).get("dataHash")).isEqualTo("");
    assertThat(results.get(0).get("updatedAt")).isEqualTo(NOW);
    assertThat(results.get(0).get("createdAt")).isEqualTo(1416238020000L);

    assertThat(results.get(1).get("projectUuid")).isEqualTo("uuid-MyProject");
    assertThat(results.get(1).get("fileUuid")).isEqualTo("uuid-MyFile.xoo");
    assertThat(results.get(1).get("data")).isEqualTo(
            ",,,,,,,,,,,,,,,class Foo {\r\n,,,,,,,,,,,,,,,  // Empty\r\n,,,,,,,,,,,,,,,}\r\n,,,,,,,,,,,,,,,\r\n");
    assertThat(results.get(1).get("lineHashes")).isEqualTo(
            "6a19ce786467960a3a9b0d26383a464a\naab2dbc5fdeaa80b050b1d049ede357c\ncbb184dd8e05c9709e5dcaedaa0495cf\n\n");
    assertThat(results.get(1).get("dataHash")).isEqualTo("");
    assertThat(formatLongDate((long) results.get(1).get("updatedAt")).toString()).startsWith("2014-10-31");
    assertThat(results.get(1).get("createdAt")).isEqualTo(NOW);
}

From source file:com.jagornet.dhcp.db.JdbcLeaseManager.java

/**
 * Update dhcp lease./*from w  w w.j av  a  2s.  c o m*/
 *
 * @param lease the lease
 */
protected void updateDhcpLease(final DhcpLease lease) {
    getJdbcTemplate().update(
            "update dhcplease" + " set state=?," + " starttime=?," + " preferredendtime=?," + " validendtime=?,"
                    + " ia_options=?," + " ipaddr_options=?" + " where ipaddress=?",
            new PreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps) throws SQLException {
                    ps.setByte(1, lease.getState());
                    java.sql.Timestamp sts = new java.sql.Timestamp(lease.getStartTime().getTime());
                    ps.setTimestamp(2, sts, Util.GMT_CALENDAR);
                    java.sql.Timestamp pts = new java.sql.Timestamp(lease.getPreferredEndTime().getTime());
                    ps.setTimestamp(3, pts, Util.GMT_CALENDAR);
                    java.sql.Timestamp vts = new java.sql.Timestamp(lease.getValidEndTime().getTime());
                    ps.setTimestamp(4, vts, Util.GMT_CALENDAR);
                    ps.setBytes(5, encodeOptions(lease.getIaDhcpOptions()));
                    ps.setBytes(6, encodeOptions(lease.getIaAddrDhcpOptions()));
                    ps.setBytes(7, lease.getIpAddress().getAddress());
                }
            });
}

From source file:org.jboss.dashboard.database.hibernate.StringBlobType.java

public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    LOBHelper.lookup().nullSafeSet(st, value, index, new LOBHelper.ValueWriter() {
        public void writeValue(OutputStream os, Object value) throws IOException {
            if (value != null) {
                os.write(((String) value).getBytes(STRING_ENCODING));
            }/* w w w  .  ja v a2 s  . com*/
        }

        public void writeValue(PreparedStatement st, Object value, int index) throws SQLException {
            HibernateInitializer hi = CoreServices.lookup().getHibernateInitializer();
            if (hi.isPostgresDatabase()) {
                st.setString(index, ((String) value));
            } else if (hi.isH2Database()) {
                st.setString(index, ((String) value));
            } else if (hi.isMySQLDatabase()) {
                try {
                    st.setBytes(index, value == null ? null : ((String) value).getBytes(STRING_ENCODING));
                } catch (UnsupportedEncodingException e) {
                    log.error("Error: ", e);
                }
            } else if (hi.isSQLServerDatabase()) {
                st.setString(index, (String) value);
            } else {
                throw new IllegalArgumentException("Unknown database name: " + hi.getDatabaseName());
            }
        }
    });
}

From source file:org.cerberus.crud.dao.impl.TestCaseCountryPropertiesDAO.java

@Override
public void updateTestCaseCountryProperties(TestCaseCountryProperties testCaseCountryProperties)
        throws CerberusException {
    boolean throwExcep = false;
    StringBuilder query = new StringBuilder();
    query.append("UPDATE testcasecountryproperties SET ");
    query.append(/* ww  w .  ja v  a2s  . c o m*/
            " `Description` = ?, `Type` = ? ,`Database` = ? ,Value1 = ?,Value2 = ?,`Length` = ?,  RowLimit = ?,  `Nature` = ? ,  `RetryNb` = ? ,  `RetryPeriod` = ? ");
    query.append(" WHERE Test = ? AND TestCase = ? AND Country = ? AND hex(`Property`) like hex(?)");

    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            preStat.setBytes(1, testCaseCountryProperties.getDescription().getBytes("UTF-8"));
            preStat.setString(2, testCaseCountryProperties.getType());
            preStat.setString(3, testCaseCountryProperties.getDatabase());
            preStat.setBytes(4, testCaseCountryProperties.getValue1().getBytes("UTF-8"));
            preStat.setBytes(5, testCaseCountryProperties.getValue2().getBytes("UTF-8"));
            preStat.setInt(6, testCaseCountryProperties.getLength());
            preStat.setInt(7, testCaseCountryProperties.getRowLimit());
            preStat.setString(8, testCaseCountryProperties.getNature());
            preStat.setInt(9, testCaseCountryProperties.getRetryNb());
            preStat.setInt(10, testCaseCountryProperties.getRetryPeriod());
            preStat.setString(11, testCaseCountryProperties.getTest());
            preStat.setString(12, testCaseCountryProperties.getTestCase());
            preStat.setString(13, testCaseCountryProperties.getCountry());
            preStat.setBytes(14, testCaseCountryProperties.getProperty().getBytes("UTF-8"));

            preStat.executeUpdate();
            throwExcep = false;

        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
        } catch (UnsupportedEncodingException ex) {
            LOG.error(ex.toString());
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
    if (throwExcep) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.CANNOT_UPDATE_TABLE));
    }
}

From source file:net.pms.dlna.DLNAMediaDatabase.java

public synchronized void updateThumbnail(String name, long modified, int type, DLNAMediaInfo media) {
    Connection conn = null;/*from  w  w w .j  a  v a 2  s.  co m*/
    PreparedStatement ps = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement("UPDATE FILES SET THUMB = ? WHERE FILENAME = ? AND MODIFIED = ?");
        ps.setString(2, name);
        ps.setTimestamp(3, new Timestamp(modified));
        if (media != null) {
            ps.setBytes(1, media.getThumb());
        } else {
            ps.setNull(1, Types.BINARY);
        }
        ps.executeUpdate();
    } catch (SQLException se) {
        if (se.getErrorCode() == 23001) {
            logger.debug("Duplicate key while inserting this entry: " + name + " into the database: "
                    + se.getMessage());
        } else {
            logger.error(null, se);
        }
    } finally {
        close(ps);
        close(conn);
    }
}