Example usage for java.sql PreparedStatement setBoolean

List of usage examples for java.sql PreparedStatement setBoolean

Introduction

In this page you can find the example usage for java.sql PreparedStatement setBoolean.

Prototype

void setBoolean(int parameterIndex, boolean x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java boolean value.

Usage

From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java

public void updateChannel(Channel channel) {
    Connection conn = null;//from  w w w  .  ja v a  2s.c o m
    PreparedStatement ps = null;

    try {
        conn = DriverManager.getConnection(JdbcChannelDAO.POOL_CONNECT_STRING);
        ps = conn.prepareStatement("UPDATE " + TABLE_CHANNELS + " " + "SET author = ?, name = ?, url = ?, "
                + "title = ?, link = ?, description = ?, " + "lastArticle = ?, "
                + "lastPolled = ?, lastCleaned = ?, lastModified = ?, lastETag = ?, rssVersion = ?, "
                + "enabled = ?, " + "postingEnabled = ?, " + "publishAPI = ?, " + "publishConfig = ?, "
                + "parseAtAllCost = ?, " + "managingEditor = ?, " + "pollingInterval = ?, " + "status = ?, "
                + "expiration = ?, " + "category = ? " + "WHERE id = ?");

        int paramCount = 1;
        ps.setString(paramCount++, trim(channel.getAuthor(), FIELD_CHANNEL_AUTHOR_LENGTH));
        ps.setString(paramCount++, trim(channel.getName(), FIELD_CHANNEL_NAME_LENGTH));
        ps.setString(paramCount++, channel.getUrl());
        ps.setString(paramCount++, trim(channel.getTitle(), FIELD_CHANNEL_TITLE_LENGTH));
        ps.setString(paramCount++, channel.getLink());
        ps.setString(paramCount++, channel.getDescription());
        ps.setInt(paramCount++, channel.getLastArticleNumber());

        if (channel.getLastPolled() != null) {
            ps.setTimestamp(paramCount++, new Timestamp(channel.getLastPolled().getTime()));
        } else {
            ps.setNull(paramCount++, java.sql.Types.TIMESTAMP);
        }

        if (channel.getLastCleaned() != null) {
            ps.setTimestamp(paramCount++, new Timestamp(channel.getLastCleaned().getTime()));
        } else {
            ps.setNull(paramCount++, java.sql.Types.TIMESTAMP);
        }

        ps.setLong(paramCount++, channel.getLastModified());
        ps.setString(paramCount++, channel.getLastETag());
        ps.setString(paramCount++, trim(channel.getRssVersion(), FIELD_CHANNEL_VERSION_LENGTH));
        //                  ps.setBoolean(paramCount++, channel.isHistorical());
        ps.setBoolean(paramCount++, channel.isEnabled());
        ps.setBoolean(paramCount++, channel.isPostingEnabled());
        ps.setString(paramCount++, channel.getPublishAPI());
        ps.setString(paramCount++, XMLHelper.stringMapToXML(channel.getPublishConfig()));
        ps.setBoolean(paramCount++, channel.isParseAtAllCost());

        ps.setString(paramCount++, trim(channel.getManagingEditor(), FIELD_CHANNEL_MANAGING_EDITOR_LENGTH));

        ps.setLong(paramCount++, channel.getPollingIntervalSeconds());
        ps.setInt(paramCount++, channel.getStatus());
        ps.setLong(paramCount++, channel.getExpiration());
        int categoryId = 0;
        if (channel.getCategory() != null) {
            categoryId = channel.getCategory().getId();
        }
        ps.setInt(paramCount++, categoryId);

        ps.setInt(paramCount++, channel.getId());
        ps.executeUpdate();

    } catch (SQLException se) {
        throw new RuntimeException(se);
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException se) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
        }
    }

}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

public synchronized void flushBatch() throws SQLException {
    if (batchCommit && tripleBatch != null) {
        requireJDBCConnection();/*from  w  w  w.j a  v  a 2 s.  c  om*/

        commitLock.lock();
        try {
            RetryExecution execution = new RetryExecution("FLUSH BATCH");
            execution.setUseSavepoint(true);
            execution.execute(connection, new RetryCommand<Void>() {
                @Override
                public Void run() throws SQLException {
                    PreparedStatement insertTriple = getPreparedStatement("store.triple");
                    insertTriple.clearParameters();
                    insertTriple.clearBatch();

                    synchronized (tripleBatch) {
                        for (KiWiTriple triple : tripleBatch) {
                            // retrieve a new triple ID and set it in the object
                            if (triple.getId() < 0) {
                                triple.setId(getNextSequence());
                            }

                            insertTriple.setLong(1, triple.getId());
                            insertTriple.setLong(2, triple.getSubject().getId());
                            insertTriple.setLong(3, triple.getPredicate().getId());
                            insertTriple.setLong(4, triple.getObject().getId());
                            if (triple.getContext() != null) {
                                insertTriple.setLong(5, triple.getContext().getId());
                            } else {
                                insertTriple.setNull(5, Types.BIGINT);
                            }
                            insertTriple.setBoolean(6, triple.isInferred());
                            insertTriple.setTimestamp(7, new Timestamp(triple.getCreated().getTime()));

                            insertTriple.addBatch();
                        }
                    }
                    insertTriple.executeBatch();

                    tripleBatch.clear();

                    return null;
                }
            });

        } finally {
            commitLock.unlock();
        }

    }

}

From source file:org.siphon.jssql.SqlExecutor.java

void setArg(PreparedStatement ps, int index, Object arg) throws SQLException, SqlExecutorException,
        UnsupportedDataTypeException, NoSuchMethodException, ScriptException {
    boolean output = false;
    int outputParameterType = 0;
    CallableStatement cs = null;/*from  w w  w  .j a  v  a2 s . co  m*/
    if (ps instanceof CallableStatement) {
        cs = (CallableStatement) ps;
        if (arg instanceof ScriptObjectMirror && ((ScriptObjectMirror) arg).containsKey("OUT")) {
            ScriptObjectMirror jsarg = ((ScriptObjectMirror) arg);
            outputParameterType = (int) jsarg.get("JDBC_TYPE");
            arg = jsarg.get("VALUE");
            output = true;
        }
    }
    if (output) {
        cs.registerOutParameter(index + 1, outputParameterType);
        if (JsTypeUtil.isNull(arg) || (arg instanceof Double && Double.isNaN((Double) arg))) {
            return;
        }
    }

    if (JsTypeUtil.isNull(arg)) {
        ps.setObject(index + 1, null);
    } else if (arg instanceof CharSequence) {
        ps.setString(index + 1, arg.toString());
    } else if (arg instanceof NativeString) {
        ps.setString(index + 1, arg.toString());
    } else if (arg instanceof Double) { // js number always be
        // Doublebut if its came from
        // JSON.parse since JSON is jdk
        // given global object, it will
        // make Integer and ...
        double d = ((Double) arg).doubleValue();
        if (d == (int) d) {
            ps.setInt(index + 1, (int) d);
        } else if (d == (long) d) {
            ps.setLong(index + 1, (long) d);
        } else {
            ps.setBigDecimal(index + 1, new BigDecimal(d));
        }
    } else if (arg instanceof Integer) {
        ps.setInt(index + 1, (Integer) arg);
    } else if (arg instanceof Long) {
        ps.setLong(index + 1, (Long) arg);
    } else if (arg instanceof Float) {
        ps.setFloat(index + 1, (Float) arg);
    } else if (jsTypeUtil.isNativeDate(arg)) {
        ps.setTimestamp(index + 1, parseDate(arg));
    } else if (arg instanceof ZonedDateTime) {
        ZonedDateTime zdt = (ZonedDateTime) arg;
        ps.setTimestamp(index + 1, new Timestamp(zdt.toInstant().toEpochMilli()));
    } else if (arg instanceof Boolean) {
        ps.setBoolean(index + 1, JsTypeUtil.isTrue(arg));
    } else if (arg instanceof ScriptObjectMirror || arg instanceof ScriptObject) {
        String attr = null;
        Object value = null;
        if (arg instanceof ScriptObjectMirror) {
            ScriptObjectMirror atm = (ScriptObjectMirror) arg;
            if (atm.keySet().contains("toJavaObject")) {
                Object obj = atm.callMember("toJavaObject");
                setArg(ps, index, obj);
                return;
            }

            attr = atm.keySet().iterator().next();
            value = atm.get(attr);
        } else {
            ScriptObject obj = (ScriptObject) arg;
            if (obj.containsKey("toJavaObject")) {
                ScriptObjectMirror atm = (ScriptObjectMirror) jsTypeUtil.toScriptObjectMirror(obj);
                Object result = atm.callMember("toJavaObject");
                setArg(ps, index, result);
                return;
            }
            String[] arr = obj.getOwnKeys(false);
            if (arr.length == 0) {
                throw new SqlExecutorException("js argument " + arg + " (" + arg.getClass() + ") at " + index
                        + " is an empty js object");
            }
            attr = arr[0];
            value = obj.get(attr);
        }

        if ("STRING".equals(attr)) {
            ps.setString(index + 1, String.valueOf(value));
        } else if ("DECIMAL".equals(attr)) {
            if (value instanceof Double) {
                ps.setBigDecimal(index + 1, new BigDecimal((Double) value));
            } else {
                ps.setBigDecimal(index + 1, new BigDecimal(value + ""));
            }
        } else if ("INT".equals(attr)) {
            if (value instanceof Double) {
                if (((Double) value).isNaN()) {
                    ps.setObject(index + 1, null);
                } else {
                    ps.setInt(index + 1, ((Double) value).intValue());
                }
            } else {
                ps.setInt(index + 1, new Integer(value + ""));
            }
        } else if ("BOOLEAN".equals(attr)) {
            ps.setBoolean(index + 1, JsTypeUtil.isTrue(arg));
        } else if ("DOUBLE".equals(attr)) {
            if (value instanceof Double) {
                if (((Double) value).isNaN()) {
                    ps.setObject(index + 1, null);
                } else {
                    ps.setDouble(index + 1, (double) value);
                }
            } else {
                ps.setDouble(index + 1, new Double(value + ""));
            }
        } else if ("FLOAT".equals(attr)) {
            if (value instanceof Double) {
                if (((Double) value).isNaN()) {
                    ps.setObject(index + 1, null);
                } else {
                    ps.setFloat(index + 1, (float) (double) value);
                }
            } else {
                ps.setFloat(index + 1, new Float(value + ""));
            }
        } else if ("DATE".equals(attr)) {
            ps.setTimestamp(index + 1, parseDate(value));
        } else if ("TIME".equals(attr)) {
            ps.setTimestamp(index + 1, parseTime(value));
        } else if ("BINARY".equals(attr)) {
            ps.setBytes(index + 1, parseBinary(value));
        } else if ("CLOB".equals(attr)) {
            Clob clob = ps.getConnection().createClob();
            clob.setString(1, String.valueOf(value));
            ps.setClob(index + 1, clob);
        } else if ("LONG".equals(attr)) {
            if (value instanceof Double) {
                if (((Double) value).isNaN()) {
                    ps.setObject(index + 1, null);
                } else {
                    ps.setLong(index + 1, ((Double) value).longValue());
                }
            } else {
                ps.setLong(index + 1, new Long(value + ""));
            }
        } else if ("OUTCURSOR".equals(attr)) {
            // cs.registerOutParameter(i+1, OracleTypes.CURSOR);
            cs.registerOutParameter(index + 1, -10);
        } else if ("ARRAY".equals(attr)) {
            if (value instanceof NativeArray) {
                ps.setArray(index + 1, createSqlArray(ps.getConnection(), (NativeArray) value));
            } else {
                setArg(ps, index, value); // value is {ARRAY : ['int', e1, e2, ...]}
            }
            // ps.setObject(i+1, createSqlArray(ps.getConnection(),
            // (NativeArray) value));
        } else if ("JSON".equals(attr) || "JSONB".equals(attr)) {
            PGobject obj = new PGobject();
            obj.setType(attr.toLowerCase());
            obj.setValue(this.JSON.tryStringify(value));
            ps.setObject(index + 1, obj);
        } else if ("UUID".equals(attr)) {
            if (value != null) {
                ps.setObject(index + 1, UUID.fromString(value.toString()));
            } else {
                ps.setObject(index + 1, null);
            }
        } else {
            if (this.defaultJsonDbType != null) {
                PGobject obj = new PGobject();
                obj.setType(this.defaultJsonDbType);
                obj.setValue(this.JSON.tryStringify(arg));
                ps.setObject(index + 1, obj);
            } else {
                throw new SqlExecutorException("js argument " + arg + " (" + arg.getClass() + ") not support");
            }
        }
    } else {
        throw new SqlExecutorException(
                "js argument " + arg + " (" + arg.getClass() + ") at " + index + " not support");
    }
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * Creates a property assignment/*from   w  w w.  ja  v a2  s . c  o  m*/
 *
 * @param con a valid and open connection
 * @param sql an instance of StringBuilder
 * @param pa  an instance of FxPropertyAssignmentEdit to be persisted
 * @return the property assignmentId
 * @throws FxApplicationException on errors
 */
private long createPropertyAssignment(Connection con, StringBuilder sql, FxPropertyAssignmentEdit pa)
        throws FxApplicationException {
    if (!pa.isNew())
        throw new FxInvalidParameterException("ex.structure.assignment.create.existing", pa.getXPath());
    if (sql == null) {
        sql = new StringBuilder(1000);
    }
    PreparedStatement ps = null;
    long newAssignmentId;
    try {
        sql.setLength(0);
        sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS).
        //               1  2     3       4       5       6       7       8   9     10     11   12          13
                append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,APROPERTY,"
                        +
                        //14 15      16          17
                        "ACL,DEFLANG,SYSINTERNAL,DEFAULT_VALUE)" + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        ps = con.prepareStatement(sql.toString());
        newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT);
        ps.setLong(1, newAssignmentId);
        ps.setInt(2, FxAssignment.TYPE_PROPERTY);
        ps.setBoolean(3, pa.isEnabled());
        ps.setLong(4, pa.getAssignedType().getId());
        ps.setInt(5, pa.getMultiplicity().getMin());
        ps.setInt(6, pa.getMultiplicity().getMax());
        ps.setInt(7, pa.getDefaultMultiplicity());
        int position = getValidPosition(con, sql, pa.getPosition(), pa.getAssignedType().getId(),
                pa.getParentGroupAssignment());
        ps.setInt(8, position);
        String XPath;
        if (!pa.getXPath().startsWith(pa.getAssignedType().getName()))
            XPath = XPathElement.buildXPath(false, pa.getAssignedType().getName(), pa.getXPath());
        else
            XPath = pa.getXPath();
        ps.setString(9, XPath);
        ps.setString(10, pa.getAlias());
        if (pa.getBaseAssignmentId() == FxAssignment.NO_BASE)
            ps.setNull(11, Types.NUMERIC);
        else
            ps.setLong(11, pa.getBaseAssignmentId());
        ps.setLong(12, pa.getParentGroupAssignment() == null ? FxAssignment.NO_PARENT
                : pa.getParentGroupAssignment().getId());
        ps.setLong(13, pa.getProperty().getId());
        ps.setLong(14, pa.getACL().getId());
        ps.setInt(15, pa.hasDefaultLanguage() ? (int) pa.getDefaultLanguage() : (int) FxLanguage.SYSTEM_ID);
        ps.setBoolean(16, pa.isSystemInternal());
        FxValue defValue = pa.getDefaultValue();
        if (defValue instanceof FxBinary) {
            ContentStorage storage = StorageManager.getContentStorage(pa.getAssignedType().getStorageMode());
            storage.prepareBinary(con, (FxBinary) defValue);
        }
        final String _def = defValue == null || defValue.isEmpty() ? null
                : ConversionEngine.getXStream().toXML(defValue);
        if (_def == null)
            ps.setNull(17, java.sql.Types.VARCHAR);
        else
            ps.setString(17, _def);
        ps.executeUpdate();
        ps.close();
        Database.storeFxString(new FxString[] { pa.getLabel(), pa.getHint() }, con, TBL_STRUCT_ASSIGNMENTS,
                new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId);
        htracker.track(pa.getAssignedType(), "history.assignment.createPropertyAssignment", XPath,
                pa.getAssignedType().getId(), pa.getAssignedType().getName(), pa.getProperty().getId(),
                pa.getProperty().getName());

        // FxStructureOption inheritance
        boolean isInheritedAssignment = FxSharedUtils.checkAssignmentInherited(pa);
        if (isInheritedAssignment) {
            // FxStructureOptions - retrieve only those with an activated "isInherited" flag
            final List<FxStructureOption> inheritedOpts = FxStructureOption.cloneOptions(pa.getOptions(), true);
            if (inheritedOpts.size() > 0) {
                storeOptions(con, TBL_STRUCT_PROPERTY_OPTIONS, "ID", pa.getProperty().getId(), newAssignmentId,
                        inheritedOpts);
            }
        } else {
            storeOptions(con, TBL_STRUCT_PROPERTY_OPTIONS, "ID", pa.getProperty().getId(), newAssignmentId,
                    pa.getOptions());
        }

        setAssignmentPosition(con, newAssignmentId, pa.getPosition());

        if (!pa.isSystemInternal()) {
            if (divisionConfig.isFlatStorageEnabled()
                    && divisionConfig.get(SystemParameters.FLATSTORAGE_AUTO)) {
                final FxFlatStorage fs = FxFlatStorageManager.getInstance();
                if (fs.isFlattenable(pa)) {
                    try {
                        StructureLoader.reload(con);
                    } catch (FxCacheException e) {
                        EJBUtils.rollback(ctx);
                        throw new FxCreateException(e, "ex.cache", e.getMessage());
                    }
                    fs.flatten(con, fs.getDefaultStorage(),
                            (FxPropertyAssignment) CacheAdmin.getEnvironment().getAssignment(newAssignmentId));
                }
            }

            //only need a reload and inheritance handling if the property is not system internal
            //since system internal properties are only created from the type engine we don't have to care
            try {
                StructureLoader.reloadAssignments(FxContext.get().getDivisionId());
            } catch (FxApplicationException e) {
                EJBUtils.rollback(ctx);
                throw new FxCreateException(e, "ex.cache", e.getMessage());
            }
            if (pa.getAssignedType().getId() != FxType.ROOT_ID)
                createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql,
                        pa.getAssignedType().getDerivedTypes());
        }
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        if (!ctx.getRollbackOnly())
            EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.assignment.property.exists", pa.getAlias(),
                    pa.getAssignedType().getName() + pa.getXPath());
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(AssignmentEngineBean.class, null, ps);
    }
    return newAssignmentId;
}

From source file:org.apache.openaz.xacml.std.pip.engines.jdbc.ConfigurableJDBCResolver.java

@Override
public PreparedStatement getPreparedStatement(PIPEngine pipEngine, PIPRequest pipRequest, PIPFinder pipFinder,
        Connection connection) throws PIPException {
    /*//from  w ww . j  a v a2s .  c  om
     * Do we support the request?
     */
    if (!this.isSupported(pipRequest)) {
        return null;
    }

    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = connection.prepareStatement(this.sqlQuery);
    } catch (SQLException ex) {
        this.logger.error("SQLException creating PreparedStatement: " + ex.toString(), ex);
        // TODO: throw the exception or return a null PreparedStatement?
        return null;
    }

    if (this.parameters.size() > 0) {
        /*
         * Gather all of the AttributeValues for parameters to the prepared statement. For now, we assume
         * a single value for each parameter. If there are multiple values we will log an error and return
         * a null PreparedStatement. TODO: Should the interface change to return a cross-product of
         * PreparedStatements to deal with multiple values for parameters? If not, should we just take the
         * first value and use it as the parameter value?
         */
        for (int i = 0; i < this.parameters.size(); i++) {
            PIPRequest pipRequestParameter = this.parameters.get(i);
            PIPResponse pipResponse = pipFinder.getMatchingAttributes(pipRequestParameter, null);
            if (pipResponse.getStatus() == null || pipResponse.getStatus().isOk()) {
                Collection<Attribute> listAttributes = pipResponse.getAttributes();
                if (listAttributes.size() > 0) {
                    if (listAttributes.size() > 1) {
                        this.logger.error("PIPFinder returned more than one Attribute for "
                                + pipRequestParameter.toString());
                        throw new PIPException("PIPFinder returned more than one Attribute for "
                                + pipRequestParameter.toString());
                    }
                    Collection<AttributeValue<?>> listAttributeValuesReturned = listAttributes.iterator().next()
                            .getValues();
                    if (listAttributeValuesReturned.size() > 0) {
                        if (listAttributeValuesReturned.size() > 1) {
                            this.logger.warn("PIPFinder returned more than one AttributeValue for "
                                    + pipRequestParameter.toString());
                            return null;
                        }
                        AttributeValue<?> attributeValue = listAttributeValuesReturned.iterator().next();
                        Identifier identifierAttributeValueDataType = attributeValue.getDataTypeId();
                        try {
                            if (identifierAttributeValueDataType.equals(XACML3.ID_DATATYPE_INTEGER)) {
                                preparedStatement.setInt(i + 1,
                                        DataTypes.DT_INTEGER.convert(attributeValue.getValue()).intValue());
                            } else if (identifierAttributeValueDataType.equals(XACML3.ID_DATATYPE_DOUBLE)) {
                                preparedStatement.setDouble(i + 1,
                                        DataTypes.DT_DOUBLE.convert(attributeValue.getValue()));
                            } else if (identifierAttributeValueDataType.equals(XACML3.ID_DATATYPE_BOOLEAN)) {
                                preparedStatement.setBoolean(i + 1,
                                        DataTypes.DT_BOOLEAN.convert(attributeValue.getValue()));
                            } else if (identifierAttributeValueDataType.equals(XACML3.ID_DATATYPE_DATETIME)) {
                                ISO8601DateTime iso8601DateTime = DataTypes.DT_DATETIME
                                        .convert(attributeValue.getValue());
                                java.sql.Date sqlDate = new java.sql.Date(
                                        iso8601DateTime.getCalendar().getTimeInMillis());
                                preparedStatement.setDate(i + 1, sqlDate, iso8601DateTime.getCalendar());
                            } else if (identifierAttributeValueDataType.equals(XACML3.ID_DATATYPE_DATE)) {
                                ISO8601Date iso8601Date = DataTypes.DT_DATE.convert(attributeValue.getValue());
                                java.sql.Date sqlDate = new java.sql.Date(
                                        iso8601Date.getCalendar().getTimeInMillis());
                                preparedStatement.setDate(i + 1, sqlDate, iso8601Date.getCalendar());
                            } else {
                                preparedStatement.setString(i + 1,
                                        DataTypes.DT_STRING.convert(attributeValue.getValue()));
                            }
                        } catch (Exception ex) {
                            this.logger.error("Exception setting parameter " + (i + 1) + " to "
                                    + attributeValue.toString() + ": " + ex.toString(), ex);
                            return null;
                        }
                    } else {
                        this.logger.warn(
                                "No AttributeValues returned for parameter " + pipRequestParameter.toString());
                        return null;
                    }
                } else {
                    this.logger.warn("No Attributes returned for parameter " + pipRequestParameter.toString());
                    return null;
                }
            } else {
                this.logger.warn("PIPFinder returned status " + pipResponse.getStatus().toString());
                return null;
            }
        }
    }

    return preparedStatement;
}

From source file:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import flat storages to the hierarchical storage
 *
 * @param con an open and valid connection to store imported data
 * @param zip zip file containing the data
 * @throws Exception on errors/*  w  w w .  j  a v  a 2  s  .co  m*/
 */
protected void importFlatStoragesHierarchical(Connection con, ZipFile zip) throws Exception {
    //mapping: storage->level->columnname->assignment id
    final Map<String, Map<Integer, Map<String, Long>>> flatAssignmentMapping = new HashMap<String, Map<Integer, Map<String, Long>>>(
            5);
    //mapping: assignment id->position index
    final Map<Long, Integer> assignmentPositions = new HashMap<Long, Integer>(100);
    //mapping: flatstorage->column sizes [string,bigint,double,select,text]
    final Map<String, Integer[]> flatstoragesColumns = new HashMap<String, Integer[]>(5);
    ZipEntry zeMeta = getZipEntry(zip, FILE_FLATSTORAGE_META);
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(zip.getInputStream(zeMeta));
    XPath xPath = XPathFactory.newInstance().newXPath();

    //calculate column sizes
    NodeList nodes = (NodeList) xPath.evaluate("/flatstorageMeta/storageMeta", document,
            XPathConstants.NODESET);
    Node currNode;
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        int cbigInt = Integer.parseInt(currNode.getAttributes().getNamedItem("bigInt").getNodeValue());
        int cdouble = Integer.parseInt(currNode.getAttributes().getNamedItem("double").getNodeValue());
        int cselect = Integer.parseInt(currNode.getAttributes().getNamedItem("select").getNodeValue());
        int cstring = Integer.parseInt(currNode.getAttributes().getNamedItem("string").getNodeValue());
        int ctext = Integer.parseInt(currNode.getAttributes().getNamedItem("text").getNodeValue());
        String tableName = null;
        if (currNode.hasChildNodes()) {
            for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                if (currNode.getChildNodes().item(j).getNodeName().equals("name")) {
                    tableName = currNode.getChildNodes().item(j).getTextContent();
                }
        }
        if (tableName != null) {
            flatstoragesColumns.put(tableName, new Integer[] { cstring, cbigInt, cdouble, cselect, ctext });
        }
    }

    //parse mappings
    nodes = (NodeList) xPath.evaluate("/flatstorageMeta/mapping", document, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        currNode = nodes.item(i);
        long assignment = Long.valueOf(currNode.getAttributes().getNamedItem("assid").getNodeValue());
        int level = Integer.valueOf(currNode.getAttributes().getNamedItem("lvl").getNodeValue());
        String storage = null;
        String columnname = null;
        final NodeList childNodes = currNode.getChildNodes();
        for (int c = 0; c < childNodes.getLength(); c++) {
            Node child = childNodes.item(c);
            if ("tblname".equals(child.getNodeName()))
                storage = child.getTextContent();
            else if ("colname".equals(child.getNodeName()))
                columnname = child.getTextContent();
        }
        if (storage == null || columnname == null)
            throw new Exception("Invalid flatstorage export: could not read storage or column name!");
        if (!flatAssignmentMapping.containsKey(storage))
            flatAssignmentMapping.put(storage, new HashMap<Integer, Map<String, Long>>(20));
        Map<Integer, Map<String, Long>> levelMap = flatAssignmentMapping.get(storage);
        if (!levelMap.containsKey(level))
            levelMap.put(level, new HashMap<String, Long>(30));
        Map<String, Long> columnMap = levelMap.get(level);
        if (!columnMap.containsKey(columnname))
            columnMap.put(columnname, assignment);
        //calculate position
        assignmentPositions.put(assignment,
                getAssignmentPosition(flatstoragesColumns.get(storage), columnname));
    }
    if (flatAssignmentMapping.size() == 0) {
        LOG.warn("No flatstorage assignments found to process!");
        return;
    }
    ZipEntry zeData = getZipEntry(zip, FILE_DATA_FLAT);

    final String xpathStorage = "flatstorages/storage";
    final String xpathData = "flatstorages/storage/data";

    final PreparedStatement psGetAssInfo = con.prepareStatement(
            "SELECT DISTINCT a.APROPERTY,a.XALIAS,p.DATATYPE FROM " + DatabaseConst.TBL_STRUCT_ASSIGNMENTS
                    + " a, " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p WHERE a.ID=? AND p.ID=a.APROPERTY");
    final Map<Long, Object[]> assignmentPropAlias = new HashMap<Long, Object[]>(assignmentPositions.size());
    final String insert1 = "INSERT INTO " + DatabaseConst.TBL_CONTENT_DATA +
    //1  2   3   4    5     6      =1     =1    =1     =1          7         8          9
            "(ID,VER,POS,LANG,TPROP,ASSIGN,XDEPTH,XMULT,XINDEX,PARENTXMULT,ISMAX_VER,ISLIVE_VER,ISMLDEF,";
    final String insert2 = "(?,?,?,?,1,?,?,1,1,1,?,?,?,";
    final PreparedStatement psString = con
            .prepareStatement(insert1 + "FTEXT1024,UFTEXT1024,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psText = con
            .prepareStatement(insert1 + "FCLOB,UFCLOB,FSELECT,FINT)VALUES" + insert2 + "?,?,0,?)");
    final PreparedStatement psDouble = con
            .prepareStatement(insert1 + "FDOUBLE,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psNumber = con
            .prepareStatement(insert1 + "FINT,FSELECT,FBIGINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psLargeNumber = con
            .prepareStatement(insert1 + "FBIGINT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psFloat = con
            .prepareStatement(insert1 + "FFLOAT,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psBoolean = con
            .prepareStatement(insert1 + "FBOOL,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psReference = con
            .prepareStatement(insert1 + "FREF,FSELECT,FINT)VALUES" + insert2 + "?,0,?)");
    final PreparedStatement psSelectOne = con
            .prepareStatement(insert1 + "FSELECT,FINT)VALUES" + insert2 + "?,?)");
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private String currentStorage = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            int insertCount = 0;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
                currentStorage = null;
                insertCount = 0;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                LOG.info("Imported [" + insertCount + "] flatstorage entries into the hierarchical storage");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpathData)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else if (currPath.toString().equals(xpathStorage)) {
                    currentStorage = attributes.getValue("name");
                    LOG.info("Processing storage: " + currentStorage);
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            @SuppressWarnings({ "UnusedDeclaration" })
            private void pushPath(String qName, Attributes att) {
                path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpathData)) {
                    //                        LOG.info("Insert [" + xpathData + "]: [" + data + "]");
                    inTag = false;
                    processData();
                    /*try {
                    if (insertMode) {
                        if (executeInsertPhase) {
                            processColumnSet(insertColumns, psInsert);
                            counter += psInsert.executeUpdate();
                        }
                    } else {
                        if (executeUpdatePhase) {
                            if (processColumnSet(updateSetColumns, psUpdate)) {
                                processColumnSet(updateClauseColumns, psUpdate);
                                counter += psUpdate.executeUpdate();
                            }
                        }
                    }
                    } catch (SQLException e) {
                    throw new SAXException(e);
                    } catch (ParseException e) {
                    throw new SAXException(e);
                    }*/
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            void processData() {
                //                    System.out.println("processing " + currentStorage + " -> " + data);
                final String[] cols = { "string", "bigint", "double", "select", "text" };
                for (String column : data.keySet()) {
                    if (column.endsWith("_mld"))
                        continue;
                    for (String check : cols) {
                        if (column.startsWith(check)) {
                            if ("select".equals(check) && "0".equals(data.get(column)))
                                continue; //dont insert 0-referencing selects
                            try {
                                insertData(column);
                            } catch (SQLException e) {
                                //noinspection ThrowableInstanceNeverThrown
                                throw new FxDbException(e, "ex.db.sqlError", e.getMessage())
                                        .asRuntimeException();
                            }
                        }
                    }
                }
            }

            private void insertData(String column) throws SQLException {
                final int level = Integer.parseInt(data.get("lvl"));
                long assignment = flatAssignmentMapping.get(currentStorage).get(level)
                        .get(column.toUpperCase());
                int pos = FxArrayUtils.getIntElementAt(data.get("positions"), ',',
                        assignmentPositions.get(assignment));
                String _valueData = data.get("valuedata");
                Integer valueData = _valueData == null ? null
                        : FxArrayUtils.getHexIntElementAt(data.get("valuedata"), ',',
                                assignmentPositions.get(assignment));
                Object[] propXP = getPropertyXPathDataType(assignment);
                long prop = (Long) propXP[0];
                String xpath = (String) propXP[1];
                FxDataType dataType;
                try {
                    dataType = FxDataType.getById((Long) propXP[2]);
                } catch (FxNotFoundException e) {
                    throw e.asRuntimeException();
                }
                long id = Long.parseLong(data.get("id"));
                int ver = Integer.parseInt(data.get("ver"));
                long lang = Integer.parseInt(data.get("lang"));
                boolean isMaxVer = "1".equals(data.get("ismax_ver"));
                boolean isLiveVer = "1".equals(data.get("islive_ver"));
                boolean mlDef = "1".equals(data.get(column + "_mld"));
                PreparedStatement ps;
                int vdPos;
                switch (dataType) {
                case String1024:
                    ps = psString;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Text:
                case HTML:
                    ps = psText;
                    ps.setString(10, data.get(column));
                    ps.setString(11, data.get(column).toUpperCase());
                    vdPos = 12;
                    break;
                case Number:
                    ps = psNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case LargeNumber:
                    ps = psLargeNumber;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Reference:
                    ps = psReference;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Float:
                    ps = psFloat;
                    ps.setFloat(10, Float.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Double:
                    ps = psDouble;
                    ps.setDouble(10, Double.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                case Boolean:
                    ps = psBoolean;
                    ps.setBoolean(10, "1".equals(data.get(column)));
                    vdPos = 11;
                    break;
                case SelectOne:
                    ps = psSelectOne;
                    ps.setLong(10, Long.valueOf(data.get(column)));
                    vdPos = 11;
                    break;
                default:
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxInvalidParameterException("assignment",
                            "ex.structure.flatstorage.datatype.unsupported", dataType.name())
                                    .asRuntimeException();
                }
                ps.setLong(1, id);
                ps.setInt(2, ver);
                ps.setInt(3, pos);
                ps.setLong(4, lang);
                ps.setLong(5, prop);
                ps.setLong(6, assignment);
                ps.setBoolean(7, isMaxVer);
                ps.setBoolean(8, isLiveVer);
                ps.setBoolean(9, mlDef);
                if (valueData == null)
                    ps.setNull(vdPos, java.sql.Types.NUMERIC);
                else
                    ps.setInt(vdPos, valueData);
                ps.executeUpdate();
                insertCount++;
            }

            /**
             * Get property id, xpath and data type for an assignment
             *
             * @param assignment assignment id
             * @return Object[] {propertyId, xpath, datatype}
             */
            private Object[] getPropertyXPathDataType(long assignment) {
                if (assignmentPropAlias.get(assignment) != null)
                    return assignmentPropAlias.get(assignment);
                try {
                    psGetAssInfo.setLong(1, assignment);
                    ResultSet rs = psGetAssInfo.executeQuery();
                    if (rs != null && rs.next()) {
                        Object[] data = new Object[] { rs.getLong(1), rs.getString(2), rs.getLong(3) };
                        assignmentPropAlias.put(assignment, data);
                        return data;
                    }
                } catch (SQLException e) {
                    throw new IllegalArgumentException(
                            "Could not load data for assignment " + assignment + ": " + e.getMessage());
                }
                throw new IllegalArgumentException("Could not load data for assignment " + assignment + "!");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        parser.parse(zip.getInputStream(zeData), handler);
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psGetAssInfo, psString, psBoolean, psDouble,
                psFloat, psLargeNumber, psNumber, psReference, psSelectOne, psText);
    }
}

From source file:com.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * @param con      an existing connection
 * @param original the original property assignment to compare changes
 *                 against and update. if==null, the original will be fetched from the cache
 * @param modified the modified property assignment   @return if any changes were found
 * @return true if the original assignment was modified
 * @throws FxApplicationException on errors
 *///from   w  ww .  j  av  a2s. c  o  m
private boolean updatePropertyAssignment(Connection con, FxPropertyAssignment original,
        FxPropertyAssignmentEdit modified) throws FxApplicationException {
    if (modified.isNew())
        throw new FxInvalidParameterException("ex.structure.assignment.update.new", modified.getXPath());
    final StringBuilder sql = new StringBuilder(1000);
    boolean changes = false;
    boolean success = false;
    StringBuilder changesDesc = new StringBuilder(200);
    if (original == null)
        original = (FxPropertyAssignment) CacheAdmin.getEnvironment().getAssignment(modified.getId());
    PreparedStatement ps = null;
    try {
        if (con == null)
            con = Database.getDbConnection();
        sql.setLength(0);

        if (!original.isSystemInternal() || FxContext.getUserTicket().isGlobalSupervisor()) {
            // enable or disable a property assignment, remove the assignment if set to false
            if (original.isEnabled() != modified.isEnabled()) {
                if (!modified.isEnabled())
                    removeAssignment(original.getId(), true, false, true, false);
                else {
                    ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET ENABLED=? WHERE ID=?");
                    ps.setBoolean(1, modified.isEnabled());
                    ps.setLong(2, original.getId());
                    ps.executeUpdate();
                    ps.close();
                }
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("enabled=").append(modified.isEnabled());
                changes = true;
            }
            // change the property assignment's default multiplicity
            if (original.getDefaultMultiplicity() != modified.getDefaultMultiplicity()) {
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET DEFMULT=? WHERE ID=?");
                ps.setInt(1, modified.getDefaultMultiplicity());
                ps.setLong(2, original.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("defaultMultiplicity=").append(modified.getDefaultMultiplicity());
                changes = true;
            }
            boolean needMin = original.getMultiplicity().getMin() != modified.getMultiplicity().getMin();
            boolean needMax = original.getMultiplicity().getMax() != modified.getMultiplicity().getMax();
            // change the property assignment's multiplicity
            if (needMin || needMax) {
                if (original.getProperty().mayOverrideBaseMultiplicity()) {
                    //only check if instances exist
                    if (EJBLookup.getTypeEngine().getInstanceCount(original.getAssignedType().getId()) > 0) {
                        if (needMin)
                            checkChangePropertyAssignmentMinMultiplicity(con, original,
                                    modified.getMultiplicity());
                        if (needMax && getPropertyInstanceMultiplicity(con, original.getProperty().getId(),
                                false) > modified.getMultiplicity().getMax())
                            throw new FxUpdateException("ex.structure.modification.contentExists",
                                    "maximumMultiplicity");
                    }
                } else {
                    throw new FxUpdateException(
                            "ex.structure.property.assignment.overrideBaseMultiplicityNotEnabled",
                            original.getProperty().getId());
                }
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET MINMULT=? ,MAXMULT=? WHERE ID=?");
                ps.setInt(1, modified.getMultiplicity().getMin());
                ps.setInt(2, modified.getMultiplicity().getMax());
                ps.setLong(3, original.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("multiplicity=").append(modified.getMultiplicity());
                changes = true;
            }
            // set the assignment's position
            if (original.getPosition() != modified.getPosition()) {
                int finalPos = setAssignmentPosition(con, modified.getId(), modified.getPosition());
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("position=").append(finalPos);
                changes = true;
            }
            // alias / xpath change
            if (!original.getXPath().equals(modified.getXPath())
                    || !original.getAlias().equals(modified.getAlias())) {
                if (!XPathElement.isValidXPath(XPathElement.stripType(modified.getXPath()))
                        || modified.getAlias().equals(XPathElement
                                .lastElement(XPathElement.stripType(original.getXPath())).getAlias()))
                    throw new FxUpdateException("ex.structure.assignment.noXPath");
                // generate correct XPATH
                if (!modified.getXPath().startsWith(modified.getAssignedType().getName()))
                    modified.setXPath(modified.getAssignedType().getName() + modified.getXPath());
                //avoid duplicates
                if (original.getAssignedType().isXPathValid(modified.getXPath(), true))
                    throw new FxUpdateException("ex.structure.assignment.exists", modified.getXPath(),
                            modified.getAssignedType().getName());
                // update db entries
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET XPATH=?, XALIAS=? WHERE ID=?");
                ps.setString(1, modified.getXPath());
                ps.setString(2, modified.getAlias());
                ps.setLong(3, modified.getId());
                ps.executeUpdate();
                ps.close();
                // update the relevant content instances
                ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical);
                storage.updateXPath(con, modified.getId(), XPathElement.stripType(original.getXPath()),
                        XPathElement.stripType(modified.getXPath()));

                if (changes)
                    changesDesc.append(',');
                changesDesc.append("xPath=").append(modified.getXPath()).append(",alias=")
                        .append(modified.getAlias());
                changes = true;
            }
            // change the assignment's ACL
            if (original.getACL().getId() != modified.getACL().getId()) {
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET ACL=? WHERE ID=?");
                ps.setLong(1, modified.getACL().getId());
                ps.setLong(2, original.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("acl=").append(modified.getACL().getId());
                changes = true;
            }
            // options are stored via storeOption method
            if (original.isMultiLang() != modified.isMultiLang()) {
                //Multi->Single: lang=system, values of the def. lang. are used, other are discarded
                //Single->Multi: lang=default language
                if (!original.getProperty().mayOverrideMultiLang())
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxUpdateException("ex.structure.assignment.overrideNotAllowed.multiLang",
                            original.getXPath(), original.getProperty().getName()).setAffectedXPath(
                                    original.getXPath(), FxContentExceptionCause.MultiLangOverride);
                if (modified.isFlatStorageEntry() && getAssignmentInstanceCount(modified.getId()) > 0)
                    //noinspection ThrowableInstanceNeverThrown
                    throw new FxUpdateException("ex.structure.assignment.overrideNotSupported.multiLang",
                            original.getXPath(), original.getProperty().getName()).setAffectedXPath(
                                    original.getXPath(), FxContentExceptionCause.MultiLangOverride);
                StorageManager.getContentStorage(TypeStorageMode.Hierarchical).updateMultilanguageSettings(con,
                        original.getId(), original.isMultiLang(), modified.isMultiLang(),
                        modified.getDefaultLanguage());
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("multiLang=").append(modified.isMultiLang());
                changes = true;
            }
            // change the assignment's label
            if (original.getLabel() != null && !original.getLabel().equals(modified.getLabel())
                    || original.getLabel() == null && modified.getLabel() != null
                    || original.getHint() != null && !original.getHint().equals(modified.getHint())
                    || original.getHint() == null && modified.getHint() != null) {
                Database.storeFxString(new FxString[] { modified.getLabel(), modified.getHint() }, con,
                        TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", original.getId());
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("label=").append(modified.getLabel()).append(',');
                changesDesc.append("hint=").append(modified.getHint()).append(',');
                changes = true;
            }
            // change the assigment's default value
            if (original.getDefaultValue() != null
                    && !original.getDefaultValue().equals(modified.getDefaultValue())
                    || original.getDefaultValue() == null && modified.getDefaultValue() != null
                    || original.hasAssignmentDefaultValue() != modified.hasAssignmentDefaultValue()) {
                if (changes)
                    changesDesc.append(',');
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET DEFAULT_VALUE=? WHERE ID=?");
                FxValue defValue = modified.getDefaultValue();
                if (defValue instanceof FxBinary && modified.hasAssignmentDefaultValue()) {
                    ContentStorage storage = StorageManager
                            .getContentStorage(modified.getAssignedType().getStorageMode());
                    storage.prepareBinary(con, (FxBinary) defValue);
                }
                final String _def = defValue == null || defValue.isEmpty() ? null
                        : ConversionEngine.getXStream().toXML(defValue);
                if (_def != null && modified.hasAssignmentDefaultValue()
                        && (modified.getDefaultValue() instanceof FxReference)) {
                    //check if the type matches the instance
                    checkReferencedType(con, (FxReference) modified.getDefaultValue(),
                            modified.getProperty().getReferencedType());
                }
                if (_def == null || !modified.hasAssignmentDefaultValue())
                    ps.setNull(1, java.sql.Types.VARCHAR);
                else
                    ps.setString(1, _def);
                ps.setLong(2, original.getId());
                ps.executeUpdate();
                ps.close();
                changesDesc.append("defaultValue=").append(original.getDefaultValue());
                changes = true;
            }
            // change the default language
            if (original.getDefaultLanguage() != modified.getDefaultLanguage()) {
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET DEFLANG=? WHERE ID=?");
                ps.setInt(1, (int) modified.getDefaultLanguage());
                ps.setLong(2, original.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("defaultLanguage=").append(modified.getDefaultLanguage());
                changes = true;
            }
            //update SystemInternal flag, this is a one way function, so it can only be set, but not reset!!
            if (!original.isSystemInternal() && modified.isSystemInternal()) {
                if (FxContext.getUserTicket().isGlobalSupervisor()) {
                    ps = con.prepareStatement(
                            "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET SYSINTERNAL=? WHERE ID=?");
                    ps.setBoolean(1, modified.isSystemInternal());
                    ps.setLong(2, original.getId());
                    ps.executeUpdate();
                    ps.close();
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("systemInternal=").append(modified.isSystemInternal());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.systemInternal.notGlobalSupervisor",
                            modified.getLabel());
            }
            // change the parentgroupassignment
            //                if (original.getParentGroupAssignment().getId() != modified.getParentGroupAssignment().getId()) {
            //                }
            /*
            if (changes) {
            //propagate changes to derived assignments
            List<FxAssignment> children = CacheAdmin.getEnvironment().getDerivedAssignments(modified.getId());
            for (FxAssignment as : children) {
                if (as instanceof FxPropertyAssignment) {
                    updatePropertyAssignment(null, null, null, (FxPropertyAssignment) as, modified);
                }
            }
            //if there are changes AND the assignment is a child,
            // break the inheritance and make it a "ROOT_BASE" assignment
            if(original.isDerivedAssignment()) {
                if (ps!=null)
                    ps.close();
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET BASE=? WHERE ID=?");
                ps.setNull(1, Types.NUMERIC);
                ps.setLong(2, original.getId());
                ps.executeUpdate();
                   changesDesc.append(",baseAssignment=null");
            }
            }
            */
        } else
            throw new FxUpdateException("ex.structure.systemInternal.forbidden", modified.getLabel());

        if (updatePropertyAssignmentOptions(con, original, modified)) {
            changesDesc.append(",options:");
            List<FxStructureOption> options = modified.getOptions();
            for (FxStructureOption option : options) {
                changesDesc.append(option.getKey()).append("=").append(option.getValue())
                        .append(" overridable=").append(option.isOverridable()).append(" isSet=")
                        .append(option.isSet()).append("isInherited").append(option.getIsInherited());
            }
            changes = true;
        }

        //TODO: compare all possible modifications
        if (changes) {
            htracker.track(modified.getAssignedType(), "history.assignment.updatePropertyAssignment",
                    original.getXPath(), modified.getAssignedType().getId(),
                    modified.getAssignedType().getName(), modified.getProperty().getId(),
                    modified.getProperty().getName(), changesDesc.toString());
        }
        success = true;
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.assignment.property.exists", original.getAlias(),
                    original.getXPath());
        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}//www . j  a  v  a2  s .c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public List<FxPhraseTreeNodePosition> getAssignedNodes(long phraseId, long phraseMandator, 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,m.CAT FROM " + TBL_PHRASE_MAP
                + " m WHERE m.PHRASEID=? AND m.PMANDATOR=? AND m.DIRECT=? AND m.MANDATOR" + mandatorQuery
                + " ORDER BY m.NODEMANDATOR,m.NODEID,m.POS");
        ps.setLong(1, phraseId);
        ps.setLong(2, phraseMandator);
        ps.setBoolean(3, true);
        ResultSet rs = ps.executeQuery();
        while (rs != null && rs.next()) {
            try {
                result.add(new FxPhraseTreeNodePosition(loadPhraseTreeNode(con, false, rs.getInt(4),
                        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:org.obm.domain.dao.CalendarDaoJdbcImpl.java

@VisibleForTesting
void insertAttendees(AccessToken editor, Event ev, Connection con, List<Attendee> attendees)
        throws SQLException {
    String attQ = "INSERT INTO EventLink (" + ATT_INSERT_FIELDS + ") VALUES (" + "?, " + // event_id
            "?, " + // entity_id
            "?, " + // state
            "?, " + // required
            "?," + // percent
            "?," + // user_create
            "?" + // is_organizer
            ")";/*  w ww.ja v a2 s . com*/
    boolean shouldClearOrganizer = false;
    PreparedStatement ps = null;

    try {
        ps = con.prepareStatement(attQ);

        final int eventObmId = ev.getObmId().getObmId();
        final Set<Attendee> listAttendee = removeDuplicateAttendee(attendees);
        Set<EntityId> alreadyAddedAttendees = Sets.newHashSet();

        for (final Attendee at : listAttendee) {
            boolean isOrganizer = Objects.firstNonNull(at.isOrganizer(), false);

            String attendeeEmail = at.getEmail();
            EntityId userEntity = at.getEntityId();

            // There must be only one organizer in a given event
            if (isOrganizer) {
                shouldClearOrganizer = true;
            }

            if (alreadyAddedAttendees.contains(userEntity)) {
                logger.info("Attendee {} with entity ID {} already added, skipping.", attendeeEmail,
                        userEntity);

                continue;
            }

            ps.setInt(1, eventObmId);
            ps.setInt(2, userEntity.getId());
            ps.setObject(3, getJdbcObjectParticipation(at));
            ps.setObject(4, getJdbcObjectParticipationRole(at));
            ps.setInt(5, at.getPercent());
            ps.setInt(6, editor.getObmId());
            ps.setBoolean(7, isOrganizer);
            ps.addBatch();
            logger.info("Adding " + attendeeEmail + (isOrganizer ? " as organizer" : " as attendee"));

            alreadyAddedAttendees.add(userEntity);
        }

        // Clear the previous organizer if needed
        if (shouldClearOrganizer) {
            clearOrganizer(eventObmId, con);
        }

        ps.executeBatch();
    } finally {
        obmHelper.cleanup(null, ps, null);
    }
}

From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java

@VisibleForTesting
void insertAttendees(AccessToken editor, Event ev, Connection con, List<Attendee> attendees)
        throws SQLException {
    String attQ = "INSERT INTO EventLink (" + ATT_INSERT_FIELDS + ") VALUES (" + "?, " + // event_id
            "?, " + // entity_id
            "?, " + // state
            "?, " + // required
            "?," + // percent
            "?," + // user_create
            "?" + // is_organizer
            ")";//w  w  w.  j av a2  s. c  om
    boolean shouldClearOrganizer = false;
    PreparedStatement ps = null;

    try {
        ps = con.prepareStatement(attQ);

        final int eventObmId = ev.getObmId().getObmId();
        final Set<Attendee> listAttendee = removeDuplicateAttendee(attendees);
        Set<EntityId> alreadyAddedAttendees = Sets.newHashSet();

        for (final Attendee at : listAttendee) {
            boolean isOrganizer = Objects.firstNonNull(at.isOrganizer(), false);

            String attendeeEmail = at.getEmail();
            EntityId userEntity = at.getEntityId();

            // There must be only one organizer in a given event
            if (isOrganizer) {
                shouldClearOrganizer = true;
            }

            if (alreadyAddedAttendees.contains(userEntity)) {
                logger.info("Attendee {} with entity ID {} already added, skipping.", attendeeEmail,
                        userEntity);

                continue;
            }

            ps.setInt(1, eventObmId);
            ps.setInt(2, userEntity.getId());
            ps.setObject(3, getJdbcObjectParticipation(at));
            ps.setObject(4, getJdbcObjectParticipationRole(at));
            ps.setInt(5, at.getPercent());
            ps.setInt(6, editor.getObmId());
            ps.setBoolean(7, isOrganizer);
            ps.addBatch();
            logger.info(LogUtils.prefix(editor) + "Adding " + attendeeEmail
                    + (isOrganizer ? " as organizer" : " as attendee"));

            alreadyAddedAttendees.add(userEntity);
        }

        // Clear the previous organizer if needed
        if (shouldClearOrganizer) {
            clearOrganizer(eventObmId, con);
        }

        ps.executeBatch();
    } finally {
        obmHelper.cleanup(null, ps, null);
    }
}