List of usage examples for java.sql PreparedStatement addBatch
void addBatch() throws SQLException;
PreparedStatement
object's batch of commands. From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public void storeMembershipEvent(String changedMember, String groupId, List<String> clusterNodes, int membershipEventType) throws ClusterCoordinationException { Connection connection = null; PreparedStatement storeMembershipEventPreparedStatement = null; String task = "Storing membership event: " + membershipEventType + " for member: " + changedMember + " in group " + groupId; try {/*from w ww.jav a2 s .co m*/ connection = getConnection(); storeMembershipEventPreparedStatement = connection .prepareStatement(RDBMSConstants.PS_INSERT_MEMBERSHIP_EVENT); for (String clusterNode : clusterNodes) { storeMembershipEventPreparedStatement.setString(1, clusterNode); storeMembershipEventPreparedStatement.setString(2, groupId); storeMembershipEventPreparedStatement.setInt(3, membershipEventType); storeMembershipEventPreparedStatement.setString(4, changedMember); storeMembershipEventPreparedStatement.addBatch(); } storeMembershipEventPreparedStatement.executeBatch(); connection.commit(); } catch (SQLException e) { rollback(connection, task); throw new ClusterCoordinationException("Error storing membership change: " + membershipEventType + " for member: " + changedMember + " in group " + groupId, e); } finally { close(storeMembershipEventPreparedStatement, task); close(connection, task); } }
From source file:org.wso2.carbon.apimgt.migration.client.MigrateFrom110to200.java
private void updateAuthzUserName() throws SQLException { log.info("Updating Authz UserName for API Manager started"); Connection connection = null; PreparedStatement selectStatement = null; ResultSet resultSet = null;/*from w w w . j a va2 s. c o m*/ ArrayList<AccessTokenInfo> updateValues = new ArrayList<>(); try { String selectQuery = "SELECT DISTINCT AUTHZ_USER FROM IDN_OAUTH2_ACCESS_TOKEN WHERE AUTHZ_USER LIKE '%@%'"; connection = APIMgtDBUtil.getConnection(); selectStatement = connection.prepareStatement(selectQuery); resultSet = selectStatement.executeQuery(); while (resultSet.next()) { String authzUser = resultSet.getString("AUTHZ_USER"); String usernameWithoutDomain = MultitenantUtils.getTenantAwareUsername(authzUser); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(usernameWithoutDomain, authzUser); updateValues.add(accessTokenInfo); } } finally { APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet); } if (!updateValues.isEmpty()) { // If user names that need to be updated exist PreparedStatement updateStatement = null; try { connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); updateStatement = connection.prepareStatement( "UPDATE IDN_OAUTH2_ACCESS_TOKEN SET AUTHZ_USER = ?" + " WHERE AUTHZ_USER = ?"); for (AccessTokenInfo accessTokenInfo : updateValues) { updateStatement.setString(1, accessTokenInfo.usernameWithoutDomain); updateStatement.setString(2, accessTokenInfo.authzUser); updateStatement.addBatch(); } updateStatement.executeBatch(); connection.commit(); } finally { APIMgtDBUtil.closeAllConnections(updateStatement, connection, null); } } log.info("Updating Authz UserName for API Manager completed"); }
From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java
/** * {@inheritDoc}/*w ww . j a va 2 s. c o m*/ */ @Override public void loadAnnotationValues(AnnotationValueTable avt) throws SQLException { PreparedStatement aps = getPreparedStatement(ANNOTATION_SQL); Set<Entry<Integer, TableAnnotationValue>> annotationEntries = avt.getIndexValue().entrySet(); for (Entry<Integer, TableAnnotationValue> annotationEntry : annotationEntries) { aps.setInt(1, (annotationEntry.getKey() + 1)); TableAnnotationValue tableValue = annotationEntry.getValue(); String value = tableValue.getAnnotationValue(); int oid; Integer objectId = valueIndexMap.get(value); if (objectId != null) { oid = objectId; } else { oid = saveObject(1, value); valueIndexMap.put(value, oid); } aps.setInt(2, oid); aps.setInt(3, (tableValue.getAnnotationDefinitionId() + 1)); aps.addBatch(); } aps.executeBatch(); }
From source file:edu.umd.cs.submitServer.servlets.LogEclipseLaunchEvent.java
/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post./*from w w w . ja v a 2 s. c o m*/ * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = null; BufferedReader reader = null; try { MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); long clientTime = multipartRequest.getLongParameter("clientTime"); long serverTime = System.currentTimeMillis(); // Compute the "skew" between client and server in minutes. // This implicitly throw out things that are < 1 min so we lose the // regular // lagtime it takes to upload the submission and post the launch // events. int skew = (int) ((serverTime - clientTime) / 1000 / 60); StudentRegistration registration = (StudentRegistration) request.getAttribute("studentRegistration"); Project project = (Project) request.getAttribute("project"); FileItem fileItem = multipartRequest.getFileItem(); reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream())); String prevLine = null; conn = getConnection(); PreparedStatement stmt = EclipseLaunchEvent.makeInsertStatement(conn); int count = 0; while (true) { String line = reader.readLine(); if (line == null) break; if (line.equals(prevLine)) continue; prevLine = line; // eclipseLaunchEvent date timestamp projectName event String tokens[] = line.split("\t"); String timestampStr = tokens[1]; String md5sum = tokens[2]; String projectName = tokens[3]; String event = tokens[4]; getSubmitServerServletLog().debug(timestampStr + "\t" + md5sum + "\t" + projectName + "\t" + event); EclipseLaunchEvent eclipseLaunchEvent = new EclipseLaunchEvent(); eclipseLaunchEvent.setStudentRegistrationPK(registration.getStudentRegistrationPK()); eclipseLaunchEvent.setProjectNumber(projectName); eclipseLaunchEvent.setProjectPK(project.getProjectPK()); eclipseLaunchEvent.setEvent(event); long timestamp = Long.valueOf(timestampStr); eclipseLaunchEvent.setTimestamp(new Timestamp(timestamp)); eclipseLaunchEvent.setMd5sum(md5sum); eclipseLaunchEvent.setSkew(skew); eclipseLaunchEvent.fillInInsertStatement(stmt); stmt.addBatch(); count++; } if (count > 0) { stmt.executeBatch(); StudentSubmitStatus status = StudentSubmitStatus.lookupByStudentRegistrationPKAndProjectPK( registration.getStudentRegistrationPK(), project.getProjectPK(), conn); if (status != null) { int totalEclipseLaunchEvents = EclipseLaunchEvent .countEclipseLaunchEventsByProjectPKAndStudentRegistration( project, registration, conn); status.setNumberRuns(totalEclipseLaunchEvents); status.update(conn); } } } catch (InvalidRequiredParameterException e) { ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.BAD_PARAMETERS, request, null, "LogEclipseLaunchEvent missing required parameter", "", e); } catch (SQLException e) { ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.EXCEPTION, request, null, "LogEclipseLaunchEvent missing required parameter", "", e); } finally { releaseConnection(conn); if (reader != null) reader.close(); } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl.java
@Override public void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException { Connection conn;//from www .ja v a2s . co m PreparedStatement stmt = null; ResultSet generatedKeys = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (log.isDebugEnabled()) { log.debug("Adding the compliance details for devices and policies"); for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) { log.debug(map.getKey() + " -- " + map.getValue()); } } try { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " + "LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?,?, ?, ?) "; stmt = conn.prepareStatement(query); for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) { stmt.setInt(1, map.getKey()); stmt.setInt(2, map.getValue()); stmt.setInt(3, 1); stmt.setInt(4, 1); stmt.setTimestamp(5, currentTimestamp); stmt.setInt(6, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java
/** * Update the supplied user profile in the profile table. * @param oConnection the connection/*from w ww . j a v a 2 s. co m*/ * @param user the user that must be updated * @throws UserException if update fails */ private void updateProfile(Connection oConnection, ProvisioningUser user) throws UserException { ResultSet oResultSet = null; PreparedStatement psRetrieve = null; PreparedStatement psInsert = null; try { Vector<String> vExistingMethodIDs = new Vector<String>(); psRetrieve = oConnection.prepareStatement(_sProfileSelect); psRetrieve.setString(1, user.getID()); oResultSet = psRetrieve.executeQuery(); String sUserID = user.getID(); while (oResultSet.next()) { sUserID = oResultSet.getString(COLUMN_PROFILE_ID); String sMethodID = oResultSet.getString(COLUMN_PROFILE_AUTHSPID); vExistingMethodIDs.add(sMethodID); } psInsert = oConnection.prepareStatement(_sProfileInsert); psInsert.setString(1, sUserID); for (String sMethod : user.getAuthenticationMethods()) { if (!vExistingMethodIDs.contains(sMethod)) { psInsert.setString(2, sMethod); psInsert.setBoolean(3, user.isAuthenticationRegistered(sMethod)); psInsert.addBatch(); } } int[] iInserts = psInsert.executeBatch(); _logger.debug("Total number of update queries performed in batch: " + iInserts.length); } catch (SQLException e) { _logger.error("Could not update profile for user with id: " + user.getID(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_UPDATE); } catch (Exception e) { _logger.fatal("Could not update profile", e); throw new UserException(SystemErrors.ERROR_INTERNAL); } finally { try { if (psRetrieve != null) psRetrieve.close(); } catch (Exception e) { _logger.error("Could not close retrieve statement", e); } try { if (psInsert != null) psInsert.close(); } catch (Exception e) { _logger.error("Could not close insert statement", e); } } }
From source file:org.rhq.enterprise.server.measurement.MeasurementDataManagerBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void addTraitData(Set<MeasurementDataTrait> data) { if ((data == null) || (data.isEmpty())) { return;/*w ww .j a v a2 s .c o m*/ } Connection conn = null; PreparedStatement ps = null; try { conn = rhqDs.getConnection(); ps = conn.prepareStatement(TRAIT_INSERT_STATEMENT); for (MeasurementDataTrait aData : data) { // time_stamp, schedule_id, value, schedule_id, schedule_id, value, value, value, value ps.setLong(1, aData.getTimestamp()); ps.setInt(2, aData.getScheduleId()); ps.setString(3, aData.getValue()); ps.setInt(4, aData.getScheduleId()); ps.setInt(5, aData.getScheduleId()); ps.setString(6, aData.getValue()); ps.setString(7, aData.getValue()); ps.setString(8, aData.getValue()); ps.setString(9, aData.getValue()); ps.addBatch(); } int[] res = ps.executeBatch(); if (res.length != data.size()) { throw new MeasurementStorageException("Failure to store measurement trait data."); // It is expected that some of these batch updates didn't update anything as the previous value was the same } notifyAlertConditionCacheManager("mergeMeasurementReport", data.toArray(new MeasurementData[data.size()])); } catch (SQLException e) { log.warn("Failure saving measurement trait data:\n" + ThrowableUtil.getAllMessages(e)); } catch (Exception e) { log.error("Error persisting trait data", e); } finally { JDBCUtil.safeClose(conn, ps, null); } }
From source file:org.cartoweb.stats.imports.Import.java
/** * Imports one file into the DB.// ww w .ja v a2 s. co m */ private void convertFile(final Connection con, File file) throws IOException, SQLException { try { final String query = "INSERT INTO " + tableName + " (" + MAPPER.getFieldNames() + ") VALUES (" + MAPPER.getInsertPlaceHolders() + ")"; final PreparedStatement layerStmt = wantLayers ? con.prepareStatement("INSERT INTO " + tableName + "_layers (id, layer) VALUES (?,?)") : null; StatsReader reader = createReader(file); JdbcUtilities.runInsertQuery("inserting stats", query, con, reader, 500, new JdbcUtilities.InsertTask<StatsRecord>() { private int cptLayers = 0; public boolean marshall(PreparedStatement stmt, StatsRecord item) throws SQLException { if (item != null) { item.setId(curId++); MAPPER.saveToDb(stmt, item, 1); if (wantLayers && item.getLayerArray() != null) { for (int i = 0; i < item.getLayerArray().size(); i++) { Integer val = item.getLayerArray().get(i); layerStmt.setLong(1, item.getId()); layerStmt.setInt(2, val); layerStmt.addBatch(); if ((++cptLayers % 500) == 0) { layerStmt.executeBatch(); } } } return true; } else { return false; } } }); if (layerStmt != null) { layerStmt.executeBatch(); layerStmt.close(); } } catch (BatchUpdateException ex) { ex.getNextException().printStackTrace(); throw ex; } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl.java
@Override public void addComplianceDetails(List<PolicyDeviceWrapper> policyDeviceWrapper) throws MonitoringDAOException { Connection conn;/*from www . j av a 2 s . c om*/ PreparedStatement stmt = null; ResultSet generatedKeys = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (log.isDebugEnabled()) { for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) { log.debug("Policy Id : " + wrapper.getPolicyId() + " - " + " Device Id : " + wrapper.getDeviceId()); } } try { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " + "LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?) "; stmt = conn.prepareStatement(query); for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) { stmt.setInt(1, wrapper.getDeviceId()); stmt.setInt(2, wrapper.getPolicyId()); stmt.setInt(3, 1); stmt.setInt(4, 1); stmt.setTimestamp(5, currentTimestamp); stmt.setInt(6, tenantId); stmt.setInt(7, wrapper.getEnrolmentId()); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new MonitoringDAOException("Error occurred while adding the none compliance to the database.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); } }
From source file:org.wso2.carbon.device.mgt.core.archival.dao.impl.ArchivalDAOImpl.java
@Override public void moveOperationResponses() throws ArchivalDAOException { Statement stmt = null;/*w ww .j av a 2s .co m*/ PreparedStatement stmt2 = null; Statement stmt3 = null; ResultSet rs = null; try { Connection conn = ArchivalSourceDAOFactory.getConnection(); String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN " + "(SELECT ID FROM DM_ARCHIVED_OPERATIONS)"; stmt = this.createMemoryEfficientStatement(conn); rs = stmt.executeQuery(sql); Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); sql = "INSERT INTO DM_DEVICE_OPERATION_RESPONSE_ARCH VALUES(?, ?, ?, ?, ?,?,?)"; stmt2 = conn2.prepareStatement(sql); int count = 0; while (rs.next()) { stmt2.setInt(1, rs.getInt("ID")); stmt2.setInt(2, rs.getInt("ENROLMENT_ID")); stmt2.setInt(3, rs.getInt("OPERATION_ID")); stmt2.setInt(4, rs.getInt("EN_OP_MAP_ID")); stmt2.setBytes(5, rs.getBytes("OPERATION_RESPONSE")); stmt2.setTimestamp(6, rs.getTimestamp("RECEIVED_TIMESTAMP")); stmt2.setTimestamp(7, this.currentTimestamp); stmt2.addBatch(); if (++count % batchSize == 0) { stmt2.executeBatch(); if (log.isDebugEnabled()) { log.debug("Executing batch " + count); } } } stmt2.executeBatch(); if (log.isDebugEnabled()) { log.debug(count + " [OPERATION_RESPONSES] Records copied to the archival table. Starting deletion"); } //try the deletion now sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN (" + " SELECT ID FROM DM_ARCHIVED_OPERATIONS)"; stmt3 = conn.createStatement(); int affected = stmt3.executeUpdate(sql); if (log.isDebugEnabled()) { log.debug(affected + " Rows deleted"); } } catch (SQLException e) { throw new ArchivalDAOException("Error occurred while moving operations ", e); } finally { ArchivalDAOUtil.cleanupResources(stmt, rs); ArchivalDAOUtil.cleanupResources(stmt2); ArchivalDAOUtil.cleanupResources(stmt3); } }