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:ttpserver.UserCreation.java

public void RegisterUser(int userid, String password) {
    byte[] userG = null;
    byte[] userK = null;
    byte[] userGK = null;
    byte[] userZK = null;
    byte[] pw = password.getBytes();
    KeyGen key;/*from   w w  w . java 2  s  .com*/
    User owner;
    pw = hash(pw);

    try {
        // Quan do this
        //yeah right

        //Pull common values (g, k, gk, zk and curveparams) from database
        DatabaseGetSet DB = new DatabaseGetSet();

        userG = DB.getG(1);
        userK = DB.getK(1);
        userGK = DB.getGK(1);
        userZK = DB.getZK(1);

        System.out.println(Arrays.toString(userG));

        //Create the private and public key

        //PairingParameters p = SerializationUtils.deserialize(userCurveParams); // not used
        Params pr = new Params(userG, userK, userGK, userZK);

        key = new KeyGen(pr);
        owner = key.generate();

        byte[] publicKey = owner.getPKBytes();
        byte[] privateKey = owner.getSKBytes();

        //Now create new user lalala
        //Set up the connection
        Connection connection = null;
        Statement stmt = null;

        try {
            connection = DatabaseManager.getInstance().getConnection();
            stmt = connection.createStatement();
            PreparedStatement pstmt = connection.prepareStatement(
                    "INSERT INTO USER_TABLE(userID, password, pairing, g, k, gk, zk,  publicKey, secretKey, role) VALUE(?,?,?,?,?,?,?,?,?,?)");

            //set values            
            pstmt.setInt(1, userid);
            pstmt.setBytes(2, pw);
            byte[] userCurveParams = null;
            pstmt.setBytes(3, userCurveParams);
            pstmt.setBytes(4, userG);
            pstmt.setBytes(5, userK);
            pstmt.setBytes(6, userGK);
            pstmt.setBytes(7, userZK);
            pstmt.setBytes(8, publicKey);
            pstmt.setBytes(9, privateKey);
            pstmt.setInt(10, 0);
            pstmt.executeUpdate();

        } catch (Exception ex) {
            //Logger.getLogger(TTPServer.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (Exception e1) {
                System.out.println("Exception while closing connection::" + e1.getMessage());
            }
            try {
                stmt.close();
            } catch (Exception e2) {
                System.out.println("Exception while closing statement::" + e2.getMessage());
            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(UserCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(UserCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(UserCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(UserCreation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JDOMException ex) {
        Logger.getLogger(UserCreation.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

private void migrate_sources_with_scm_and_coverage_in(String columnName) throws Exception {
    db.prepareDbUnit(getClass(), "before.xml");

    Connection connection = null;
    try {/*from  ww  w  . j a v a2s.  c  o m*/
        connection = db.openConnection();

        db.executeUpdateSql("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')");

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

        PreparedStatement revisionStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(1, 6, ?)");
        revisionStmt.setBytes(1, "1=aef12a;2=abe465;3=afb789;4=afb789".getBytes(StandardCharsets.UTF_8));
        revisionStmt.executeUpdate();
        revisionStmt.close();

        PreparedStatement authorStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(2, 6, ?)");
        authorStmt.setBytes(1, "1=alice;2=bob;3=carol;4=carol".getBytes(StandardCharsets.UTF_8));
        authorStmt.executeUpdate();
        authorStmt.close();

        PreparedStatement dateStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(3, 6, ?)");
        dateStmt.setBytes(1,
                "1=2014-04-25T12:34:56+0100;2=2014-07-25T12:34:56+0100;3=2014-03-23T12:34:56+0100;4=2014-03-23T12:34:56+0100"
                        .getBytes(StandardCharsets.UTF_8));
        dateStmt.executeUpdate();
        dateStmt.close();

        PreparedStatement utHitsStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(4, 6, ?)");
        utHitsStmt.setBytes(1, "1=1;3=0".getBytes(StandardCharsets.UTF_8));
        utHitsStmt.executeUpdate();
        utHitsStmt.close();

        PreparedStatement utCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(5, 6, ?)");
        utCondStmt.setBytes(1, "1=4".getBytes(StandardCharsets.UTF_8));
        utCondStmt.executeUpdate();
        utCondStmt.close();

        PreparedStatement utCoveredCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(6, 6, ?)");
        utCoveredCondStmt.setBytes(1, "1=2".getBytes(StandardCharsets.UTF_8));
        utCoveredCondStmt.executeUpdate();
        utCoveredCondStmt.close();

        PreparedStatement itHitsStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(7, 6, ?)");
        itHitsStmt.setBytes(1, "1=2;3=0".getBytes(StandardCharsets.UTF_8));
        itHitsStmt.executeUpdate();
        itHitsStmt.close();

        PreparedStatement itCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(8, 6, ?)");
        itCondStmt.setBytes(1, "1=5".getBytes(StandardCharsets.UTF_8));
        itCondStmt.executeUpdate();
        itCondStmt.close();

        PreparedStatement itCoveredCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(9, 6, ?)");
        itCoveredCondStmt.setBytes(1, "1=3".getBytes(StandardCharsets.UTF_8));
        itCoveredCondStmt.executeUpdate();
        itCoveredCondStmt.close();

        PreparedStatement overallHitsStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(10, 6, ?)");
        overallHitsStmt.setBytes(1, "1=3;3=0".getBytes(StandardCharsets.UTF_8));
        overallHitsStmt.executeUpdate();
        overallHitsStmt.close();

        PreparedStatement overallCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(11, 6, ?)");
        overallCondStmt.setBytes(1, "1=6".getBytes(StandardCharsets.UTF_8));
        overallCondStmt.executeUpdate();
        overallCondStmt.close();

        PreparedStatement overallCoveredCondStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "values " + "(12, 6, ?)");
        overallCoveredCondStmt.setBytes(1, "1=4".getBytes(StandardCharsets.UTF_8));
        overallCoveredCondStmt.executeUpdate();
        overallCoveredCondStmt.close();

        PreparedStatement duplicationDataStmt = connection.prepareStatement("insert into project_measures "
                + "(metric_id, snapshot_id, " + columnName + ") " + "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\"/></g></duplications>"
                        .getBytes(StandardCharsets.UTF_8));
        duplicationDataStmt.executeUpdate();
        duplicationDataStmt.close();
    } finally {
        DbUtils.commitAndCloseQuietly(connection);
    }

    migration.execute();

    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(
            "aef12a,alice,2014-04-25T12:34:56+0100,1,4,2,2,5,3,3,6,4,,,1,class Foo {\r\nabe465,bob,2014-07-25T12:34:56+0100,,,,,,,,,,,,2,  "
                    + "// Empty\r\nafb789,carol,2014-03-23T12:34:56+0100,0,,,0,,,0,,,,,,}\r\nafb789,carol,2014-03-23T12:34:56+0100,,,,,,,,,,,,,\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:edu.jhu.pha.vospace.jobs.JobsProcessor.java

/**
 * Adds the new job to the SQL database/*from   ww  w .j a v a 2  s  . com*/
 * @param job The job description object
 */
public void submitJob(final String login, final JobDescription job) {
    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    final byte[] jobSer;
    try {
        jobSer = (new ObjectMapper()).writeValueAsBytes(job);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new InternalServerErrorException(ex.getMessage());
    }

    DbPoolServlet.goSql("Submit job",
            "insert into jobs (id,user_id,starttime,state,direction,target,json_notation) select ?, user_id, ?,?,?,?,? from user_identities WHERE identity = ?",
            new SqlWorker<Integer>() {
                @Override
                public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    stmt.setString(1, job.getId());
                    stmt.setString(2, dateFormat.format(job.getStartTime().getTime()));
                    stmt.setString(3, job.getState().toString());
                    stmt.setString(4, job.getDirection().toString());
                    stmt.setString(5, job.getTarget().toString());
                    stmt.setBytes(6, jobSer);
                    stmt.setString(7, login);
                    return stmt.executeUpdate();
                }
            });
}

From source file:nl.ordina.bag.etl.dao.postgres.BAGMutatiesDAOImpl.java

@Override
public long insertMutatiesFile(final java.util.Date dateFrom, final java.util.Date dateTo, final byte[] content)
        throws DAOException {
    try {//w  w  w  .  j av  a2s. c  o  m
        return jdbcTemplate.query(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement("insert into bag_mutaties_file (" + " id,"
                        + " date_from," + " date_to," + " content"
                        + ") values ((select coalesce(max(id),0) + 1 from bag_mutaties_file),date_trunc('day', ?::timestamp),date_trunc('day', ?::timestamp),?)"
                        + " returning id");
                ps.setDate(1, new Date(dateFrom.getTime()));
                ps.setDate(2, new Date(dateTo.getTime()));
                ps.setBytes(3, content);
                return ps;
            }
        }, new IdExtractor());
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:org.jboss.dashboard.database.hibernate.BinaryBlobType.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((byte[]) value);
            }/* w  ww .ja  v  a2  s . c o m*/
        }

        public void writeValue(PreparedStatement st, Object value, int index) throws SQLException {
            st.setBytes(index, (byte[]) value);
        }
    });
}

From source file:org.openscore.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

@Override
public void insertExecutionStates(final List<ExecutionMessage> stateMessages) {
    String insertExecStateSQL = INSERT_EXEC_STATE;
    insertExecStateSQL = insertExecStateSQL.replaceAll(":OO_EXECUTION_STATES", getExecStateTableName());
    jdbcTemplate.batchUpdate(insertExecStateSQL, new BatchPreparedStatementSetter() {

        @Override/*from w w w. j av  a  2s . c o  m*/
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ExecutionMessage msg = stateMessages.get(i);
            ps.setLong(1, msg.getExecStateId());
            ps.setString(2, msg.getMsgId());
            ps.setBytes(3, msg.getPayload().getData());
        }

        @Override
        public int getBatchSize() {
            return stateMessages.size();
        }
    });
}

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

@Override
public List<IaPrefix> findUnusedIaPrefixes(final InetAddress startAddr, final InetAddress endAddr) {
    final long offerExpiration = new Date().getTime() - 12000; // 2 min = 120 sec = 12000 ms
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaPrefix.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaPrefix.EXPIRED + " or state=" + IaPrefix.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override/*from ww  w .  ja  va 2  s  . c  om*/
                public void setValues(PreparedStatement ps) throws SQLException {
                    java.sql.Timestamp ts = new java.sql.Timestamp(offerExpiration);
                    ps.setTimestamp(1, ts);
                    ps.setBytes(2, startAddr.getAddress());
                    ps.setBytes(3, endAddr.getAddress());
                }
            }, new DhcpLeaseRowMapper());
    return toIaPrefixes(leases);
}

From source file:io.cloudslang.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

@Override
public void insertExecutionStates(final List<ExecutionMessage> stateMessages) {
    String insertExecStateSQL = INSERT_EXEC_STATE;
    insertExecutionJDBCTemplate.batchUpdate(insertExecStateSQL, new BatchPreparedStatementSetter() {

        @Override/*w w  w  .j  av a  2  s. c  o m*/
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ExecutionMessage msg = stateMessages.get(i);
            ps.setLong(1, msg.getExecStateId());
            ps.setString(2, msg.getMsgId());
            ps.setBytes(3, msg.getPayload().getData());
        }

        @Override
        public int getBatchSize() {
            return stateMessages.size();
        }
    });
}

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

public void create(final IaAddress iaAddr) {
    /**/*from   w w  w.  j  ava2s  .c o m*/
     * Note: see https://issues.apache.org/jira/browse/DERBY-3609
     * "Formally, Derby does not support getGeneratedKeys since 
     * DatabaseMetaData.supportsGetGeneratedKeys() returns false. 
     * However, Statement.getGeneratedKeys() is partially implemented,
     * ... since it will only return a meaningful result when an single 
     * row insert is done with INSERT...VALUES"
     * 
     * Spring has thus provided a workaround as described here:
     * http://jira.springframework.org/browse/SPR-5306
     */
    GeneratedKeyHolder newKey = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(
                    "insert into iaaddress" + " (ipaddress, starttime, preferredendtime, validendtime,"
                            + " state, identityassoc_id)" + " values (?, ?, ?, ?, ?, ?)",
                    PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setBytes(1, iaAddr.getIpAddress().getAddress());
            java.sql.Timestamp sts = new java.sql.Timestamp(iaAddr.getStartTime().getTime());
            ps.setTimestamp(2, sts, Util.GMT_CALENDAR);
            java.sql.Timestamp pts = new java.sql.Timestamp(iaAddr.getPreferredEndTime().getTime());
            ps.setTimestamp(3, pts, Util.GMT_CALENDAR);
            java.sql.Timestamp vts = new java.sql.Timestamp(iaAddr.getValidEndTime().getTime());
            ps.setTimestamp(4, vts, Util.GMT_CALENDAR);
            ps.setByte(5, iaAddr.getState());
            ps.setLong(6, iaAddr.getIdentityAssocId());
            return ps;
        }
    }, newKey);
    Number newId = newKey.getKey();
    if (newId != null) {
        iaAddr.setId(newId.longValue());
    }
}

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

@Override
public List<IaAddress> findUnusedIaAddresses(final InetAddress startAddr, final InetAddress endAddr) {
    long offerExpireMillis = DhcpServerPolicies.globalPolicyAsLong(Property.BINDING_MANAGER_OFFER_EXPIRATION);
    final long offerExpiration = new Date().getTime() - offerExpireMillis;
    List<DhcpLease> leases = getJdbcTemplate().query(
            "select * from dhcplease" + " where ((state=" + IaAddress.ADVERTISED + " and starttime <= ?)"
                    + " or (state=" + IaAddress.EXPIRED + " or state=" + IaAddress.RELEASED + "))"
                    + " and ipaddress >= ? and ipaddress <= ?" + " order by state, validendtime, ipaddress",
            new PreparedStatementSetter() {
                @Override//from w ww.ja v  a 2 s  .  com
                public void setValues(PreparedStatement ps) throws SQLException {
                    java.sql.Timestamp ts = new java.sql.Timestamp(offerExpiration);
                    ps.setTimestamp(1, ts);
                    ps.setBytes(2, startAddr.getAddress());
                    ps.setBytes(3, endAddr.getAddress());
                }
            }, new DhcpLeaseRowMapper());
    return toIaAddresses(leases);
}