List of usage examples for java.sql PreparedStatement setBinaryStream
void setBinaryStream(int parameterIndex, java.io.InputStream x) throws SQLException;
From source file:org.codehaus.httpcache4j.storage.jdbc.JdbcCacheStorage.java
@Override public HTTPResponse insert(HTTPRequest request, HTTPResponse response) { Key key = Key.create(request, response); Connection connection = getConnection(); String sql = "insert into response(uri, vary, status, headers, payload, mimeType, cachetime) values (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement statement = null; try {/*w w w .j a v a2s. com*/ JdbcUtil.startTransaction(connection); invalidate(key, connection); statement = connection.prepareStatement(sql); statement.setString(1, key.getURI().toString()); statement.setString(2, key.getVary().toJSON()); statement.setInt(3, response.getStatus().getCode()); statement.setString(4, response.getHeaders().toJSON()); InputStream inputStream = null; if (response.hasPayload() && response.getPayload().isAvailable()) { statement.setString(6, response.getPayload().getMimeType().toString()); inputStream = response.getPayload().getInputStream(); statement.setBinaryStream(5, inputStream); } else { statement.setNull(5, Types.BLOB); statement.setNull(6, Types.VARCHAR); } statement.setTimestamp(7, new Timestamp(DateTimeUtils.currentTimeMillis())); try { statement.executeUpdate(); } finally { IOUtils.closeQuietly(inputStream); } connection.commit(); return getImpl(connection, key); } catch (SQLException e) { JdbcUtil.rollback(connection); JdbcUtil.close(connection); throw new DataAccessException(e); } finally { JdbcUtil.endTransaction(connection); JdbcUtil.close(statement); } }
From source file:org.wso2.carbon.analytics.datasource.rdbms.RDBMSAnalyticsRecordStore.java
private void populateStatementForAdd(PreparedStatement stmt, Record record) throws SQLException, AnalyticsException { stmt.setInt(1, this.generatePartitionKey(record.getId())); stmt.setLong(2, record.getTimestamp()); byte[] bytes = AnalyticsCommonUtils.encodeRecordValues(record.getValues()); if (!this.rdbmsQueryConfigurationEntry.isBlobLengthRequired()) { stmt.setBinaryStream(3, new ByteArrayInputStream(bytes)); } else {/*from ww w . ja v a2 s .c o m*/ stmt.setBinaryStream(3, new ByteArrayInputStream(bytes), bytes.length); } stmt.setString(4, record.getId()); }
From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java
private void setBinaryField(PreparedStatement statement, int fieldIndex, Object object) throws SQLException { InputStream is = null;/*from w w w . java2s. c o m*/ try { ByteArrayOutputStream bos = new ByteArrayOutputStream(4096); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); is = new ByteArrayInputStream(bos.toByteArray()); } catch (Exception e) { } ; statement.setBinaryStream(fieldIndex, is); }
From source file:org.apache.gora.sql.store.SqlStore.java
protected void setBytes(PreparedStatement statement, Column column, int index, byte[] value) throws SQLException { switch (column.getJdbcType()) { case BLOB:/* ww w .jav a 2 s. co m*/ statement.setBlob(index, new ByteArrayInputStream(value), value.length); break; case BINARY: case VARBINARY: statement.setBytes(index, value); break; case LONGVARBINARY: statement.setBinaryStream(index, new ByteArrayInputStream(value)); break; } }
From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java
/** * Method to add a new client certificate to the database. * * @param certificate : Client certificate that need to be added. * @param apiIdentifier : API which the client certificate is uploaded against. * @param alias : Alias for the new certificate. * @param tenantId : The Id of the tenant who uploaded the certificate. * @return : True if the information is added successfully, false otherwise. * @throws CertificateManagementException if existing entry is found for the given endpoint or alias. *//* w ww . jav a2 s . co m*/ public boolean addClientCertificate(String certificate, APIIdentifier apiIdentifier, String alias, String tierName, int tenantId, Connection connection) throws CertificateManagementException { boolean result = false; boolean isNewConnection = false; PreparedStatement preparedStatement = null; String addCertQuery = SQLConstants.ClientCertificateConstants.INSERT_CERTIFICATE; try { if (connection == null) { connection = APIMgtDBUtil.getConnection(); initialAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); isNewConnection = true; } int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, connection); preparedStatement = connection.prepareStatement(addCertQuery); preparedStatement.setBinaryStream(1, getInputStream(certificate)); preparedStatement.setInt(2, tenantId); preparedStatement.setString(3, alias); preparedStatement.setInt(4, apiId); preparedStatement.setString(5, tierName); result = preparedStatement.executeUpdate() >= 1; if (isNewConnection) { connection.commit(); } } catch (SQLException e) { handleConnectionRollBack(connection); if (log.isDebugEnabled()) { log.debug("Error occurred while adding client certificate details to database for the API " + apiIdentifier.toString(), e); } handleException("Error while persisting client certificate for the API " + apiIdentifier.toString(), e); } catch (APIManagementException e) { handleConnectionRollBack(connection); handleException("Error getting API details of the API " + apiIdentifier.toString() + " when storing " + "client certificate", e); } finally { if (isNewConnection) { APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit); APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null); } else { APIMgtDBUtil.closeAllConnections(preparedStatement, null, null); } } return result; }
From source file:org.wso2.carbon.identity.provisioning.dao.ProvisioningManagementDAO.java
/** * @param newIdentityProvider/* w w w . j a v a 2 s . co m*/ * @param currentIdentityProvider * @param tenantId * @throws IdentityApplicationManagementException */ public void updateProvisionedIdentifier(IdentityProvider newIdentityProvider, IdentityProvider currentIdentityProvider, int tenantId) throws IdentityApplicationManagementException { Connection dbConnection = IdentityDatabaseUtil.getDBConnection(); try { int idPId = getIdentityProviderIdByName(dbConnection, newIdentityProvider.getIdentityProviderName(), tenantId); if (idPId <= 0) { String msg = "Trying to update non-existent Identity Provider for tenant " + tenantId; throw new IdentityApplicationManagementException(msg); } PreparedStatement prepStmt = null; // SP_IDP_NAME=?, SP_IDP_PRIMARY=?,SP_IDP_HOME_REALM_ID=?, // SP_IDP_THUMBPRINT=?, // SP_IDP_TOKEN_EP_ALIAS=?, // SP_IDP_INBOUND_PROVISIONING_ENABLED=?,SP_IDP_INBOUND_PROVISIONING_USER_STORE_ID=?,SP_IDP_USER_CLAIM_URI=?, // SP_IDP_ROLE_CLAIM_URI=?,SP_IDP_DEFAULT_AUTHENTICATOR_NAME=?,SP_IDP_DEFAULT_PRO_CONNECTOR_NAME=? String sqlStmt = IdPManagementConstants.SQLQueries.UPDATE_IDP_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, newIdentityProvider.getIdentityProviderName()); if (newIdentityProvider.isPrimary()) { prepStmt.setString(2, "1"); } else { prepStmt.setString(2, "0"); } prepStmt.setString(3, newIdentityProvider.getHomeRealmId()); prepStmt.setBinaryStream(4, setBlobValue(newIdentityProvider.getCertificate())); prepStmt.setString(5, newIdentityProvider.getAlias()); if (newIdentityProvider.getJustInTimeProvisioningConfig() != null && newIdentityProvider.getJustInTimeProvisioningConfig().isProvisioningEnabled()) { prepStmt.setString(6, "1"); prepStmt.setString(7, newIdentityProvider.getJustInTimeProvisioningConfig().getProvisioningUserStore()); } else { prepStmt.setString(6, "0"); prepStmt.setString(7, null); } if (newIdentityProvider.getClaimConfig() != null) { prepStmt.setString(8, newIdentityProvider.getClaimConfig().getUserClaimURI()); prepStmt.setString(9, newIdentityProvider.getClaimConfig().getRoleClaimURI()); } else { prepStmt.setString(8, null); prepStmt.setString(9, null); } // update the default authenticator if (newIdentityProvider.getDefaultAuthenticatorConfig() != null && newIdentityProvider.getDefaultAuthenticatorConfig().getName() != null) { prepStmt.setString(10, newIdentityProvider.getDefaultAuthenticatorConfig().getName()); } else { // its not a must to have a default authenticator. prepStmt.setString(10, null); } // update the default provisioning connector. if (newIdentityProvider.getDefaultProvisioningConnectorConfig() != null && newIdentityProvider.getDefaultProvisioningConnectorConfig().getName() != null) { prepStmt.setString(11, newIdentityProvider.getDefaultProvisioningConnectorConfig().getName()); } else { // its not a must to have a default provisioning connector.. prepStmt.setString(11, null); } prepStmt.setString(12, newIdentityProvider.getIdentityProviderDescription()); prepStmt.setInt(13, tenantId); prepStmt.setString(14, currentIdentityProvider.getIdentityProviderName()); prepStmt.executeUpdate(); prepStmt.clearParameters(); IdentityApplicationManagementUtil.closeStatement(prepStmt); dbConnection.commit(); } catch (SQLException e) { IdentityApplicationManagementUtil.rollBack(dbConnection); String msg = "Error occurred while updating Identity Provider information for tenant " + tenantId; throw new IdentityApplicationManagementException(msg, e); } finally { IdentityApplicationManagementUtil.closeConnection(dbConnection); } }
From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public void createNodeHeartbeatEntry(String nodeId, String groupId, Map propertiesMap) throws ClusterCoordinationException { Connection connection = null; PreparedStatement preparedStatement = null; try {// w w w .j a va 2s . c o m connection = getConnection(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(propertiesMap); byte[] propertiesMapAsBytes = byteArrayOutputStream.toByteArray(); preparedStatement = connection.prepareStatement(RDBMSConstants.PS_INSERT_NODE_HEARTBEAT_ROW); preparedStatement.setString(1, nodeId); preparedStatement.setLong(2, System.currentTimeMillis()); preparedStatement.setString(3, groupId); preparedStatement.setBinaryStream(4, new ByteArrayInputStream(propertiesMapAsBytes)); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { rollback(connection, RDBMSConstants.TASK_CREATE_NODE_HEARTBEAT); throw new ClusterCoordinationException("Error occurred while " + RDBMSConstants.TASK_CREATE_NODE_HEARTBEAT + ". Node ID: " + nodeId + " group ID" + groupId, e); } catch (IOException e) { throw new ClusterCoordinationException(e); } finally { close(preparedStatement, RDBMSConstants.TASK_UPDATE_COORDINATOR_HEARTBEAT); close(connection, RDBMSConstants.TASK_CREATE_NODE_HEARTBEAT); } }
From source file:org.apache.gora.sql.store.SqlStore.java
/** Serializes the field using Avro to a BLOB field */ protected void setField(PreparedStatement statement, Column column, Schema schema, int index, Object object) throws IOException, SQLException { OutputStream os = null;// w ww . j av a 2s . com Blob blob = null; JdbcType type = column.getJdbcType(); switch (type) { case BLOB: blob = connection.createBlob(); os = blob.setBinaryStream(1); break; case BINARY: case VARBINARY: case LONGVARBINARY: os = new ByteBufferOutputStream(); break; } IOUtils.serialize(os, datumWriter, schema, object); os.close(); switch (type) { case BLOB: statement.setBlob(index, blob); break; case BINARY: case VARBINARY: statement.setBytes(index, IOUtils.getAsBytes(((ByteBufferOutputStream) os).getBufferList())); break; case LONGVARBINARY: statement.setBinaryStream(index, new ByteBufferInputStream(((ByteBufferOutputStream) os).getBufferList())); break; } }
From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java
private void updatePreparedStatement(String tablename, Hashtable<String, Object[]> fieldswithcontent, PreparedStatement ps) throws Exception { Enumeration en = fieldswithcontent.keys(); int i = 0;/*from w ww . j av a2 s.co m*/ while (en.hasMoreElements()) { i++; try { String field = (String) en.nextElement(); Object[] o2 = fieldswithcontent.get(field); String type = (String) o2[0]; Object o = o2[1]; //System.out.println(field+" "+type+" "+o); if (type.equals("string")) { ps.setString(i, (String) o); } else if (type.equals("byte[]") || type.equals("base64Binary")) { ps.setBinaryStream(i, new ByteArrayInputStream((byte[]) o)); } else if (type.equals("dateTime")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; Date d = null; if (cal.toString().indexOf("0003-11-30") > -1) { ps.setString(i, "0000-00-00 00:00:00"); } else { d = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(cal.toString()); ps.setTimestamp(i, new java.sql.Timestamp(d.getTime())); } } else if (type.equals("date")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; Date d1 = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(cal.toString()); ps.setDate(i, java.sql.Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(d1))); } else if (type.equals("time")) { XMLGregorianCalendar cal = (XMLGregorianCalendar) o; String c = cal.toString(); c = c.replaceFirst("0003-11-30", "0000-00-00"); Date d1 = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(c); ps.setTime(i, new java.sql.Time(d1.getTime())); } else if (type.equals("integer")) { ps.setInt(i, ((BigInteger) o).intValue()); } else if (type.equals("double")) { ps.setDouble(i, (Double) o); } else if (type.equals("float")) { ps.setFloat(i, (Float) o); } else if (type.equals("long")) { ps.setLong(i, (Long) o); } else { throw new Exception("unknown type [" + type + "] for field [" + field + "] encountered while trying to update table [" + tablename + "]."); } } catch (Exception e) { e.printStackTrace(); throw e; } } }
From source file:org.batoo.jpa.jdbc.dbutils.QueryRunner.java
/** * Fill the <code>PreparedStatement</code> replacement parameters with the given objects. * // w w w . jav a2 s .co m * @param statement * PreparedStatement to fill * @param params * Query replacement parameters; <code>null</code> is a valid value to pass in. * @throws SQLException * if a database access error occurs */ private void fillStatement(PreparedStatement statement, Object... params) throws SQLException { // use local variable for performance boolean pmdKnownBroken = this.pmdKnownBroken; ParameterMetaData pmd = this.pmd; final boolean hasLob = this.hasLob; if (pmdKnownBroken) { ((PreparedStatementProxy) statement).setParamCount(params.length); } else { ((PreparedStatementProxy) statement).setParamCount(-1); } // if the jdbc adaptor wants to modify the parameters we let it do it its own way final JdbcAdaptor jdbcAdaptor = this.jdbcAdaptor; if ((jdbcAdaptor != null) && jdbcAdaptor.modifiesParameters()) { pmd = this.pmd = statement.getParameterMetaData(); jdbcAdaptor.modifyParameters(pmd, params); } for (int i = 0; i < params.length; i++) { final Object param = params[i]; if ((param != null) && (param != Void.TYPE)) { if (hasLob && (param instanceof Clob)) { if (this.jdbcAdaptor instanceof OracleAdaptor) { statement.setCharacterStream(i + 1, ((Clob) param).getCharacterStream()); } else { statement.setClob(i + 1, (Clob) param); } } else if (hasLob && (param instanceof Blob)) { if (this.jdbcAdaptor instanceof OracleAdaptor) { statement.setBinaryStream(i + 1, ((Blob) param).getBinaryStream()); } else { statement.setBlob(i + 1, (Blob) param); } } else { statement.setObject(i + 1, param); } } else { if (!pmdKnownBroken && (pmd == null)) { pmd = this.pmd = statement.getParameterMetaData(); } // VARCHAR works with many drivers regardless of the actual column type. // Oddly, NULL and OTHER don't work with Oracle's drivers. int sqlType = Types.VARCHAR; if (!pmdKnownBroken) { try { sqlType = pmd.getParameterType(i + 1); } catch (final SQLException e) { pmdKnownBroken = this.pmdKnownBroken = true; } } if (param != Void.TYPE) { statement.setNull(i + 1, sqlType); } } } }