List of usage examples for java.sql PreparedStatement setBoolean
void setBoolean(int parameterIndex, boolean x) throws SQLException;
boolean
value. From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java
/** * {@inheritDoc}//ww w . java 2s . c om */ @Override public ReferencedContent resolveReference(Connection con, int contentVersion, long referencedId) throws SQLException { String sql = contentVersion == FxPK.LIVE ? CONTENT_REFERENCE_LIVE : CONTENT_REFERENCE_MAX; PreparedStatement ps = null; int referencedVersion; long stepId, aclId, typeId, ownerId; String caption; try { ps = con.prepareStatement(sql); ps.setLong(1, referencedId); ps.setBoolean(2, true); ResultSet rs = ps.executeQuery(); if (rs != null && rs.next()) { referencedVersion = rs.getInt(1); aclId = rs.getLong(2); stepId = rs.getLong(3); typeId = rs.getLong(4); ownerId = rs.getLong(5); } else if (contentVersion == FxPK.LIVE) { ps.close(); ps = con.prepareStatement(CONTENT_REFERENCE_MAX); ps.setLong(1, referencedId); ps.setBoolean(2, true); rs = ps.executeQuery(); if (rs != null && rs.next()) { referencedVersion = rs.getInt(1); aclId = rs.getLong(2); stepId = rs.getLong(3); typeId = rs.getLong(4); ownerId = rs.getLong(5); } else { LOG.error("Failed to resolve a reference with id " + referencedId + ": no max. version found! (in fallback already!)"); return new ReferencedContent(referencedId); } } else { LOG.error("Failed to resolve a reference with id " + referencedId + ": no max. version found!"); return new ReferencedContent(referencedId); } ps.close(); ps = con.prepareStatement(CONTENT_REFERENCE_CAPTION); ps.setLong(1, referencedId); ps.setInt(2, referencedVersion); try { ps.setLong(3, EJBLookup.getConfigurationEngine().get(SystemParameters.TREE_CAPTION_PROPERTY)); } catch (FxApplicationException e) { throw e.asRuntimeException(); } rs = ps.executeQuery(); if (rs != null && rs.next()) caption = rs.getString(1); else caption = ""; // resolve ACLs from ACL table, if necessary FxEnvironment env = CacheAdmin.getEnvironment(); final FxPK pk = new FxPK(referencedId, referencedVersion); final List<ACL> acls; if (aclId == ACL.NULL_ACL_ID) { // multiple ACLs for this content instance acls = FxSharedUtils.filterSelectableObjectsById(env.getACLs(), loadContentAclTable(con, pk)); } else { // only one ACL acls = Arrays.asList(env.getACL(aclId)); } // don't store explicit version in PK, otherwise clients will run into unexpected results when this // content is cached (even by flexive) ReferencedContent ref = new ReferencedContent(new FxPK(pk.getId(), FxPK.MAX), caption, env.getStep(stepId), acls); try { ref.setAccessGranted(FxPermissionUtils.checkPermission(FxContext.getUserTicket(), ownerId, ACLPermission.READ, env.getType(typeId), ref.getStep().getAclId(), FxSharedUtils.getSelectableObjectIdList(acls), false)); } catch (FxNoAccessException e) { ref.setAccessGranted(false); } if (LOG.isDebugEnabled()) { LOG.debug("ReferencedContent: " + ref.toStringExtended()); } return ref; } finally { Database.closeObjects(GenericHierarchicalStorage.class, ps); } }
From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java
/** * Update a group's attributes//from w w w .j av a2 s .c o m * * @param con an existing sql connection * @param group the instance of FxGroupEdit whose attributes should be changed * @return true if changes were made to the group * @throws FxApplicationException on errors */ private boolean updateGroup(Connection con, FxGroupEdit group) throws FxApplicationException { final StringBuilder sql = new StringBuilder(1000); final StringBuilder changesDesc = new StringBuilder(200); final FxGroup org = CacheAdmin.getEnvironment().getGroup(group.getId()); PreparedStatement ps = null; boolean changes = false; boolean success = false; try { sql.setLength(0); // change the group's override base multiplicity flag if (org.mayOverrideBaseMultiplicity() != group.mayOverrideBaseMultiplicity()) { if (!group.mayOverrideBaseMultiplicity()) { if (getGroupInstanceMultiplicity(con, org.getId(), true) < group.getMultiplicity().getMin()) throw new FxUpdateException("ex.structure.modification.contentExists", "minimumMultiplicity"); if (getGroupInstanceMultiplicity(con, org.getId(), false) > group.getMultiplicity().getMax()) throw new FxUpdateException("ex.structure.modification.contentExists", "maximumMultiplicity"); } ps = con.prepareStatement("UPDATE " + TBL_STRUCT_GROUPS + " SET MAYOVERRIDEMULT=? WHERE ID=?"); ps.setBoolean(1, group.mayOverrideBaseMultiplicity()); ps.setLong(2, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("mayOverrideMultiplicity=").append(group.mayOverrideBaseMultiplicity()); changes = true; } // check and change the group's minimum and/or maximum multiplicity if (org.getMultiplicity().getMin() != group.getMultiplicity().getMin() || org.getMultiplicity().getMax() != group.getMultiplicity().getMax()) { if (!org.mayOverrideBaseMultiplicity()) { if (org.getMultiplicity().getMin() < group.getMultiplicity().getMin()) { if (getGroupInstanceMultiplicity(con, org.getId(), true) < group.getMultiplicity().getMin()) throw new FxUpdateException("ex.structure.modification.group.contentExists", group.getId(), group.getMultiplicity().getMin(), group.getMultiplicity().getMax()); } if (org.getMultiplicity().getMax() > group.getMultiplicity().getMax()) { if (getGroupInstanceMultiplicity(con, org.getId(), false) > group.getMultiplicity() .getMax()) throw new FxUpdateException("ex.structure.modification.group.contentExists", group.getId(), group.getMultiplicity().getMin(), group.getMultiplicity().getMax()); } } ps = con.prepareStatement( "UPDATE " + TBL_STRUCT_GROUPS + " SET DEFMINMULT=? ,DEFMAXMULT=? WHERE ID=?"); ps.setInt(1, group.getMultiplicity().getMin()); ps.setInt(2, group.getMultiplicity().getMax()); ps.setLong(3, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("multiplicity=").append(group.getMultiplicity()); changes = true; } // change the group's label if (org.getLabel() != null && !org.getLabel().equals(group.getLabel()) || org.getLabel() == null && group.getLabel() != null || org.getHint() != null && !org.getHint().equals(group.getHint()) || org.getHint() == null && group.getHint() != null) { Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_GROUPS, new String[] { "DESCRIPTION", "HINT" }, "ID", group.getId()); if (changes) changesDesc.append(','); changesDesc.append("label=").append(group.getLabel()).append(','); changesDesc.append("hint=").append(group.getHint()).append(','); changes = true; } // change the group's name if (!org.getName().equals(group.getName())) { ps = con.prepareStatement("UPDATE " + TBL_STRUCT_GROUPS + " SET NAME=? WHERE ID=?"); ps.setString(1, group.getName()); ps.setLong(2, group.getId()); ps.executeUpdate(); ps.close(); if (changes) changesDesc.append(','); changesDesc.append("name=").append(group.getName()); changes = true; } // change the group options if (updateGroupOptions(con, group)) { changesDesc.append(",options:"); List<FxStructureOption> options = group.getOptions(); for (FxStructureOption option : options) { changesDesc.append(option.getKey()).append("=").append(option.getValue()) .append(" overridable=").append(option.isOverridable()).append(" isSet=") .append(option.isSet()); } changes = true; } if (changes) { htracker.track("history.group.update.groupProperties", group.getName(), group.getId(), changesDesc.toString()); } success = true; } catch (SQLException e) { EJBUtils.rollback(ctx); throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { Database.closeObjects(AssignmentEngineBean.class, null, ps); if (!success) { EJBUtils.rollback(ctx); } } return changes; }
From source file:com.flexive.ejb.beans.PhraseEngineBean.java
/** * {@inheritDoc}/*from w w w.j a v a 2 s. c om*/ */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<FxPhraseTreeNodePosition> getAssignedNodes(int category, String phraseKey, long... _mandators) { final long ownMandator = FxContext.getUserTicket().getMandatorId(); Connection con = null; PreparedStatement ps = null; long[] mandators = checkMandatorFiltering(_mandators); try { // Obtain a database connection con = Database.getDbConnection(); List<FxPhraseTreeNodePosition> result = Lists.newArrayListWithCapacity(10); final String mandatorQuery = mandators.length == 1 ? "=" + mandators[0] : " IN(" + FxArrayUtils.toStringArray(mandators, ',') + ")"; ps = con.prepareStatement("SELECT m.NODEID,m.NODEMANDATOR,m.POS FROM " + TBL_PHRASE_MAP + " m," + TBL_PHRASE + " p WHERE p.PKEY=? AND p.MANDATOR" + mandatorQuery + " AND p.CAT=? AND m.PHRASEID=p.ID AND m.CAT=p.CAT AND m.DIRECT=? AND m.MANDATOR" + mandatorQuery + " ORDER BY m.NODEMANDATOR,m.NODEID,m.POS"); ps.setString(1, phraseKey); ps.setInt(2, category); ps.setBoolean(3, true); ResultSet rs = ps.executeQuery(); while (rs != null && rs.next()) { try { result.add(new FxPhraseTreeNodePosition(loadPhraseTreeNode(con, false, category, rs.getLong(1), rs.getLong(2), false, mandators), rs.getLong(3))); } catch (FxNotFoundException e) { LOG.error("Failed to load node " + rs.getLong(1) + " (mandator " + rs.getLong(2) + ") found! This should not be possible!"); } } return result; } catch (SQLException exc) { EJBUtils.rollback(ctx); throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException(); } finally { Database.closeObjects(PhraseEngineBean.class, con, ps); } }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
/** * Update all the existing field values in the database with the default * value for that field// w w w. j av a 2s. c om */ private void setFieldDefaultDbAction(Connection conn, BaseField field) throws SQLException, CantDoThatException, ObjectNotFoundException, CodingErrorException { if (field.hasDefault()) { String internalTableName = field.getTableContainingField().getInternalTableName(); String internalFieldName = field.getInternalFieldName(); String SQLCode = "UPDATE " + internalTableName + " SET " + internalFieldName + "=?"; PreparedStatement statement = conn.prepareStatement(SQLCode); if (field instanceof TextField) { String defaultValue = ((TextField) field).getDefault(); statement.setString(1, defaultValue); } else if (field instanceof DecimalField) { Double defaultValue = ((DecimalField) field).getDefault(); statement.setDouble(1, defaultValue); } else if (field instanceof IntegerField) { Integer defaultValue = ((IntegerField) field).getDefault(); statement.setInt(1, defaultValue); } else if (field instanceof CheckboxField) { Boolean defaultValue = ((CheckboxField) field).getDefault(); statement.setBoolean(1, defaultValue); } else if (field instanceof DateField) { Calendar defaultValueCalendar = ((DateField) field).getDefault(); Timestamp defaultValue = new Timestamp(defaultValueCalendar.getTimeInMillis()); statement.setTimestamp(1, defaultValue); } else { throw new CantDoThatException( "Unable to set default value for field type " + field.getFieldCategory()); } statement.execute(); statement.close(); } }
From source file:org.getobjects.eoaccess.EOAdaptorChannel.java
protected PreparedStatement _prepareStatementWithBinds(final String _sql, final List<Map<String, Object>> _binds) { boolean isDebugOn = log.isDebugEnabled(); if (_sql == null || _sql.length() == 0) return null; final PreparedStatement stmt = this._createPreparedStatement(_sql); if (stmt == null) return null; if (_binds == null) { if (isDebugOn) log.debug("statement to prepare has no binds .."); return stmt; /* hm, statement has no binds */ }//w ww . j a v a 2 s . co m /* fill in parameters */ if (isDebugOn) log.debug("prepare binds: " + _binds); try { /* Fill statement with bindg values */ for (int i = 0; i < _binds.size(); i++) { /* a dictionary with such keys: * BindVariableAttributeKey - the EOAttribute of the value * BindVariableValueKey - the actual value */ final Map<String, Object> bind = _binds.get(i); final EOAttribute attribute = (EOAttribute) bind.get(EOSQLExpression.BindVariableAttributeKey); final Object value = bind.get(EOSQLExpression.BindVariableValueKey); int sqlType = this.sqlTypeForValue(value, attribute); if (isDebugOn) { log.debug(" bind attribute: " + attribute); log.debug(" value: " + value + " / " + (value != null ? value.getClass() : "[NULL]")); log.debug(" type: " + sqlType); } if (value == null) stmt.setNull(i + 1, sqlType); else { switch (sqlType) { case java.sql.Types.NULL: stmt.setNull(i + 1, java.sql.Types.VARCHAR); // CRAP break; // TODO: customize value processing for types case java.sql.Types.VARCHAR: case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: case java.sql.Types.INTEGER: case java.sql.Types.BIGINT: case java.sql.Types.BOOLEAN: default: if (value instanceof String) stmt.setString(i + 1, (String) value); else if (value instanceof Boolean) stmt.setBoolean(i + 1, (Boolean) value); else if (value instanceof Integer) stmt.setInt(i + 1, (Integer) value); else if (value instanceof Double) stmt.setDouble(i + 1, (Double) value); else if (value instanceof BigDecimal) stmt.setBigDecimal(i + 1, (BigDecimal) value); else if (value instanceof Long) stmt.setLong(i + 1, (Long) value); else if (value instanceof java.util.Date) { // TBD: shouldn't we use setDate with a proper Calendar? stmt.setTimestamp(i + 1, new java.sql.Timestamp(((Date) value).getTime())); } else if (value instanceof java.util.Calendar) { // TBD: shouldn't we use setDate with a proper Calendar? final Date vd = ((Calendar) value).getTime(); stmt.setTimestamp(i + 1, new java.sql.Timestamp(vd.getTime())); } else if (value instanceof java.sql.Date) { /* Note: this is just the DATE component, no TIME */ stmt.setDate(i + 1, (java.sql.Date) value); } else if (value instanceof byte[]) stmt.setBytes(i + 1, (byte[]) value); else if (value instanceof EOQualifierVariable) { log.error("detected unresolved qualifier variable: " + value); this._releaseResources(stmt, null); return null; } else { log.warn("using String column for value: " + value + " (" + value.getClass() + ")"); } } } } } catch (NullPointerException e) { this.lastException = e; log.error("could not apply binds to prepared statement (null ptr): " + _sql, e); this._releaseResources(stmt, null); return null; } catch (SQLException e) { this.lastException = e; log.error("could not apply binds to prepared statement: " + _sql, e); this._releaseResources(stmt, null); return null; } return stmt; }
From source file:com.flexive.ejb.beans.PhraseEngineBean.java
private void rebuildPhraseChildMapping(Connection _con, long mandator, int category, long phraseId, long phraseMandator) { if (FxContext.preventPhraseTreeRebuild()) return;/*from ww w . j a v a 2 s. c o m*/ /* - delete all non-direct mappings for mandator and category - for all direct nodes of mandator fetch: - nodeid, nodemandator, phraseid, phrasemandator */ Connection con = _con; PreparedStatement ps = null, psNodeFetch = null, psNodeAdd = null, psNodeCheck = null; //Set<String> duplicateCheck = new HashSet<String>(); try { // Obtain a database connection if (con == null) con = Database.getDbConnection(); boolean singlePhraseOnly = phraseId != -1 && phraseMandator != -1; if (singlePhraseOnly) { ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP + " WHERE MANDATOR=? AND CAT=? AND DIRECT=? AND PHRASEID=? AND PMANDATOR=?"); ps.setLong(4, phraseId); ps.setLong(5, phraseMandator); } else ps = con.prepareStatement( "DELETE FROM " + TBL_PHRASE_MAP + " WHERE MANDATOR=? AND CAT=? AND DIRECT=?"); ps.setLong(1, mandator); ps.setInt(2, category); ps.setBoolean(3, false); ps.executeUpdate(); ps.close(); if (singlePhraseOnly) { // 1 2 3 4 ps = con.prepareStatement("SELECT NODEID,NODEMANDATOR,PHRASEID,PMANDATOR FROM " + TBL_PHRASE_MAP + " WHERE MANDATOR=? AND CAT=? AND DIRECT=? AND PHRASEID=? AND PMANDATOR=?"); ps.setLong(4, phraseId); ps.setLong(5, phraseMandator); } else { // 1 2 3 4 ps = con.prepareStatement("SELECT NODEID,NODEMANDATOR,PHRASEID,PMANDATOR FROM " + TBL_PHRASE_MAP + " WHERE MANDATOR=? AND CAT=? AND DIRECT=?"); } ps.setLong(1, mandator); ps.setInt(2, category); ps.setBoolean(3, true); ResultSet rs = ps.executeQuery(); // 1 2 3 4 5 6 7 psNodeAdd = con.prepareStatement("INSERT INTO " + TBL_PHRASE_MAP + " (NODEID,NODEMANDATOR,PHRASEID,PMANDATOR,MANDATOR,CAT,DIRECT)VALUES(?,?,?,?,?,?,?)"); psNodeAdd.setLong(5, mandator); psNodeAdd.setInt(6, category); psNodeAdd.setBoolean(7, false); // 1 2 3 4 5 6 psNodeFetch = con.prepareStatement("SELECT ID,MANDATOR,PARENTID,PARENTMANDATOR,PHRASEID,PMANDATOR FROM " + TBL_PHRASE_TREE + " WHERE ID=? AND MANDATOR=? AND CAT=?"); psNodeFetch.setInt(3, category); // 1 2 3 4 5 6 psNodeCheck = con.prepareStatement("SELECT COUNT(*) FROM " + TBL_PHRASE_MAP + " WHERE NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=? AND MANDATOR=? AND CAT=?"); psNodeCheck.setLong(5, mandator); psNodeCheck.setInt(6, category); while (rs != null && rs.next()) { psNodeFetch.setLong(1, rs.getLong(1)); psNodeFetch.setLong(2, rs.getLong(2)); final long currPhraseId = rs.getLong(3); final long currPhraseMandator = rs.getLong(4); psNodeCheck.setLong(3, currPhraseId); psNodeCheck.setLong(4, currPhraseMandator); psNodeAdd.setLong(3, currPhraseId); psNodeAdd.setLong(4, currPhraseMandator); ResultSet rsNodeFetch = psNodeFetch.executeQuery(); if (rsNodeFetch != null && rsNodeFetch.next()) { long nodeId = rsNodeFetch.getLong(3); boolean hasParent = !rsNodeFetch.wasNull(); long nodeMandator = rsNodeFetch.getLong(4); while (hasParent) { //add indirect nodemapping psNodeAdd.setLong(1, nodeId); psNodeAdd.setLong(2, nodeMandator); psNodeCheck.setLong(1, nodeId); psNodeCheck.setLong(2, nodeMandator); //final String key = nodeId + "-" + nodeMandator + "-" + rs.getLong(3) + "-" + rs.getLong(4); ResultSet rsCheck = psNodeCheck.executeQuery(); if (rsCheck != null && rsCheck.next() && rsCheck.getLong(1) == 0) { //if(!duplicateCheck.contains(key)) psNodeAdd.executeUpdate(); /* else { System.err.println("Duplicate: "+key); }*/ //duplicateCheck.add(key); } psNodeFetch.setLong(1, rsNodeFetch.getLong(3)); psNodeFetch.setLong(2, rsNodeFetch.getLong(4)); rsNodeFetch = psNodeFetch.executeQuery(); if (rsNodeFetch != null && rsNodeFetch.next()) { nodeId = rsNodeFetch.getLong(3); hasParent = !rsNodeFetch.wasNull(); nodeMandator = rsNodeFetch.getLong(4); } else hasParent = false; } } } // System.out.println("dup size:"+duplicateCheck.size()); } catch (SQLException exc) { EJBUtils.rollback(ctx); throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException(); } finally { Database.closeObjects(PhraseEngineBean.class, psNodeAdd, psNodeFetch, psNodeCheck); if (_con == null) Database.closeObjects(PhraseEngineBean.class, _con, ps); else Database.closeObjects(PhraseEngineBean.class, ps); } }
From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java
/** * {@inheritDoc}//from w w w . ja va 2 s . com */ @Override public FxContent contentLoad(Connection con, FxPK pk, FxEnvironment env, StringBuilder sql) throws FxLoadException, FxInvalidParameterException, FxNotFoundException { if (pk.isNew()) throw new FxInvalidParameterException("pk", "ex.content.load.newPK"); if (sql == null) sql = new StringBuilder(1000); sql.append(CONTENT_MAIN_LOAD); sql.append(" WHERE ID=? AND "); if (pk.isDistinctVersion()) sql.append(" VER=?"); else if (pk.getVersion() == FxPK.LIVE) sql.append(" ISLIVE_VER=?"); else if (pk.getVersion() == FxPK.MAX) sql.append(" ISMAX_VER=?"); PreparedStatement ps = null; FxPK contentPK, sourcePK = null, destinationPK = null; int srcPos = 0, dstPos = 0; Connection conNoTX = null; try { ps = con.prepareStatement(sql.toString()); ps.setLong(1, pk.getId()); if (pk.isDistinctVersion()) ps.setInt(2, pk.getVersion()); else ps.setBoolean(2, true); ResultSet rs = ps.executeQuery(); if (rs == null || !rs.next()) throw new FxNotFoundException("ex.content.notFound", pk); contentPK = new FxPK(rs.getLong(1), rs.getInt(2)); FxType type = env.getType(rs.getLong(3)); final long aclId = rs.getLong(4); Step step = env.getStep(rs.getLong(5)); Mandator mand = env.getMandator(rs.getInt(22)); final GroupPositionsProvider groupPositions = new GroupPositionsProvider(rs.getString(25)); if (!type.getAssignmentsForDataType(FxDataType.Binary).isEmpty()) { conNoTX = Database.getNonTXDataSource().getConnection(); } FxGroupData root = loadDetails(con, conNoTX, type, env, contentPK, pk.getVersion(), groupPositions); rs.getLong(12); if (!rs.wasNull()) { sourcePK = new FxPK(rs.getLong(12), rs.getInt(13)); destinationPK = new FxPK(rs.getLong(14), rs.getInt(15)); srcPos = rs.getInt(16); dstPos = rs.getInt(17); } FxContent content = new FxContent(contentPK, null /* use lazy loading for lock */, type.getId(), type.isRelation(), mand.getId(), aclId != ACL.NULL_ACL_ID ? aclId : -1, step.getId(), rs.getInt(6), rs.getInt(7), rs.getBoolean(10), rs.getInt(11), sourcePK, destinationPK, srcPos, dstPos, LifeCycleInfoImpl.load(rs, 18, 19, 20, 21), root, rs.getLong(23), rs.getLong(24)) .initSystemProperties(); if (rs.next()) throw new FxLoadException("ex.content.load.notDistinct", pk); if (type.isMultipleContentACLs() && aclId == ACL.NULL_ACL_ID) { content.setAclIds(loadContentAclTable(con, content.getPk())); } return content; } catch (SQLException e) { throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage()); } catch (FxDbException e) { throw new FxLoadException(e); } finally { Database.closeObjects(GenericHierarchicalStorage.class, conNoTX, ps); } }
From source file:com.flexive.ejb.beans.AccountEngineBean.java
/** * {@inheritDoc}//w w w . ja v a2s.com */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void update(long accountId, String password, Long defaultNode, String name, String loginName, String email, Boolean isConfirmed, Boolean isActive, Date validFrom, Date validTo, Long lang, String description, Boolean allowMultiLogin, Long contactDataId) throws FxApplicationException { // Load the account to update Account account = load(accountId); StringBuilder sbHistory = new StringBuilder(1000); sbHistory.append("<original>\n").append(" <id>").append(accountId).append("</id>\n").append(" <mandator>") .append(CacheAdmin.getEnvironment().getMandator(account.getMandatorId()).getName()) .append("</mandator>\n").append(" <username>").append(account.getName()).append("</username>\n") .append(" <loginname>").append(account.getLoginName()).append("</loginname>\n").append(" <email>") .append(account.getEmail()).append("</email>\n").append(" <validfrom>") .append(account.getValidFromString()).append("</validfrom>\n").append(" <validto>") .append(account.getValidToString()).append("</validto>\n").append(" <description><![CDATA[") .append(account.getDescription()).append("]]></description>\n").append(" <active>") .append(account.isActive()).append("</active>\n").append(" <confirmed>") .append(account.isValidated()).append("</confirmed>\n").append(" <multilogin>") .append(account.isAllowMultiLogin()).append("</multilogin>\n").append("</original>\n"); final UserTicket ticket = FxContext.getUserTicket(); // Determine if only fields are accessed that the use may alter for himself final boolean protectedFields = (name != null || loginName != null || isConfirmed != null || isActive != null || validTo != null || validFrom != null || description != null); if (!protectedFields && ticket.getUserId() == accountId) { // passed } else { if (!_checkPermissions(account)[MAY_UPDATE]) throw new FxNoAccessException(LOG, "ex.account.update.noPermission", account.getName()); } // Parameter checks try { if (loginName != null) loginName = checkLoginName(loginName); if (email != null) email = FxFormatUtils.checkEmail(email); if (password != null) { password = FxFormatUtils.encodePassword(accountId, StringUtils.defaultString(loginName, account.getLoginName()), password.trim()); } if (lang != null && !language.isValid(lang)) throw new FxInvalidParameterException("LANGUAGE", "ex.account.languageInvalid", lang); } catch (FxInvalidParameterException pe) { if (LOG.isInfoEnabled()) LOG.info(pe); throw pe; } Connection con = null; PreparedStatement stmt = null; String curSql; if (name == null) name = account.getName(); if (loginName == null) loginName = account.getLoginName(); if (email == null) email = account.getEmail(); if (lang == null) lang = account.getLanguage().getId(); if (isActive == null) isActive = account.isActive(); if (isConfirmed == null) isConfirmed = account.isValidated(); if (description == null) description = account.getDescription(); if (defaultNode == null) defaultNode = account.getDefaultNode(); if (allowMultiLogin == null) allowMultiLogin = account.isAllowMultiLogin(); // Assign and check dates if (validFrom == null) validFrom = account.getValidFrom(); if (validTo == null) validTo = account.getValidTo(); checkDates(validFrom, validTo); if (defaultNode < 0) defaultNode = (long) 0; try { // Obtain a database connection con = Database.getDbConnection(); curSql = "UPDATE " + TBL_ACCOUNTS + " SET " + // 1 2 3 4 5 6 "EMAIL=?,LANG=?,VALID_FROM=?,VALID_TO=?,DESCRIPTION=?," + // 6 7 8 9 10 "MODIFIED_BY=?,MODIFIED_AT=?,IS_ACTIVE=?,IS_VALIDATED=?,DEFAULT_NODE=?," + // 11, 12 , 13 , 14 "USERNAME=?,LOGIN_NAME=?,ALLOW_MULTILOGIN=?" + ((password != null) ? ",PASSWORD=?" : "") + ((contactDataId != null) ? ",CONTACT_ID=?" : "") + " WHERE ID=" + accountId; stmt = con.prepareStatement(curSql); stmt.setString(1, email); stmt.setInt(2, lang.intValue()); stmt.setLong(3, validFrom.getTime()); stmt.setLong(4, validTo.getTime()); stmt.setString(5, description); stmt.setLong(6, ticket.getUserId()); stmt.setLong(7, System.currentTimeMillis()); stmt.setBoolean(8, isActive); stmt.setBoolean(9, isConfirmed); stmt.setLong(10, defaultNode); stmt.setString(11, name); stmt.setString(12, loginName); stmt.setBoolean(13, allowMultiLogin); int pos = 14; if (password != null) stmt.setString(pos++, password); if (contactDataId != null) stmt.setLong(pos/*++*/, contactDataId); stmt.executeUpdate(); if (contactDataId != null) { //make sure the user is the owner of his contact data stmt.close(); stmt = con.prepareStatement("UPDATE " + TBL_CONTENT + " SET CREATED_BY=? WHERE ID=?"); stmt.setLong(1, accountId); stmt.setLong(2, contactDataId); stmt.executeUpdate(); } // Log the user out of the system if he was made active if (!isActive || !isConfirmed) { UserTicketStore.removeUserId(accountId, null); } else { // Ensure any active ticket of the updated user are refreshed UserTicketStore.flagDirtyHavingUserId(account.getId()); } sbHistory.append("<new>\n").append(" <id>").append(accountId).append("</id>\n").append(" <mandator>") .append(CacheAdmin.getEnvironment().getMandator(account.getMandatorId()).getName()) .append("</mandator>\n").append(" <username>").append(name).append("</username>\n") .append(" <loginname>").append(loginName).append("</loginname>\n").append(" <email>") .append(email).append("</email>\n").append(" <validfrom>") .append(FxFormatUtils.toString(validFrom)).append("</validfrom>\n").append(" <validto>") .append(FxFormatUtils.toString(validTo)).append("</validto>\n") .append(" <description><![CDATA[").append(description).append("]]></description>\n") .append(" <active>").append(isActive).append("</active>\n").append(" <confirmed>") .append(isConfirmed).append("</confirmed>\n").append(" <multilogin>").append(allowMultiLogin) .append("</multilogin>\n").append("</new>"); EJBLookup.getHistoryTrackerEngine().trackData(sbHistory.toString(), "history.account.update", account.getLoginName()); } catch (SQLException exc) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc); EJBUtils.rollback(ctx); if (uniqueConstraintViolation) { throw new FxEntryExistsException(LOG, "ex.account.userExists", name, loginName); } else { throw new FxUpdateException(LOG, "ex.account.update.failed.sql", account.getLoginName(), exc.getMessage()); } } finally { Database.closeObjects(AccountEngineBean.class, con, stmt); } }
From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java
private void storeOptions(Connection con, String table, String primaryColumn, long primaryId, Long assignmentId, List<FxStructureOption> options) throws SQLException, FxInvalidParameterException { PreparedStatement ps = null; try {//from w w w . j a v a 2s . c o m if (assignmentId == null) { ps = con.prepareStatement( "DELETE FROM " + table + " WHERE " + primaryColumn + "=? AND ASSID IS NULL"); } else { ps = con.prepareStatement("DELETE FROM " + table + " WHERE " + primaryColumn + "=? AND ASSID=?"); ps.setLong(2, assignmentId); } ps.setLong(1, primaryId); ps.executeUpdate(); if (options == null || options.size() == 0) return; ps.close(); ps = con.prepareStatement("INSERT INTO " + table + " (" + primaryColumn + ",ASSID,OPTKEY,MAYOVERRIDE,ISINHERITED,OPTVALUE)VALUES(?,?,?,?,?,?)"); for (FxStructureOption option : options) { ps.setLong(1, primaryId); if (assignmentId != null) ps.setLong(2, assignmentId); else ps.setNull(2, java.sql.Types.NUMERIC); if (StringUtils.isEmpty(option.getKey())) throw new FxInvalidParameterException("key", "ex.structure.option.key.empty", option.getValue()); ps.setString(3, option.getKey()); ps.setBoolean(4, option.isOverridable()); ps.setBoolean(5, option.getIsInherited()); ps.setString(6, option.getValue()); ps.addBatch(); } ps.executeBatch(); } finally { if (ps != null) ps.close(); } }
From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java
/** * Update the main entry/*from w w w. java 2 s. com*/ * * @param con an open and valid connection * @param content content to create * @throws FxUpdateException on errors */ protected void updateMainEntry(Connection con, FxContent content) throws FxUpdateException { PreparedStatement ps = null; try { ps = con.prepareStatement(CONTENT_MAIN_UPDATE); ps.setLong(19, content.getPk().getId()); ps.setInt(20, content.getPk().getVersion()); ps.setLong(1, content.getTypeId()); ps.setLong(2, content.getAclIds().size() > 1 ? ACL.NULL_ACL_ID : content.getAclIds().get(0)); ps.setLong(3, content.getStepId()); ps.setInt(4, content.getMaxVersion()); ps.setInt(5, content.getLiveVersion()); ps.setBoolean(6, content.isMaxVersion()); ps.setBoolean(7, content.isLiveVersion()); ps.setBoolean(8, content.isActive()); ps.setInt(9, (int) content.getMainLanguage()); if (content.isRelation()) { ps.setLong(10, content.getRelatedSource().getId()); ps.setInt(11, content.getRelatedSource().getVersion()); ps.setLong(12, content.getRelatedDestination().getId()); ps.setInt(13, content.getRelatedDestination().getVersion()); ps.setLong(14, content.getRelatedSourcePosition()); ps.setLong(15, content.getRelatedDestinationPosition()); } else { ps.setNull(10, java.sql.Types.NUMERIC); ps.setNull(11, java.sql.Types.NUMERIC); ps.setNull(12, java.sql.Types.NUMERIC); ps.setNull(13, java.sql.Types.NUMERIC); ps.setNull(14, java.sql.Types.NUMERIC); ps.setNull(15, java.sql.Types.NUMERIC); } if (content.isForceLifeCycle()) { ps.setLong(16, content.getValue(FxLargeNumber.class, "/MODIFIED_BY").getBestTranslation()); ps.setLong(17, content.getValue(FxDateTime.class, "/MODIFIED_AT").getBestTranslation().getTime()); } else { long userId = FxContext.getUserTicket().getUserId(); ps.setLong(16, userId); ps.setLong(17, System.currentTimeMillis()); } setGroupPositions(ps, content, 18); ps.executeUpdate(); if (content.isForceLifeCycle()) { ps.close(); // update created_at/created_by ps = con.prepareStatement(CONTENT_MAIN_UPDATE_CREATED_AT); ps.setLong(1, content.getValue(FxDateTime.class, "/CREATED_AT").getBestTranslation().getTime()); ps.setLong(2, content.getValue(FxLargeNumber.class, "/CREATED_BY").getBestTranslation()); ps.setLong(3, content.getPk().getId()); ps.setInt(4, content.getPk().getVersion()); ps.executeUpdate(); } updateACLEntries(con, content, content.getPk(), false); } catch (SQLException e) { throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage()); } catch (FxCreateException e) { throw new FxUpdateException(e); } finally { Database.closeObjects(GenericHierarchicalStorage.class, ps); } }