List of usage examples for java.sql PreparedStatement setBoolean
void setBoolean(int parameterIndex, boolean x) throws SQLException;
boolean
value. From source file:dk.statsbiblioteket.doms.licensemodule.persistence.H2Storage.java
public void persistDomLicenseGroupType(String key, String value, String value_en, String description, String description_en, String query, boolean mustGroup) throws Exception { if (!StringUtils.isNotEmpty(key)) { throw new IllegalArgumentException("Key must not be null when creating new Group"); }/*from w ww . j a v a 2s .c om*/ if (!StringUtils.isNotEmpty(value)) { throw new IllegalArgumentException("Value must not be null when creating new Group"); } if (!StringUtils.isNotEmpty(value_en)) { throw new IllegalArgumentException("Value(EN) must not be null when creating new Group"); } if (!StringUtils.isNotEmpty(query)) { throw new IllegalArgumentException("Query must not be null when creating new Group"); } log.info("Persisting new dom license group type: " + key); validateValue(value); value = value.trim(); PreparedStatement stmt = null; try { stmt = singleDBConnection.prepareStatement(persistDomLicenseGroupTypeQuery); stmt.setLong(1, generateUniqueID()); stmt.setString(2, key); stmt.setString(3, value); stmt.setString(4, value_en); stmt.setString(5, description); stmt.setString(6, description_en); stmt.setString(7, query); stmt.setBoolean(8, mustGroup); stmt.execute(); singleDBConnection.commit(); } catch (SQLException e) { log.error("SQL Exception in persistDomLicenseGroupType:" + e.getMessage()); throw e; } finally { closeStatement(stmt); } LicenseCache.reloadCache(); // Force reload so the change will be instant in the cache }
From source file:org.openmrs.util.databasechange.AddConceptMapTypesChangeset.java
/** * Executes all the changes to the concept names as a batch update. * * @param connection The database connection *//* ww w . j a va 2s . c o m*/ private void runBatchInsert(JdbcConnection connection) throws CustomChangeException { PreparedStatement pStmt = null; ResultSet rs = null; try { connection.setAutoCommit(false); Integer userId = DatabaseUpdater.getAuthenticatedUserId(); //if we have no authenticated user(for API users), set as Daemon if (userId == null || userId < 1) { userId = getInt(connection, "SELECT min(user_id) FROM users"); //leave it as null rather than setting it to 0 if (userId < 1) { userId = null; } } //userId is not a param, because it's easier this way if it's null pStmt = connection.prepareStatement("INSERT INTO concept_map_type " + "(concept_map_type_id, name, is_hidden, retired, creator, date_created, uuid) VALUES(?,?,?,?," + userId + ",?,?)"); int mapTypeId = 1; for (String map : visibleConceptMapTypeArray) { String[] mapTypeAndUuid = map.trim().split("\\|"); String mapType = mapTypeAndUuid[0]; String mapUuid = mapTypeAndUuid[1]; pStmt.setInt(1, mapTypeId); pStmt.setString(2, mapType); pStmt.setBoolean(3, false); pStmt.setBoolean(4, false); pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis())); pStmt.setString(6, mapUuid); pStmt.addBatch(); mapTypeId++; } for (String map : hiddenConceptMapTypeArray) { String[] mapTypeAndUuid = map.trim().split("\\|"); String mapType = mapTypeAndUuid[0]; String mapUuid = mapTypeAndUuid[1]; pStmt.setInt(1, mapTypeId); pStmt.setString(2, mapType); pStmt.setBoolean(3, true); pStmt.setBoolean(4, false); pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis())); pStmt.setString(6, mapUuid); pStmt.addBatch(); mapTypeId++; } try { int[] updateCounts = pStmt.executeBatch(); for (int i = 0; i < updateCounts.length; i++) { if (updateCounts[i] > -1) { log.debug("Successfully executed: updateCount=" + updateCounts[i]); } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) { log.debug("Successfully executed; No Success info"); } else if (updateCounts[i] == Statement.EXECUTE_FAILED) { log.warn("Failed to execute insert"); } } log.debug("Committing inserts..."); connection.commit(); } catch (BatchUpdateException be) { log.warn("Error generated while processsing batch insert", be); int[] updateCounts = be.getUpdateCounts(); for (int i = 0; i < updateCounts.length; i++) { if (updateCounts[i] > -1) { log.warn("Executed with exception: insertCount=" + updateCounts[i]); } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) { log.warn("Executed with exception; No Success info"); } else if (updateCounts[i] == Statement.EXECUTE_FAILED) { log.warn("Failed to execute insert with exception"); } } try { log.debug("Rolling back batch", be); connection.rollback(); } catch (Exception rbe) { log.warn("Error generated while rolling back batch insert", be); } //marks the changeset as a failed one throw new CustomChangeException("Failed to insert one or more concept map types", be); } } catch (DatabaseException e) { throw new CustomChangeException("Failed to insert one or more concept map types:", e); } catch (SQLException e) { throw new CustomChangeException("Failed to insert one or more concept map types:", e); } finally { //reset to auto commit mode try { connection.setAutoCommit(true); } catch (DatabaseException e) { log.warn("Failed to reset auto commit back to true", e); } if (rs != null) { try { rs.close(); } catch (SQLException e) { log.warn("Failed to close the resultset object"); } } if (pStmt != null) { try { pStmt.close(); } catch (SQLException e) { log.warn("Failed to close the prepared statement object"); } } } }
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 w w . j a va 2s . c o 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:dk.netarkivet.harvester.datamodel.HarvestDefinitionDBDAO.java
@Override public void setIndexIsReady(Long harvestId, boolean newValue) { if (!isSnapshot(harvestId)) { throw new NotImplementedException("Not implemented for non snapshot harvests"); } else {/*from w w w. j av a2 s . com*/ Connection c = HarvestDBConnection.get(); String sql = "UPDATE fullharvests SET isindexready=? " + "WHERE harvest_id=?"; PreparedStatement s = null; try { s = c.prepareStatement(sql); s.setBoolean(1, newValue); s.setLong(2, harvestId); int rows = s.executeUpdate(); log.debug(rows + " entries of table fullharvests updated"); } catch (SQLException e) { log.warn("Exception thrown while updating " + "fullharvests.isindexready field: " + ExceptionUtils.getSQLExceptionCause(e), e); } finally { DBUtils.closeStatementIfOpen(s); HarvestDBConnection.release(c); } } }
From source file:org.hyperic.hq.measurement.server.session.MeasurementTemplateDAO.java
public void createTemplates(final String pluginName, final Map<MonitorableType, List<MonitorableMeasurementInfo>> toAdd) { final IdentifierGenerator tmplIdGenerator = ((SessionFactoryImpl) sessionFactory) .getEntityPersister(MeasurementTemplate.class.getName()).getIdentifierGenerator(); final String templatesql = "INSERT INTO EAM_MEASUREMENT_TEMPL " + "(id, name, alias, units, collection_type, default_on, " + "default_interval, designate, monitorable_type_id, " + "category_id, template, plugin, ctime, mtime) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; final List<MonitorableMeasurementInfo> combinedInfos = new ArrayList<MonitorableMeasurementInfo>(); for (List<MonitorableMeasurementInfo> info : toAdd.values()) { combinedInfos.addAll(info);/*from w ww .jav a 2s . c om*/ } final long current = System.currentTimeMillis(); //We need JdbcTemplate to throw runtime Exception to roll back tx if batch update fails, else we'll get partial write jdbcTemplate.batchUpdate(templatesql, new BatchPreparedStatementSetter() { HashMap<String, Category> cats = new HashMap<String, Category>(); public void setValues(PreparedStatement stmt, int i) throws SQLException { MeasurementInfo info = combinedInfos.get(i).getMeasurementInfo(); Category cat = (Category) cats.get(info.getCategory()); if (cat == null) { cat = catDAO.findByName(info.getCategory()); if (cat == null) { cat = catDAO.create(info.getCategory()); } cats.put(info.getCategory(), cat); } Integer rawid = (Integer) tmplIdGenerator.generate((SessionImpl) getSession(), new MeasurementTemplate()); stmt.setInt(1, rawid.intValue()); stmt.setString(2, info.getName()); String alias = info.getAlias(); if (alias.length() > ALIAS_LIMIT) { alias = alias.substring(0, ALIAS_LIMIT); log.warn("ALIAS field of EAM_MEASUREMENT_TEMPLATE truncated: original value was " + info.getAlias() + ", truncated value is " + alias); } stmt.setString(3, alias); stmt.setString(4, info.getUnits()); stmt.setInt(5, info.getCollectionType()); stmt.setBoolean(6, info.isDefaultOn()); stmt.setLong(7, info.getInterval()); stmt.setBoolean(8, info.isIndicator()); stmt.setInt(9, combinedInfos.get(i).getMonitorableType().getId().intValue()); stmt.setInt(10, cat.getId().intValue()); stmt.setString(11, info.getTemplate()); stmt.setString(12, pluginName); stmt.setLong(13, current); stmt.setLong(14, current); } public int getBatchSize() { return combinedInfos.size(); } }); }
From source file:dk.statsbiblioteket.doms.licensemodule.persistence.H2Storage.java
public void updateDomLicenseGroupType(long id, String value_dk, String value_en, String description, String description_en, String query, boolean mustGroup) throws Exception { PreparedStatement stmt = null; try {/*from w w w . ja v a 2 s . co m*/ log.info("Updating Group type with id:" + id); // if it exists already, we do not add it. stmt = singleDBConnection.prepareStatement(updateDomLicenseGroupTypeQuery); stmt.setString(1, value_dk); stmt.setString(2, value_en); stmt.setString(3, description); stmt.setString(4, description_en); stmt.setString(5, query); stmt.setBoolean(6, mustGroup); stmt.setLong(7, id); int updated = stmt.executeUpdate(); if (updated != 1) { throw new SQLException("Grouptype id not found:" + id); } singleDBConnection.commit(); } catch (Exception e) { log.error("Exception in updateDomLicenseGroupType:" + e.getMessage()); throw e; } finally { closeStatement(stmt); } LicenseCache.reloadCache(); // Force reload so the change will be instant in the cache }
From source file:com.concursive.connect.web.modules.documents.dao.FileItemList.java
/** * Description of the Method/*from www.jav a 2s. c o m*/ * * @param pst Description of Parameter * @return Description of the Returned Value * @throws SQLException Description of Exception */ private int prepareFilter(PreparedStatement pst) throws SQLException { int i = 0; if (linkModuleId > -1) { pst.setInt(++i, linkModuleId); } if (linkItemId > -1) { pst.setInt(++i, linkItemId); } if (folderId > -1) { pst.setInt(++i, folderId); } if (owner != -1) { pst.setInt(++i, owner); } if (alertRangeStart != null) { pst.setTimestamp(++i, alertRangeStart); } if (alertRangeEnd != null) { pst.setTimestamp(++i, alertRangeEnd); } if (forProjectUser > -1) { pst.setInt(++i, forProjectUser); pst.setBoolean(++i, true); pst.setBoolean(++i, true); } if (defaultFile != Constants.UNDEFINED) { pst.setBoolean(++i, defaultFile == Constants.TRUE); } if (enabled != Constants.UNDEFINED) { pst.setBoolean(++i, enabled == Constants.TRUE); } if (filename != null) { pst.setString(++i, filename); } if (ignoreId > -1) { pst.setInt(++i, ignoreId); } if (featuredFilesOnly != Constants.UNDEFINED) { pst.setBoolean(++i, featuredFilesOnly == Constants.TRUE); } if (publicProjectFiles != Constants.UNDEFINED) { pst.setBoolean(++i, true); } if (projectCategoryId != -1) { pst.setInt(++i, projectCategoryId); } if (modifiedYearMonth != null) { pst.setTimestamp(++i, startOfCurrentMonth); pst.setTimestamp(++i, startOfNextMonth); } return i; }
From source file:com.flexive.ejb.beans.UserGroupEngineBean.java
/** * {@inheritDoc}/*w ww. ja v a 2s . c o m*/ */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public long create(String name, String color, long mandatorId) throws FxApplicationException { final UserTicket ticket = FxContext.getUserTicket(); // Permission checks try { if (!ticket.isGlobalSupervisor()) { if (ticket.getMandatorId() != mandatorId) { throw new FxNoAccessException("ex.usergroup.create.foreignMandator"); } if (!ticket.isInRole(Role.MandatorSupervisor)) FxPermissionUtils.checkRole(ticket, Role.AccountManagement); } } catch (FxNoAccessException nae) { if (LOG.isInfoEnabled()) LOG.info(nae); throw nae; } Connection con = null; Statement stmt = null; PreparedStatement ps = null; String sql = null; try { // Sanity checks color = FxFormatUtils.processColorString("color", color); checkName(name); // Obtain a database connection con = Database.getDbConnection(); // Obtain a new id long groupId = seq.getId(FxSystemSequencer.GROUP); // Create the new group sql = "INSERT INTO " + TBL_USERGROUPS + " " + "(ID,MANDATOR,AUTOMANDATOR,ISSYSTEM,NAME,COLOR,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT) VALUES (" + "?,?,?,?,?,?,?,?,?,?)"; final long NOW = System.currentTimeMillis(); ps = con.prepareStatement(sql); ps.setLong(1, groupId); ps.setLong(2, mandatorId); ps.setNull(3, java.sql.Types.NUMERIC); ps.setBoolean(4, false); ps.setString(5, name); ps.setString(6, color); ps.setLong(7, ticket.getUserId()); ps.setLong(8, NOW); ps.setLong(9, ticket.getUserId()); ps.setLong(10, NOW); ps.executeUpdate(); StructureLoader.updateUserGroups(FxContext.get().getDivisionId(), loadAll(-1)); // Return the new id return groupId; } catch (SQLException exc) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc); EJBUtils.rollback(ctx); if (uniqueConstraintViolation) { FxEntryExistsException eee = new FxEntryExistsException("ex.usergroup.create.groupExists", name); if (LOG.isInfoEnabled()) LOG.info(eee); throw eee; } else { FxCreateException ce = new FxCreateException(exc, "ex.usergroup.sqlError", exc.getMessage(), sql); LOG.error(ce); throw ce; } } finally { Database.closeObjects(UserGroupEngineBean.class, null, ps); Database.closeObjects(UserGroupEngineBean.class, con, stmt); } }
From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java
@Override public void delistService(TransactionContext transactionContext, CompensableArchive holder) { Connection connection = null; PreparedStatement stmt = null; try {//from ww w.j a v a 2s .c o m connection = this.getConnection(); StringBuilder ber = new StringBuilder(); ber.append("update tcc_compensable set variable = ?, try_committed = ? "); ber.append("where application = ? and endpoint = ? and global_tx_id = ? and branch_qualifier = ?"); stmt = connection.prepareStatement(ber.toString()); XidImpl internalXid = holder.branchXid; Blob blob = connection.createBlob(); OutputStream output = blob.setBinaryStream(1); Serializable variable = holder.variable; if (variable != null) { byte[] bytes = this.serializer.serialize(variable); output.write(bytes); } output.close(); stmt.setBlob(1, blob); stmt.setBoolean(2, holder.tryCommitted); stmt.setString(3, this.instanceKey.getApplication()); stmt.setString(4, this.instanceKey.getEndpoint()); stmt.setString(5, ByteUtils.byteArrayToString(internalXid.getGlobalTransactionId())); if (transactionContext.isCoordinator()) { stmt.setString(6, TransactionLogger.NULL); } else { stmt.setString(6, ByteUtils.byteArrayToString(internalXid.getBranchQualifier())); } stmt.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } finally { closeStatement(stmt); this.releaseConnection(connection); } }
From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java
@Override public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column) throws SQLException { switch (column.getJdbcType()) { case Types.VARCHAR: case Types.CLOB: setToPreparedStatementString(ps, index, value, column); return;//from www.j a v a2s. c o m case Types.BIT: ps.setBoolean(index, ((Boolean) value).booleanValue()); return; case Types.SMALLINT: ps.setInt(index, ((Long) value).intValue()); return; case Types.INTEGER: case Types.BIGINT: ps.setLong(index, ((Number) value).longValue()); return; case Types.DOUBLE: ps.setDouble(index, ((Double) value).doubleValue()); return; case Types.TIMESTAMP: ps.setTimestamp(index, getTimestampFromCalendar((Calendar) value)); return; case Types.ARRAY: int jdbcBaseType = column.getJdbcBaseType(); String jdbcBaseTypeName = column.getSqlBaseTypeString(); if (jdbcBaseType == Types.TIMESTAMP) { value = getTimestampFromCalendar((Serializable[]) value); } Array array = ps.getConnection().createArrayOf(jdbcBaseTypeName, (Object[]) value); ps.setArray(index, array); return; case Types.OTHER: ColumnType type = column.getType(); if (type.isId()) { setId(ps, index, value); return; } else if (type == ColumnType.FTSTORED) { ps.setString(index, (String) value); return; } throw new SQLException("Unhandled type: " + column.getType()); default: throw new SQLException("Unhandled JDBC type: " + column.getJdbcType()); } }