List of usage examples for java.sql PreparedStatement addBatch
void addBatch() throws SQLException;
PreparedStatement
object's batch of commands. From source file:org.apache.eagle.alert.metadata.impl.JdbcMetadataHandler.java
public OpResult addPublishmentsToPolicy(String policyId, List<String> publishmentIds) { OpResult result = new OpResult(); Connection connection = null; PreparedStatement statement = null; try {/*from w w w . j a va2 s. com*/ connection = dataSource.getConnection(); connection.setAutoCommit(false); statement = connection.prepareStatement(DELETE_PUBLISHMENT_STATEMENT); statement.setString(1, policyId); int status = statement.executeUpdate(); LOG.info("delete {} records from policy_publishment", status); closeResource(null, statement, null); statement = connection.prepareStatement(INSERT_POLICYPUBLISHMENT_STATEMENT); for (String pub : publishmentIds) { statement.setString(1, policyId); statement.setString(2, pub); statement.addBatch(); } int[] num = statement.executeBatch(); connection.commit(); connection.setAutoCommit(true); int sum = 0; for (int i : num) { sum += i; } result.code = OpResult.SUCCESS; result.message = String.format("Add %d records into policy_publishment", sum); } catch (SQLException ex) { LOG.error("Error to add publishments to policy {}", policyId, ex); result.code = OpResult.FAILURE; result.message = ex.getMessage(); } finally { closeResource(null, statement, connection); } LOG.info(result.message); return result; }
From source file:org.openbel.framework.core.kam.JdbcKAMLoaderImpl.java
@Override public void loadDocumentNamespaceMap(Map<Integer, List<Integer>> dnsm) throws SQLException { PreparedStatement ps = getPreparedStatement(DOCUMENT_NAMESPACE_SQL); Set<Entry<Integer, List<Integer>>> entries = dnsm.entrySet(); for (final Entry<Integer, List<Integer>> entry : entries) { final Integer key = entry.getKey(); for (final Integer nsi : entry.getValue()) { ps.setInt(1, (key + 1));/* w w w . jav a 2 s.c o m*/ ps.setInt(2, (nsi + 1)); ps.addBatch(); } } ps.executeBatch(); }
From source file:com.sec.ose.osi.sdk.protexsdk.discovery.DCPatternMatch.java
public void loadFromProtexServer(UIResponseObserver observer, ReportEntityList identifiedFiles, ReportEntityList patternMatchesPendingFiles) { PreparedStatement prep = IdentificationDBManager.getPatternMatchPreparedStatement(projectName); if (patternMatchesPendingFiles == null) { System.err.println("Not Founded PatternMatches PendingFiles."); } else {/*from w w w . j a v a2s. c om*/ String PatternMatchFilePath = ""; String PatternMatchComment = ""; for (ReportEntity entity : patternMatchesPendingFiles) { PatternMatchFilePath = entity.getValue(ReportInfo.PATTERN_MATCHES_PENDING_FILES.FULL_PATH); PatternMatchComment = entity.getValue(ReportInfo.PATTERN_MATCHES_PENDING_FILES.COMMENT); try { prep.setString(1, PatternMatchFilePath); prep.setString(2, null); prep.setString(3, null); prep.setString(4, null); prep.setString(5, String.valueOf(AbstractMatchInfo.STATUS_PENDING)); prep.setString(6, PatternMatchComment); prep.addBatch(); } catch (SQLException e) { log.warn(e); } } IdentificationDBManager.execute(prep); } String PatternMatchFileName = ""; String PatternMatchComponent = ""; String PatternMatchVersion = ""; String PatternMatchLicense = ""; String PatternMatchComment = ""; if (identifiedFiles != null) { for (ReportEntity tmpIdentifiedFile : identifiedFiles.getEntityList()) { if (tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.DISCOVERY_TYPE) .equals("Other Supported Languages") || tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.RESOLUTION_TYPE) .equals("Declared")) { PatternMatchFileName = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.FILE_FOLDER_NAME) .substring(1); PatternMatchComponent = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.COMPONENT); PatternMatchVersion = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.VERSION); if (PatternMatchVersion == null) PatternMatchVersion = ""; PatternMatchLicense = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.LICENSE); PatternMatchComment = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.COMMENT); try { prep.setString(1, PatternMatchFileName); prep.setString(2, PatternMatchComponent); prep.setString(3, PatternMatchVersion); prep.setString(4, PatternMatchLicense); prep.setString(5, String.valueOf(AbstractMatchInfo.STATUS_IDENTIFIED)); prep.setString(6, PatternMatchComment); prep.addBatch(); } catch (SQLException e) { log.warn(e); } } } IdentificationDBManager.execute(prep); } if (prep != null) { try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java
/** * blacklist list given msisdns//from ww w . j ava2s .c o m * * @param msisdns * @param apiID * @param apiName * @param userID * @throws Exception */ public void blacklist(MSISDNValidationDTO msisdns, final String apiID, final String apiName, final String userID) throws Exception { log.debug("BlackListWhiteListDAO.blacklist triggerd MSISDN[" + StringUtils.join(msisdns.getValidProcessed().toArray(), ",") + "] apiID:" + apiID + " apiName:" + apiName + " userID:" + userID); StringBuilder sql = new StringBuilder(); sql.append(" INSERT INTO "); sql.append(OparatorTable.BLACKLIST_MSISDN.getTObject()); sql.append("(PREFIX,MSISDN,API_ID,API_NAME,USER_ID,VALIDATION_REGEX)"); sql.append(" VALUES (?, ?, ?, ?, ?, ?)"); Connection conn = null; PreparedStatement ps = null; try { conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = conn.prepareStatement(sql.toString()); conn.setAutoCommit(false); for (MsisdnDTO msisdn : msisdns.getValidProcessed()) { ps.setString(1, msisdn.getPrefix()); ps.setString(2, msisdn.getDigits()); ps.setString(3, apiID); ps.setString(4, apiName); ps.setString(5, userID); ps.setString(6, msisdns.getValidationRegex()); ps.addBatch(); } ps.executeBatch(); conn.commit(); } catch (Exception e) { if (conn != null) { conn.rollback(); } throw e; } finally { DbUtils.closeAllConnections(ps, conn, null); } }
From source file:com.wso2telco.dep.operatorservice.dao.BlackListWhiteListDAO.java
/** * when the subscription id is known//from w w w . j a va 2 s . c o m * * @param userMSISDNs * @param subscriptionId * @param apiID * @param applicationID * @throws SQLException * @throws Exception */ public void whitelist(MSISDNValidationDTO msisdns, String subscriptionId, String apiID, String applicationID) throws Exception { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO "); sql.append(OparatorTable.SUBSCRIPTION_WHITELIST.getTObject()); sql.append(" (subscriptionID, prefix, msisdn, api_id, application_id, validation_regex)"); sql.append(" VALUES (?,?,?,?,?,?);"); Connection conn = null; PreparedStatement ps = null; try { conn = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB); ps = conn.prepareStatement(sql.toString()); conn.setAutoCommit(false); for (MsisdnDTO msisdn : msisdns.getValidProcessed()) { ps.setString(1, subscriptionId); ps.setString(2, msisdn.getPrefix()); ps.setString(3, msisdn.getDigits()); ps.setString(4, apiID); ps.setString(5, applicationID); ps.setString(6, msisdns.getValidationRegex()); ps.addBatch(); } ps.executeBatch(); conn.commit(); } catch (Exception e) { if (conn != null) { conn.rollback(); } log.error("", e); throw e; } finally { DbUtils.closeAllConnections(ps, conn, null); } }
From source file:org.freebxml.omar.server.persistence.rdb.InternationalStringDAO.java
public void insert(String parentId, InternationalStringType is) throws RegistryException { PreparedStatement pstmt = null; try {/*from ww w .ja v a 2 s. co m*/ String str = "INSERT INTO " + getTableName() + " VALUES(?, " + // charsetName "?," + // lang "?, " + // value "?)"; // parentId pstmt = context.getConnection().prepareStatement(str); if (is != null) { Iterator lsItems = is.getLocalizedString().iterator(); while (lsItems.hasNext()) { LocalizedString ls = (LocalizedString) lsItems.next(); String charset = ls.getCharset(); String lang = ls.getLang(); String value = ls.getValue(); String charsetName = ls.getCharset(); if (value != null && value.length() > 0) { pstmt.setString(1, charsetName); pstmt.setString(2, lang); pstmt.setString(3, value); pstmt.setString(4, parentId); log.trace("SQL = " + str); // HIEOS/BHT: DEBUG (fix) pstmt.addBatch(); } } } if (is != null) { int[] updateCounts = pstmt.executeBatch(); } } catch (SQLException e) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e); throw new RegistryException(e); } finally { closeStatement(pstmt); } }
From source file:com.nabla.wapp.server.auth.UserManager.java
public boolean initializeDatabase(final IRoleListProvider roleListProvider, final String rootPassword) throws SQLException { Assert.argumentNotNull(roleListProvider); final LockTableGuard lock = new LockTableGuard(conn, LOCK_USER_TABLES); try {/*from ww w . j av a 2s . c o m*/ if (!Database.isTableEmpty(conn, IRoleTable.TABLE)) return true; if (log.isDebugEnabled()) log.debug("initializing role tables"); final Map<String, String[]> roles = roleListProvider.get(); Assert.state(!roles.containsKey(IRootUser.NAME)); final ConnectionTransactionGuard guard = new ConnectionTransactionGuard(conn); try { final PreparedStatement stmtRole = conn.prepareStatement( "INSERT INTO role (name,uname,privilege,internal) VALUES(?,?,?,?);", Statement.RETURN_GENERATED_KEYS); final Map<String, Integer> roleIds = new HashMap<String, Integer>(); try { stmtRole.clearBatch(); stmtRole.setBoolean(4, true); // add privileges and default roles for (final Map.Entry<String, String[]> role : roles.entrySet()) { stmtRole.setString(1, role.getKey()); stmtRole.setString(2, role.getKey().toUpperCase()); stmtRole.setBoolean(3, role.getValue() == null); stmtRole.addBatch(); } if (!Database.isBatchCompleted(stmtRole.executeBatch())) return false; final ResultSet rsKey = stmtRole.getGeneratedKeys(); try { for (final Map.Entry<String, String[]> role : roles.entrySet()) { rsKey.next(); roleIds.put(role.getKey(), rsKey.getInt(1)); } } finally { rsKey.close(); } } finally { stmtRole.close(); } final PreparedStatement stmtDefinition = conn .prepareStatement("INSERT INTO role_definition (role_id,child_role_id) VALUES(?,?);"); try { stmtDefinition.clearBatch(); for (final Map.Entry<String, String[]> role : roles.entrySet()) { final String[] definition = role.getValue(); if (definition == null) continue; stmtDefinition.setInt(1, roleIds.get(role.getKey())); for (final String child : definition) { final Integer childId = roleIds.get(child); if (childId == null) { if (log.isErrorEnabled()) log.error("child role '" + child + "' not defined!"); return false; } stmtDefinition.setInt(2, childId); stmtDefinition.addBatch(); } } if (!Database.isBatchCompleted(stmtDefinition.executeBatch())) return false; } finally { stmtDefinition.close(); } // add 'root' user Database.executeUpdate(conn, "INSERT INTO user (name,uname,active,password) VALUES(?,?,TRUE,?);", IRootUser.NAME, IRootUser.NAME.toUpperCase(), getPasswordEncryptor().encryptPassword(rootPassword)); return guard.setSuccess(true); } finally { guard.close(); } } finally { lock.close(); } }
From source file:ccc.cli.StringToDecConverterUtil.java
/** * Generates and stores decimal values for the values of the paragraphs * of type 'NUMBER'. The new values are stored in the value_decimal column. // w w w . j a va 2 s . com * @param connection The DB connection. */ public void convertParagraphs(final Connection connection) { LOG.info("Convert Paragraphs Started"); Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; try { stmt = connection.createStatement(); LOG.trace("Getting the paragraphs where type is 'NUMBER'"); rs = stmt.executeQuery(GET_PARAGRAPHS_QUERY); if (rs != null && rs.next()) { LOG.debug("Processing result set"); pstmt = connection.prepareStatement(UPDATE_PARAGRAPH); int totalparagraphs = 0; do { final String textNumber = rs.getString("value_text"); final String pageId = rs.getString("page_revision_id"); LOG.trace("Found " + textNumber + " for id " + pageId); // Conversion final BigDecimal decNumber = convert(textNumber); if (decNumber == null) { LOG.warn("Failed to convert paragraph " + pageId + " with value " + textNumber); } pstmt.setBigDecimal(1, decNumber); pstmt.setString(2, pageId); pstmt.addBatch(); totalparagraphs++; } while (rs.next()); LOG.debug("Executing updates"); pstmt.executeBatch(); LOG.info("Processed " + totalparagraphs + " paragraphs"); LOG.info("Finished"); } } catch (final SQLException e) { LOG.fatal("An error occured while converting Strings to Decimal", e); } finally { LOG.info("Releasing the resources"); DbUtils.closeQuietly(rs); DbUtils.closeQuietly(pstmt); DbUtils.closeQuietly(stmt); } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl.java
@Override public void addNonComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature> complianceFeatures) throws MonitoringDAOException { Connection conn;/*from w w w . j av a 2 s .co m*/ PreparedStatement stmt = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY_COMPLIANCE_FEATURES (COMPLIANCE_STATUS_ID, FEATURE_CODE, STATUS, " + "TENANT_ID) VALUES (?, ?, ?, ?) "; stmt = conn.prepareStatement(query); for (ComplianceFeature feature : complianceFeatures) { stmt.setInt(1, policyComplianceStatusId); stmt.setString(2, feature.getFeatureCode()); if (feature.isCompliant()) { stmt.setInt(3, 1); } else { stmt.setInt(3, 0); } stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new MonitoringDAOException( "Error occurred while adding the none compliance features to the " + "database.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.WideColumnIndexer.java
public void index(Map<String, PreparedStatement> statementCache, String keySpace, String columnFamily, String key, String rid, Map<String, Object> values) throws StorageClientException, SQLException { ResultSet rs = null;/*w w w .j a v a 2 s. c o m*/ try { Set<String> removeArrayColumns = Sets.newHashSet(); Set<String> removeColumns = Sets.newHashSet(); Map<String, Object[]> updateArrayColumns = Maps.newHashMap(); Map<String, Object> updateColumns = Maps.newHashMap(); for (Entry<String, Object> e : values.entrySet()) { String k = e.getKey(); Object o = e.getValue(); Object[] valueMembers = (o instanceof Object[]) ? (Object[]) o : new Object[] { o }; if (shouldIndex(keySpace, columnFamily, k)) { if (isColumnArray(keySpace, columnFamily, k)) { if (o instanceof RemoveProperty || o == null || valueMembers.length == 0) { removeArrayColumns.add(k); } else { removeArrayColumns.add(k); updateArrayColumns.put(k, valueMembers); } } else { if (o instanceof RemoveProperty || o == null || valueMembers.length == 0) { removeColumns.add(k); } else { updateColumns.put(k, valueMembers[0]); } } } } if (!StorageClientUtils.isRoot(key) && getColumnName(keySpace, columnFamily, InternalContent.PARENT_HASH_FIELD) != null) { String parent = StorageClientUtils.getParentObjectPath(key); String hash = client.rowHash(keySpace, columnFamily, parent); LOGGER.debug("Hash of {}:{}:{} is {} ", new Object[] { keySpace, columnFamily, parent, hash }); updateColumns.put(InternalContent.PARENT_HASH_FIELD, hash); } LOGGER.debug("Removing Array {} ", removeArrayColumns); LOGGER.debug("Updating Array {} ", updateArrayColumns); LOGGER.debug("Removing {} ", removeColumns); LOGGER.debug("Updating {} ", updateColumns); // arrays are stored in css, so we can re-use css sql. PreparedStatement removeStringColumn = client.getStatement(keySpace, columnFamily, JDBCStorageClient.SQL_REMOVE_STRING_COLUMN, rid, statementCache); int nbatch = 0; for (String column : removeArrayColumns) { removeStringColumn.clearWarnings(); removeStringColumn.clearParameters(); removeStringColumn.setString(1, rid); removeStringColumn.setString(2, column); removeStringColumn.addBatch(); LOGGER.debug("Removing {} {} ", rid, column); nbatch++; } if (nbatch > 0) { long t = System.currentTimeMillis(); removeStringColumn.executeBatch(); checkSlow(t, client.getSql(keySpace, columnFamily, JDBCStorageClient.SQL_REMOVE_STRING_COLUMN)); nbatch = 0; } // add the column values in PreparedStatement insertStringColumn = client.getStatement(keySpace, columnFamily, JDBCStorageClient.SQL_INSERT_STRING_COLUMN, rid, statementCache); for (Entry<String, Object[]> e : updateArrayColumns.entrySet()) { for (Object o : e.getValue()) { insertStringColumn.clearWarnings(); insertStringColumn.clearParameters(); insertStringColumn.setString(1, o.toString()); insertStringColumn.setString(2, rid); insertStringColumn.setString(3, e.getKey()); insertStringColumn.addBatch(); LOGGER.debug("Inserting {} {} {} ", new Object[] { o.toString(), rid, e.getKey() }); nbatch++; } } if (nbatch > 0) { long t = System.currentTimeMillis(); insertStringColumn.executeBatch(); checkSlow(t, client.getSql(keySpace, columnFamily, JDBCStorageClient.SQL_INSERT_STRING_COLUMN)); nbatch = 0; } if (removeColumns.size() == 0 && updateColumns.size() == 0) { return; // nothing to add or remove, do nothing. } if (removeColumns.size() > 0 && updateColumns.size() == 0) { // exists, columns to remove, none to update, therefore // delete row this assumes that the starting point is a // complete map PreparedStatement deleteWideStringColumn = client.getStatement(keySpace, columnFamily, SQL_DELETE_WIDESTRING_ROW, rid, statementCache); deleteWideStringColumn.clearParameters(); deleteWideStringColumn.setString(1, rid); long t = System.currentTimeMillis(); deleteWideStringColumn.execute(); checkSlow(t, client.getSql(keySpace, columnFamily, SQL_DELETE_WIDESTRING_ROW)); LOGGER.debug("Executed {} with {} ", deleteWideStringColumn, rid); } else if (updateColumns.size() > 0 || removeColumns.size() > 0) { // // build an update query, record does not exists, but there // is stuff to add String[] sqlParts = StringUtils .split(client.getSql(keySpace, columnFamily, SQL_UPDATE_WIDESTRING_ROW), ";"); StringBuilder setOperations = new StringBuilder(); for (Entry<String, Object> e : updateColumns.entrySet()) { join(setOperations, " ,").append( MessageFormat.format(sqlParts[1], getColumnName(keySpace, columnFamily, e.getKey()))); } for (String toRemove : removeColumns) { join(setOperations, " ,").append( MessageFormat.format(sqlParts[1], getColumnName(keySpace, columnFamily, toRemove))); } String finalSql = MessageFormat.format(sqlParts[0], setOperations); LOGGER.debug("Performing {} ", finalSql); PreparedStatement updateColumnPst = client.getStatement(finalSql, statementCache); updateColumnPst.clearWarnings(); updateColumnPst.clearParameters(); int i = 1; for (Entry<String, Object> e : updateColumns.entrySet()) { updateColumnPst.setString(i, e.getValue().toString()); LOGGER.debug(" Param {} {} ", i, e.getValue().toString()); i++; } for (String toRemove : removeColumns) { updateColumnPst.setNull(i, toSqlType(columnFamily, toRemove)); LOGGER.debug(" Param {} NULL ", i); i++; } updateColumnPst.setString(i, rid); long t = System.currentTimeMillis(); int n = updateColumnPst.executeUpdate(); checkSlow(t, finalSql); if (n == 0) { // part 0 is the final ,part 1 is the template for column names, // part 2 is the template for parameters. // insert into x ( columnsnames ) values () StringBuilder columnNames = new StringBuilder(); StringBuilder paramHolders = new StringBuilder(); for (Entry<String, Object> e : updateColumns.entrySet()) { columnNames.append(" ,").append(getColumnName(keySpace, columnFamily, e.getKey())); paramHolders.append(" ,").append("?"); } finalSql = MessageFormat.format( client.getSql(keySpace, columnFamily, SQL_INSERT_WIDESTRING_ROW), columnNames.toString(), paramHolders.toString()); LOGGER.debug("Insert SQL {} ", finalSql); PreparedStatement insertColumnPst = client.getStatement(finalSql, statementCache); insertColumnPst.clearWarnings(); insertColumnPst.clearParameters(); insertColumnPst.setString(1, rid); i = 2; for (Entry<String, Object> e : updateColumns.entrySet()) { LOGGER.debug(" Param {} {} ", i, e.getValue().toString()); insertColumnPst.setString(i, e.getValue().toString()); i++; } t = System.currentTimeMillis(); insertColumnPst.executeUpdate(); checkSlow(t, finalSql); } } } finally { if (rs != null) { rs.close(); } } }