List of usage examples for java.sql PreparedStatement setBytes
void setBytes(int parameterIndex, byte x[]) throws SQLException;
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.SQLServerFeatureDAOImpl.java
@Override public List<ProfileFeature> addProfileFeatures(List<ProfileFeature> features, int profileId) throws FeatureManagerDAOException { Connection conn;//from w w w .j av a 2s.co 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(); // This logic has been commented out due to getGeneratedKeys method is not supported in MSSQL. // 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:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java
/** * Persistance model used in the rest of application is skipped due to to much design/coding overhead compared to demo-nature of this feature * Assumed that database will be on the same host as servlets * @throws SQLException//w w w .j a v a 2 s. c om */ private boolean persistSurvey(String surveyString, String surveyId, String surveyIdOriginal) { if (surveyString == null || surveyId == null) return false; boolean result = false; PreparedStatement insertSurveyStmt = null; Connection conn = null; try { conn = getDbConnection(); insertSurveyStmt = conn.prepareStatement(INSERT_SURVEY_STATEMENT); insertSurveyStmt.setString(1, surveyId); insertSurveyStmt.setString(2, surveyIdOriginal); insertSurveyStmt.setBytes(3, surveyString.getBytes("UTF-8")); insertSurveyStmt.executeUpdate(); result = true; } catch (UnsupportedEncodingException e) { e.printStackTrace(); result = false; } catch (SQLException e) { e.printStackTrace(); result = false; } finally { try { insertSurveyStmt.close(); conn.close(); } catch (Exception e) { } } return result; }
From source file:dao.ContactAddQuery.java
public void run(Connection conn, String fname, String lname, String mname, String dob, String title, String industry, String company, String pwebsite, String cwebsite, String blogsite, String city, String state, String country, String desc, String zipcode, String gender, String nickname, String designation, String bcity, String bstate, String bcountry, String bzipcode, String hphone, String cphone, String bphone, String yim, String aim, String msn, String icq, String loginId, String fax, String netphone, String relation, String email, String published, String usertag, String street, String bstreet) throws BaseDaoException { /**** use UTC_TIMESTAMP after upgrading mysql **/ // default date if (RegexStrUtil.isNull(dob)) { dob = "1970-01-01"; }/*from w w w . j av a 2 s . co m*/ byte[] mydesc = { ' ' }; if (!RegexStrUtil.isNull(desc)) { mydesc = desc.getBytes(); } byte[] mytag = { ' ' }; if (!RegexStrUtil.isNull(usertag)) { mytag = usertag.getBytes(); } PreparedStatement query = null; String stmt = "insert into hdcontacts values (" + 0 + ", " + loginId + ", '" + fname + "', '" + lname + "', '" + mname + "', '" + nickname + "'," + gender + ", '" + dob + "', '" + email + "', '" + designation + "', '" + title + "', '" + industry + "', '" + company + "', '" + pwebsite + "', '" + cwebsite + "', '" + blogsite + "', '" + street + "', '" + city + "', '" + state + "', '" + country + "', '" + zipcode + "',?, '" + bstreet + "', '" + bcity + "', '" + bstate + "', '" + bcountry + "', '" + bzipcode + "', '" + hphone + "', '" + cphone + "', '" + bphone + "', '" + netphone + "', '" + fax + "', '" + yim + "', '" + aim + "','" + msn + "', '" + icq + "','" + relation + "', '" + published + "', ?)"; try { query = conn.prepareStatement(stmt); query.setBytes(1, mydesc); query.setBytes(2, mytag); query.executeUpdate(); } catch (Exception e) { throw new BaseDaoException("Error occured while executing contact addquery" + stmt, e); } }
From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.OperationDAOImpl.java
@Override public void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException { PreparedStatement stmt = null; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; try {//from www .j a v a 2 s . co m Connection connection = OperationManagementDAOFactory.getConnection(); stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID,DEVICE_ID," + "OPERATION_RESPONSE) VALUES(?, ?, ?)"); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(operationResponse); stmt.setInt(1, operationId); stmt.setInt(2, enrolmentId); stmt.setBytes(3, bao.toByteArray()); stmt.executeUpdate(); } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while inserting operation response", e); } catch (IOException e) { throw new OperationManagementDAOException("Error occurred while serializing policy 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); } }
From source file:org.sentinel.instrumentationserver.metadata.MetadataDAO.java
/** * Save the metadata for an app that was instrumented and is specified to be made public. *///from ww w . j a v a2s. c om public void saveMetadataForInstrumentedApk(byte[] logo, String appName, String packageName, String sha512Hash, String sha256hash) { connectToDatabase(); long apkId = getApkId(sha512Hash); String sqlStatementSaveMetadataForInstrumentedApk = QueryBuilder.getQueryToSaveMetadataForInstrumentedApk(); try { if (getMetadataId(sha256hash) != -1) { String sqlStatementSaveInstrumentedApkIdForExistingMetadata = QueryBuilder .getQueryToLinkApkToMetadata(); PreparedStatement preparedStatement = databaseConnection .prepareStatement(sqlStatementSaveInstrumentedApkIdForExistingMetadata); preparedStatement.setLong(1, apkId); preparedStatement.setString(2, sha512Hash); preparedStatement.setString(3, sha256hash); preparedStatement.executeUpdate(); preparedStatement.close(); databaseConnection.close(); } else { PreparedStatement preparedStatement = databaseConnection .prepareStatement(sqlStatementSaveMetadataForInstrumentedApk); preparedStatement.setBytes(1, logo); preparedStatement.setString(2, appName); preparedStatement.setString(3, packageName); preparedStatement.setLong(4, apkId); preparedStatement.executeUpdate(); preparedStatement.close(); databaseConnection.close(); } } catch (SQLException e) { e.printStackTrace(); } }
From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java
private void storeDeviceList(Connection con, DeviceList deviceList, PublicKey pKey) throws SQLException, PersistanceException { Statement s = con.createStatement(); try {/* w w w . j a v a 2 s . c o m*/ createDLTables(s); } catch (SQLException e) { logger.error("Could not create DeviceList tables", e); } finally { s.close(); } PreparedStatement insert = con.prepareStatement(INSERT_DEVICE_LIST); Iterator<String> it = deviceList.getAliasIterator(); while (it.hasNext()) { String devAlias = it.next(); PublicKey devPubKey = deviceList.getPublicKey(devAlias); final byte[] encodedPubKey = devPubKey.getEncoded(); insert.setString(1, devAlias); insert.setBytes(2, encodedPubKey); int i = insert.executeUpdate(); logger.debug("Inserted " + i + " rows of devicelist"); } storeSignature(con, deviceList.getSignature()); if (insert != null) { try { insert.close(); } catch (Exception e) { logger.warn("Could not close Statement", e); } } }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
private void migrateConfigValues(Connection conn) { System.out.println("Begin migrate config values"); PreparedStatement pstmt = null; ResultSet rs = null;/*ww w . j a v a 2s . co m*/ try { pstmt = conn.prepareStatement( "select name, value from configuration where category in ('Hidden', 'Secure')"); rs = pstmt.executeQuery(); while (rs.next()) { String name = rs.getString(1); String value = rs.getString(2); if (value == null || value.isEmpty()) { continue; } String encryptedValue = migrateValue(value); pstmt = conn.prepareStatement("update configuration set value=? where name=?"); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setString(2, name); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to update configuration values ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable to update configuration values ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } System.out.println("End migrate config values"); }
From source file:org.tsm.concharto.model.geometry.GeometryUserType.java
/** * Write an instance of the mapped class to a prepared statement. Implementors * should handle possibility of null values. A multi-column type should be * written to parameters starting from <tt>index</tt>. * /*from w w w . j av a 2 s. c o m*/ * @param st a JDBC prepared statement * @param value the object to write * @param index statement parameter index * @throws HibernateException * @throws SQLException */ @SuppressWarnings("deprecation") public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.BLOB); } else { Geometry geom = (Geometry) value; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int SRID = geom.getSRID(); try { byte[] buf = new byte[4]; ByteOrderValues.putInt(SRID, buf, ByteOrderValues.LITTLE_ENDIAN); bos.write(buf); WKBWriter writer = new WKBWriter(2, ByteOrderValues.LITTLE_ENDIAN); writer.write(geom, new OutputStreamOutStream(bos)); } catch (IOException e) { // should be impossible throw new UnhandledException(e); } st.setBytes(index, bos.toByteArray()); } }
From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.PolicyOperationDAOImpl.java
@Override public int addOperation(Operation operation) throws OperationManagementDAOException { int operationId; PreparedStatement stmt = null; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; try {// w w w . j a v a 2 s.co m operationId = super.addOperation(operation); operation.setCreatedTimeStamp(new Timestamp(new java.util.Date().getTime()).toString()); operation.setId(operationId); operation.setEnabled(true); PolicyOperation policyOperation = (PolicyOperation) operation; Connection conn = OperationManagementDAOFactory.getConnection(); stmt = conn.prepareStatement( "INSERT INTO DM_POLICY_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 policy operation", e); } catch (IOException e) { throw new OperationManagementDAOException("Error occurred while serializing policy 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.apache.phoenix.query.BaseTest.java
protected static void createTestTable(String url, String ddl, byte[][] splits, Long ts, boolean swallowTableAlreadyExistsException) throws SQLException { assertNotNull(ddl);/*from w w w. j a va 2 s . c om*/ StringBuilder buf = new StringBuilder(ddl); if (splits != null) { buf.append(" SPLIT ON ("); for (int i = 0; i < splits.length; i++) { buf.append("?,"); } buf.setCharAt(buf.length() - 1, ')'); } ddl = buf.toString(); Properties props = new Properties(); if (ts != null) { props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts)); } Connection conn = DriverManager.getConnection(url, props); try { PreparedStatement stmt = conn.prepareStatement(ddl); if (splits != null) { for (int i = 0; i < splits.length; i++) { stmt.setBytes(i + 1, splits[i]); } } stmt.execute(ddl); } catch (TableAlreadyExistsException e) { if (!swallowTableAlreadyExistsException) { throw e; } } finally { conn.close(); } }