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.lockss.subscription.SubscriptionManager.java

/**
 * Adds a subscription range to the database.
 * //from  www.  ja  va 2  s.c  o m
 * @param conn
 *          A Connection with the database connection to be used.
 * @param subscriptionSeq
 *          A Long with the identifier of the subscription.
 * @param range
 *          A BibliographicPeriod with the subscription range.
 * @param subscribed
 *          A boolean with the indication of whether the LOCKSS installation
 *          is subscribed to the publication range or not.
 * @throws DbException
 *           if any problem occurred accessing the database.
 */
private int persistSubscriptionRange(Connection conn, Long subscriptionSeq, BibliographicPeriod range,
        boolean subscribed) throws DbException {
    final String DEBUG_HEADER = "persistSubscriptionRange(): ";
    if (log.isDebug2()) {
        log.debug2(DEBUG_HEADER + "subscriptionSeq = " + subscriptionSeq);
        log.debug2(DEBUG_HEADER + "range = " + range);
        log.debug2(DEBUG_HEADER + "subscribed = " + subscribed);
    }

    int count = 0;

    // Skip an empty range that does not accomplish anything.
    if (range.isEmpty()) {
        if (log.isDebug2())
            log.debug2(DEBUG_HEADER + "count = " + count);
        return count;
    }

    String sql = getInsertSubscriptionRangeSql();
    PreparedStatement insertSubscriptionRange = dbManager.prepareStatement(conn, sql);

    try {
        insertSubscriptionRange.setLong(1, subscriptionSeq);
        insertSubscriptionRange.setString(2, range.toDisplayableString());
        insertSubscriptionRange.setBoolean(3, subscribed);
        insertSubscriptionRange.setLong(4, subscriptionSeq);
        insertSubscriptionRange.setBoolean(5, subscribed);

        count = dbManager.executeUpdate(insertSubscriptionRange);
        if (log.isDebug3())
            log.debug3(DEBUG_HEADER + "count = " + count);
    } catch (SQLException sqle) {
        log.error("Cannot insert subscription range", sqle);
        log.error("SQL = '" + sql + "'.");
        log.error("subscriptionSeq = " + subscriptionSeq);
        log.error("range = " + range);
        log.error("subscribed = " + subscribed);
        throw new DbException("Cannot insert subscription range", sqle);
    } finally {
        DbManager.safeCloseStatement(insertSubscriptionRange);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "count = " + count);
    return count;
}

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

/**
 * Updates a property/*from   ww  w  .j  a  v a  2  s.  c  o  m*/
 *
 * @param con  a valid and open connection
 * @param prop the instance of FxPropertyEdit to be changed
 * @return returns true if changes were made to the property
 * @throws FxApplicationException on errors
 */
private boolean updateProperty(Connection con, FxPropertyEdit prop) throws FxApplicationException {
    if (prop.isNew())
        throw new FxInvalidParameterException("ex.structure.property.update.new", prop.getName());
    boolean changes = false;
    boolean success = false;
    StringBuilder changesDesc = new StringBuilder(200);
    final FxEnvironment env = CacheAdmin.getEnvironment();
    FxProperty org = env.getProperty(prop.getId());
    PreparedStatement ps = null;

    try {
        if (!org.isSystemInternal() || FxContext.getUserTicket().isGlobalSupervisor()) {
            // change the multiplicity override prop
            if (org.mayOverrideBaseMultiplicity() != prop.mayOverrideBaseMultiplicity()) {
                if (!prop.mayOverrideBaseMultiplicity() && getPropertyInstanceCount(prop.getId()) > 0) {
                    final long minMult = getPropertyInstanceMultiplicity(con, org.getId(), true);
                    if (minMult > 0 && minMult < prop.getMultiplicity().getMin())
                        throw new FxUpdateException("ex.structure.modification.contentExists",
                                "minimumMultiplicity");
                    if (getPropertyInstanceMultiplicity(con, org.getId(), false) > prop.getMultiplicity()
                            .getMax())
                        throw new FxUpdateException("ex.structure.modification.contentExists",
                                "maximumMultiplicity");
                }
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_PROPERTIES + " SET MAYOVERRIDEMULT=? WHERE ID=?");
                ps.setBoolean(1, prop.mayOverrideBaseMultiplicity());
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("mayOverrideMultiplicity=").append(prop.mayOverrideBaseMultiplicity());
                changes = true;
            }
            // change the props multiplicity
            if (org.getMultiplicity().getMin() != prop.getMultiplicity().getMin()
                    || org.getMultiplicity().getMax() != prop.getMultiplicity().getMax()) {
                if (!prop.mayOverrideBaseMultiplicity()) {
                    if (org.getMultiplicity().getMin() < prop.getMultiplicity().getMin()) {
                        for (FxPropertyAssignment pa : CacheAdmin.getEnvironment()
                                .getPropertyAssignments(prop.getId(), true))
                            checkChangePropertyAssignmentMinMultiplicity(con, pa, prop.getMultiplicity());
                    }
                    if (org.getMultiplicity().getMax() > prop.getMultiplicity().getMax()) {
                        if (getPropertyInstanceMultiplicity(con, org.getId(), false) > prop.getMultiplicity()
                                .getMax())
                            throw new FxUpdateException("ex.structure.modification.contentExists",
                                    "maximumMultiplicity");
                    }
                }
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_PROPERTIES + " SET DEFMINMULT=? ,DEFMAXMULT=? WHERE ID=?");
                ps.setInt(1, prop.getMultiplicity().getMin());
                ps.setInt(2, prop.getMultiplicity().getMax());
                ps.setLong(3, prop.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("multiplicity=").append(prop.getMultiplicity());
                changes = true;
            }
            //not supported yet
            if (!org.getName().equals(prop.getName())) {
                throw new FxUpdateException("ex.structure.modification.notSupported", "name");
                /*
                if (ps != null) ps.close();
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_PROPERTIES + " SET NAME=? WHERE ID=?");
                ps.setString(1, prop.getName());
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                if (changes)
                changesDesc.append(',');
                changesDesc.append("name=").append(prop.getName());
                changes = true;
                */
            }
            //may only change if there are no existing content instances that use this property already
            if (org.getDataType().getId() != prop.getDataType().getId()) {
                if (getPropertyInstanceCount(org.getId()) == 0) {
                    ps = con.prepareStatement("UPDATE " + TBL_STRUCT_PROPERTIES + " SET DATATYPE=? WHERE ID=?");
                    ps.setLong(1, prop.getDataType().getId());
                    ps.setLong(2, prop.getId());
                    ps.executeUpdate();
                    ps.close();
                    //FX-858: get all assignments for this property and re-flatten if possible to reflect data type changes
                    final List<FxPropertyAssignment> refAssignments = env
                            .getReferencingPropertyAssignments(prop.getId());
                    final FxFlatStorage fs = FxFlatStorageManager.getInstance();
                    List<FxPropertyAssignment> flattened = new ArrayList<FxPropertyAssignment>(
                            refAssignments.size());
                    for (FxPropertyAssignment refAssignment : refAssignments) {
                        if (refAssignment.isFlatStorageEntry()) {
                            fs.unflatten(con, refAssignment);
                            flattened.add(refAssignment);
                        }
                    }
                    if (flattened.size() > 0) {
                        try {
                            StructureLoader.reload(con);
                            final FxEnvironment envNew = CacheAdmin.getEnvironment();
                            boolean needReload = false;
                            for (FxPropertyAssignment ref : flattened) {
                                final FxPropertyAssignment paNew = (FxPropertyAssignment) envNew
                                        .getAssignment(ref.getId());
                                if (fs.isFlattenable(paNew)) {
                                    fs.flatten(con, fs.getDefaultStorage(), paNew);
                                    needReload = true;
                                }
                            }
                            if (needReload)
                                StructureLoader.reload(con);
                        } catch (FxCacheException e) {
                            EJBUtils.rollback(ctx);
                            throw new FxCreateException(e, "ex.cache", e.getMessage());
                        }
                    }
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("dataType=").append(prop.getDataType().getName());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.contentExists", "dataType");
            }
            //may only change if there are no existing content instances that use this property already
            if (org.getReferencedType() != null && prop.getReferencedType() != null
                    && org.getReferencedType().getId() != prop.getReferencedType().getId()
                    || org.hasReferencedType() != prop.hasReferencedType()) {
                if (getPropertyInstanceCount(org.getId()) == 0) {
                    if (prop.isDefaultValueSet() && (prop.getDefaultValue() instanceof FxReference)) {
                        //check if the type matches the instance
                        checkReferencedType(con, (FxReference) prop.getDefaultValue(),
                                prop.getReferencedType());
                        //check for referencing assignments
                        final List<FxPropertyAssignment> refAssignments = env
                                .getReferencingPropertyAssignments(prop.getId());
                        for (FxPropertyAssignment refAssignment : refAssignments) {
                            if (refAssignment.hasAssignmentDefaultValue()
                                    && refAssignment.getDefaultValue() instanceof FxReference)
                                checkReferencedType(con, (FxReference) refAssignment.getDefaultValue(),
                                        prop.getReferencedType());
                        }
                    }
                    ps = con.prepareStatement("UPDATE " + TBL_STRUCT_PROPERTIES + " SET REFTYPE=? WHERE ID=?");
                    ps.setLong(2, prop.getId());
                    if (prop.hasReferencedType()) {
                        ps.setLong(1, prop.getReferencedType().getId());
                    } else
                        ps.setNull(1, java.sql.Types.NUMERIC);
                    ps.executeUpdate();
                    ps.close();
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("referencedType=").append(prop.getReferencedType());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.contentExists", "referencedType");
            }
            // set fulltext indexing for the property
            if (org.isFulltextIndexed() != prop.isFulltextIndexed()) {
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_PROPERTIES + " SET ISFULLTEXTINDEXED=? WHERE ID=?");
                ps.setBoolean(1, prop.isFulltextIndexed());
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("isFulltextIndexed=").append(prop.isFulltextIndexed());
                FulltextIndexer ft = StorageManager.getFulltextIndexer(con);
                if (prop.isFulltextIndexed())
                    ft.rebuildIndexForProperty(prop.getId());
                else
                    ft.removeIndexForProperty(prop.getId());
                changes = true;
            }
            // set ACL override flag
            if (org.mayOverrideACL() != prop.mayOverrideACL()) {
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_PROPERTIES + " SET MAYOVERRIDEACL=? WHERE ID=?");
                ps.setBoolean(1, prop.mayOverrideACL());
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("mayOverrideACL=").append(prop.mayOverrideACL());
                changes = true;
            }
            //may only change if there are no existing content instances that use this property already
            if (org.getReferencedList() != null && prop.getReferencedList() != null
                    && org.getReferencedList().getId() != prop.getReferencedList().getId()
                    || org.hasReferencedList() != prop.hasReferencedList()) {
                if (getPropertyInstanceCount(org.getId()) == 0) {
                    ps = con.prepareStatement("UPDATE " + TBL_STRUCT_PROPERTIES + " SET REFLIST=? WHERE ID=?");
                    ps.setLong(2, prop.getId());
                    if (prop.hasReferencedList()) {
                        ps.setLong(1, prop.getReferencedList().getId());
                    } else
                        ps.setNull(1, java.sql.Types.NUMERIC);
                    ps.executeUpdate();
                    ps.close();
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("referencedList=").append(prop.getReferencedList());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.contentExists", "referencedList");
            }
            // set the unique mode
            if (org.getUniqueMode() != prop.getUniqueMode()) {
                boolean allowChange = getPropertyInstanceCount(org.getId()) == 0
                        || prop.getUniqueMode().equals(UniqueMode.None);
                if (!allowChange) {
                    boolean hasFlat = false;
                    for (FxPropertyAssignment pa : env.getPropertyAssignments(prop.getId(), true)) {
                        if (pa.isFlatStorageEntry()) {
                            hasFlat = true;
                            break;
                        }
                    }
                    if (!hasFlat) {
                        boolean check = true;
                        for (FxType type : env.getTypesForProperty(prop.getId())) {
                            check = StorageManager.getContentStorage(TypeStorageMode.Hierarchical)
                                    .uniqueConditionValid(con, prop.getUniqueMode(), prop, type.getId(), null);
                            if (!check)
                                break;
                        }
                        allowChange = check;
                    }
                }
                if (allowChange) {
                    ps = con.prepareStatement(
                            "UPDATE " + TBL_STRUCT_PROPERTIES + " SET UNIQUEMODE=? WHERE ID=?");
                    ps.setLong(1, prop.getUniqueMode().getId());
                    ps.setLong(2, prop.getId());
                    ps.executeUpdate();
                    ps.close();
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("uniqueMode=").append(prop.getUniqueMode().getId());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.contentExists", "uniqueMode");
            }
            // change the property's ACL
            if (org.getACL().getId() != prop.getACL().getId()) {
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_PROPERTIES + " SET ACL=? WHERE ID=?");
                ps.setLong(1, prop.getACL().getId());
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                ps.close();
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("acl=").append(prop.getACL().getId());
                changes = true;
            }
            // change the prop's label
            if (org.getLabel() != null && !org.getLabel().equals(prop.getLabel())
                    || org.getLabel() == null && prop.getLabel() != null
                    || org.getHint() != null && !org.getHint().equals(prop.getHint())
                    || org.getHint() == null && prop.getHint() != null) {
                Database.storeFxString(new FxString[] { prop.getLabel(), prop.getHint() }, con,
                        TBL_STRUCT_PROPERTIES, new String[] { "DESCRIPTION", "HINT" }, "ID", prop.getId());
                if (changes)
                    changesDesc.append(',');
                changesDesc.append("label=").append(prop.getLabel()).append(',');
                changesDesc.append("hint=").append(prop.getHint()).append(',');
                changes = true;
            }
            // change the default value
            if (org.getDefaultValue() != null && !org.getDefaultValue().equals(prop.getDefaultValue())
                    || org.getDefaultValue() == null && prop.getDefaultValue() != null) {
                if (changes)
                    changesDesc.append(',');
                ps = con.prepareStatement(
                        "UPDATE " + TBL_STRUCT_PROPERTIES + " SET DEFAULT_VALUE=? WHERE ID=?");
                FxValue defValue = prop.getDefaultValue();
                if (defValue instanceof FxBinary) {
                    ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical);
                    storage.prepareBinary(con, (FxBinary) defValue);
                }
                if (prop.isDefaultValueSet() && (defValue instanceof FxReference)) {
                    //check if the type matches the instance
                    checkReferencedType(con, (FxReference) defValue, prop.getReferencedType());
                    //check for referencing assignments
                    final List<FxPropertyAssignment> refAssignments = env
                            .getReferencingPropertyAssignments(prop.getId());
                    for (FxPropertyAssignment refAssignment : refAssignments) {
                        if (refAssignment.hasAssignmentDefaultValue()
                                && refAssignment.getDefaultValue() instanceof FxReference)
                            checkReferencedType(con, (FxReference) refAssignment.getDefaultValue(),
                                    prop.getReferencedType());
                    }
                }
                final String _def = defValue == null || defValue.isEmpty() ? null
                        : ConversionEngine.getXStream().toXML(defValue);
                if (_def == null)
                    ps.setNull(1, java.sql.Types.VARCHAR);
                else
                    ps.setString(1, _def);
                ps.setLong(2, prop.getId());
                ps.executeUpdate();
                ps.close();
                changesDesc.append("defaultValue=").append(prop.getDefaultValue());
                changes = true;
            }
            //update SystemInternal flag, this is a one way function, so it can only be set, but not reset!!
            if (!org.isSystemInternal() && prop.isSystemInternal()) {
                if (FxContext.getUserTicket().isGlobalSupervisor()) {
                    ps = con.prepareStatement(
                            "UPDATE " + TBL_STRUCT_PROPERTIES + " SET SYSINTERNAL=? WHERE ID=?");
                    ps.setBoolean(1, prop.isSystemInternal());
                    ps.setLong(2, prop.getId());
                    ps.executeUpdate();
                    ps.close();
                    if (changes)
                        changesDesc.append(',');
                    changesDesc.append("systemInternal=").append(prop.isSystemInternal());
                    changes = true;
                } else
                    throw new FxUpdateException("ex.structure.modification.systemInternal.notGlobalSupervisor",
                            prop.getName());
            }
            if (org.isMultiLang() != prop.isMultiLang()) {
                if (getPropertyInstanceCount(org.getId()) > 0)
                    throw new FxUpdateException("ex.structure.modification.contentExists", "multiLang");
            }
        }
        if (updatePropertyOptions(con, prop)) {
            changesDesc.append(",options:");
            List<FxStructureOption> options = prop.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.assignment.updateProperty", prop.getName(), prop.getId(),
                    changesDesc.toString());
        success = true;
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        /*TODO: Determine if this must be checked
        if (Database.isUniqueConstraintViolation(e))
        throw new FxEntryExistsException("ex.structure.assignment.property.exists", prop.getAlias(), prop.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:org.apache.tajo.catalog.store.AbstractDBStore.java

@Override
public void createTable(final CatalogProtos.TableDescProto table)
        throws UndefinedDatabaseException, DuplicateTableException {

    Connection conn = null;//from  w  ww.java2  s .com
    PreparedStatement pstmt = null;
    ResultSet res = null;

    final String[] splitted = IdentifierUtil.splitTableName(table.getTableName());
    if (splitted.length == 1) {
        throw new TajoInternalError(
                "createTable() requires a qualified table name, but it is '" + table.getTableName() + "'");
    }
    final String databaseName = splitted[0];
    final String tableName = splitted[1];

    if (existTable(databaseName, tableName)) {
        throw new DuplicateTableException(tableName);
    }
    final int dbid = getDatabaseId(databaseName);

    try {
        conn = getConnection();
        conn.setAutoCommit(false);

        String sql = "INSERT INTO TABLES (DB_ID, " + COL_TABLES_NAME
                + ", TABLE_TYPE, PATH, DATA_FORMAT, HAS_SELF_DESCRIBE_SCHEMA) VALUES(?, ?, ?, ?, ?, ?) ";

        if (LOG.isDebugEnabled()) {
            LOG.debug(sql);
        }

        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, dbid);
        pstmt.setString(2, tableName);
        if (table.getIsExternal()) {
            pstmt.setString(3, TableType.EXTERNAL.name());
        } else {
            pstmt.setString(3, TableType.MANAGED.name());
        }
        pstmt.setString(4, table.getPath());
        pstmt.setString(5, table.getMeta().getDataFormat());
        pstmt.setBoolean(6, table.getSchema() == null);
        pstmt.executeUpdate();
        pstmt.close();

        String tidSql = "SELECT TID from " + TB_TABLES + " WHERE " + COL_DATABASES_PK + "=? AND "
                + COL_TABLES_NAME + "=?";
        pstmt = conn.prepareStatement(tidSql);
        pstmt.setInt(1, dbid);
        pstmt.setString(2, tableName);
        res = pstmt.executeQuery();

        if (!res.next()) {
            throw new TajoInternalError("There is no TID matched to '" + table.getTableName() + '"');
        }

        int tableId = res.getInt("TID");
        res.close();
        pstmt.close();

        String colSql = "INSERT INTO " + TB_COLUMNS +
        // 1    2            3                 4
                " (TID, COLUMN_NAME, ORDINAL_POSITION, DATA_TYPE)" + " VALUES(?, ?, ?, ?) ";

        if (LOG.isDebugEnabled()) {
            LOG.debug(colSql);
        }

        pstmt = conn.prepareStatement(colSql);
        for (int i = 0; i < table.getSchema().getFieldsCount(); i++) {
            ColumnProto col = table.getSchema().getFields(i);
            org.apache.tajo.type.Type type = TypeProtobufEncoder.decode(col.getType());

            pstmt.setInt(1, tableId);
            pstmt.setString(2, extractSimpleName(col.getName()));
            pstmt.setInt(3, i);
            pstmt.setString(4, TypeStringEncoder.encode(type));
            pstmt.addBatch();
            pstmt.clearParameters();
        }
        pstmt.executeBatch();
        pstmt.close();

        if (table.getMeta().hasParams()) {
            String propSQL = "INSERT INTO " + TB_OPTIONS + "(TID, KEY_, VALUE_) VALUES(?, ?, ?)";

            if (LOG.isDebugEnabled()) {
                LOG.debug(propSQL);
            }

            pstmt = conn.prepareStatement(propSQL);
            for (KeyValueProto entry : table.getMeta().getParams().getKeyvalList()) {
                pstmt.setInt(1, tableId);
                pstmt.setString(2, entry.getKey());
                pstmt.setString(3, entry.getValue());
                pstmt.addBatch();
                pstmt.clearParameters();
            }
            pstmt.executeBatch();
            pstmt.close();
        }

        if (table.hasStats()) {

            String statSql = "INSERT INTO " + TB_STATISTICS + " (TID, NUM_ROWS, NUM_BYTES) VALUES(?, ?, ?)";

            if (LOG.isDebugEnabled()) {
                LOG.debug(statSql);
            }

            pstmt = conn.prepareStatement(statSql);
            pstmt.setInt(1, tableId);
            pstmt.setLong(2, table.getStats().getNumRows());
            pstmt.setLong(3, table.getStats().getNumBytes());
            pstmt.executeUpdate();
            pstmt.close();
        }

        if (table.hasPartition()) {
            String partSql = "INSERT INTO PARTITION_METHODS (TID, PARTITION_TYPE, EXPRESSION, EXPRESSION_SCHEMA) VALUES(?, ?, ?, ?)";

            if (LOG.isDebugEnabled()) {
                LOG.debug(partSql);
            }

            pstmt = conn.prepareStatement(partSql);
            pstmt.setInt(1, tableId);
            pstmt.setString(2, table.getPartition().getPartitionType().name());
            pstmt.setString(3, table.getPartition().getExpression());
            pstmt.setBytes(4, table.getPartition().getExpressionSchema().toByteArray());
            pstmt.executeUpdate();
        }

        // If there is no error, commit the changes.
        conn.commit();
    } catch (SQLException se) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                LOG.error(e, e);
            }
        }
        throw new TajoInternalError(se);
    } finally {
        CatalogUtil.closeQuietly(pstmt, res);
    }
}

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

/**
 * Updates a group assignment// w ww  .ja v a  2 s.com
 *
 * @param con   a valid and open connection
 * @param group the FxGroupAssignment to be changed
 * @return returns true if changes were made to the group assignment
 * @throws FxApplicationException on errors
 */
private boolean updateGroupAssignment(Connection con, FxGroupAssignmentEdit group)
        throws FxApplicationException {
    if (group.isNew())
        throw new FxInvalidParameterException("ex.structure.assignment.update.new", group.getXPath());
    final StringBuilder sql = new StringBuilder(1000);
    boolean changes = false;
    boolean success = false;
    StringBuilder changesDesc = new StringBuilder(200);
    FxGroupAssignment org = (FxGroupAssignment) CacheAdmin.getEnvironment().getAssignment(group.getId());
    PreparedStatement ps = null;
    try {
        sql.setLength(0);
        // enable / disable an assignment
        if (org.isEnabled() != group.isEnabled()) {
            if (changes)
                changesDesc.append(',');
            changesDesc.append("enabled=").append(group.isEnabled());
            //apply for all child groups and properties as well!
            if (org.getAssignments().size() > 0)
                changesDesc.append(", ").append(group.isEnabled() ? "en" : "dis")
                        .append("abled child assignments: ");
            for (FxAssignment as : org.getAssignments()) {
                changesDesc.append(as.getXPath()).append(',');
            }
            if (changesDesc.charAt(changesDesc.length() - 1) == ',')
                changesDesc.deleteCharAt(changesDesc.length() - 1);
            if (!group.isEnabled())
                removeAssignment(org.getId(), true, false, true, false);
            else {
                StringBuilder affectedAssignment = new StringBuilder(500);
                affectedAssignment.append(org.getId());
                for (FxAssignment as : org.getAllChildAssignments())
                    affectedAssignment.append(",").append(as.getId());
                ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET ENABLED=? WHERE ID IN ("
                        + affectedAssignment + ")");
                ps.setBoolean(1, true);
                ps.executeUpdate();
                ps.close();
            }
            changes = true;
        }
        // set the assignment's position
        if (org.getPosition() != group.getPosition()) {
            int finalPos = setAssignmentPosition(con, group.getId(), group.getPosition());
            if (changes)
                changesDesc.append(',');
            changesDesc.append("position=").append(finalPos);
            changes = true;
        }
        // change the assignment's default multiplicity (will be auto-adjusted to a valid value in FxGroupAssignmentEdit)
        if (org.getDefaultMultiplicity() != group.getDefaultMultiplicity()) {
            ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET DEFMULT=? WHERE ID=?");
            ps.setInt(1, group.getDefaultMultiplicity());
            ps.setLong(2, group.getId());
            ps.executeUpdate();
            ps.close();
            if (changes)
                changesDesc.append(',');
            changesDesc.append("defaultMultiplicity=").append(group.getDefaultMultiplicity());
            changes = true;
        }
        // change the assignment's multiplicity
        final boolean needMinChange = org.getMultiplicity().getMin() != group.getMultiplicity().getMin();
        final boolean needMaxChange = org.getMultiplicity().getMax() != group.getMultiplicity().getMax();
        if (needMinChange || needMaxChange) {
            if (org.getGroup().mayOverrideBaseMultiplicity()) {
                if (needMinChange)
                    checkChangeGroupAssignmentMinMultiplicity(con, org, group);
                if (needMaxChange && getGroupInstanceMultiplicity(con, org.getGroup().getId(), false) > group
                        .getMultiplicity().getMax())
                    throw new FxUpdateException("ex.structure.modification.contentExists",
                            "maximumMultiplicity");
            } else {
                throw new FxUpdateException("ex.structure.group.assignment.overrideBaseMultiplicityNotEnabled",
                        org.getGroup().getId());
            }
            ps = con.prepareStatement(
                    "UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET MINMULT=? ,MAXMULT=? 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;
        }
        // set the assignment's position
        if (org.getPosition() != group.getPosition()) {
            int finalPos = setAssignmentPosition(con, group.getId(), group.getPosition());
            if (changes)
                changesDesc.append(',');
            changesDesc.append("position=").append(finalPos);
            changes = true;
        }
        // set the XPath (and the alias) of a group assignment
        if (!org.getXPath().equals(group.getXPath()) || !org.getAlias().equals(group.getAlias())) {
            if (!XPathElement.isValidXPath(XPathElement.stripType(group.getXPath())) || group.getAlias()
                    .equals(XPathElement.lastElement(XPathElement.stripType(org.getXPath())).getAlias()))
                throw new FxUpdateException("ex.structure.assignment.noXPath");
            // generate correct XPATH
            if (!group.getXPath().startsWith(group.getAssignedType().getName()))
                group.setXPath(group.getAssignedType().getName() + group.getXPath());
            //avoid duplicates
            if (org.getAssignedType().isXPathValid(group.getXPath(), true))
                throw new FxUpdateException("ex.structure.assignment.exists", group.getXPath(),
                        group.getAssignedType().getName());
            // update db entries
            ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET XPATH=?, XALIAS=? WHERE ID=?");
            ps.setString(1, group.getXPath());
            ps.setString(2, group.getAlias());
            ps.setLong(3, group.getId());
            ps.executeUpdate();
            ps.close();
            // update the relevant content instances
            ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical);
            storage.updateXPath(con, group.getId(), XPathElement.stripType(org.getXPath()),
                    XPathElement.stripType(group.getXPath()));
            //update all child assignments
            ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET XPATH=? WHERE ID=?");
            for (FxAssignment child : org.getAllChildAssignments()) {
                ps.setString(1, group.getXPath() + child.getXPath().substring(org.getXPath().length()));
                ps.setLong(2, child.getId());
                ps.executeUpdate();
                storage.updateXPath(con, child.getId(), XPathElement.stripType(child.getXPath()), XPathElement
                        .stripType(group.getXPath() + child.getXPath().substring(org.getXPath().length())));
            }
            ps.close();
            if (changes)
                changesDesc.append(',');
            changesDesc.append("xPath=").append(group.getXPath()).append(",alias=").append(group.getAlias());
            changes = true;
        }
        // update 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_ASSIGNMENTS, 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;
        }
        //update SystemInternal flag, this is a one way function, so it can only be set, but not reset!!
        if (!org.isSystemInternal() && group.isSystemInternal()
                && FxContext.getUserTicket().isGlobalSupervisor()) {
            ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET SYSINTERNAL=? WHERE ID=?");
            ps.setBoolean(1, group.isSystemInternal());
            ps.setLong(2, group.getId());
            ps.executeUpdate();
            ps.close();
            if (changes)
                changesDesc.append(',');
            changesDesc.append("systemInternal=").append(group.isSystemInternal());
            changes = true;
        }
        // change GroupMode
        // OneOf --> AnyOf always allowed, AnyOf --> OneOf not allowed if content exists
        if (org.getMode().getId() != group.getMode().getId()) {
            if (org.getMode().equals(GroupMode.AnyOf) && group.getMode().equals(GroupMode.OneOf)) {
                if (getGroupInstanceMultiplicity(con, org.getGroup().getId(), true) > 0) {
                    throw new FxUpdateException(LOG, "ex.structure.group.assignment.modeChangeError");
                }
            }
            ps = con.prepareStatement("UPDATE " + TBL_STRUCT_ASSIGNMENTS + " SET GROUPMODE=? WHERE ID=?");
            ps.setLong(1, group.getMode().getId());
            ps.setLong(2, group.getId());
            ps.executeUpdate();
            ps.close();
            if (changes)
                changesDesc.append(',');
            changesDesc.append("groupMode=").append(group.getMode().getId());
            changes = true;
        }
        // change the parentgroupassignment
        // TODO: change the parent group assignment & failure conditions
        //            if (org.getParentGroupAssignment().getId() != group.getParentGroupAssignment().getId()) {
        //            }
        // change the group assignment options
        if (updateGroupAssignmentOptions(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()).append(" isInherited=").append(option.getIsInherited());
            }
            changes = true;
        }

        if (changes)
            htracker.track(group.getAssignedType(), "history.assignment.updateGroupAssignment",
                    group.getXPath(), group.getAssignedType().getId(), group.getAssignedType().getName(),
                    group.getGroup().getId(), group.getGroup().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.group.exists", group.getAlias(),
                    group.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.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void storeMetaData(ConnectorMessage connectorMessage, List<MetaDataColumn> metaDataColumns) {
    logger.debug(connectorMessage.getChannelId() + "/" + connectorMessage.getMessageId() + "/"
            + connectorMessage.getMetaDataId() + ": updating custom meta data");
    PreparedStatement statement = null;

    try {/*from  ww w . j  a va  2  s .co m*/
        List<String> metaDataColumnNames = new ArrayList<String>();
        Map<String, Object> metaDataMap = connectorMessage.getMetaDataMap();

        for (MetaDataColumn metaDataColumn : metaDataColumns) {
            Object value = metaDataMap.get(metaDataColumn.getName());

            if (value != null) {
                metaDataColumnNames.add(metaDataColumn.getName());
            }
        }

        // Don't do anything if all values were null
        if (!metaDataColumnNames.isEmpty()) {
            Map<String, Object> values = new HashMap<String, Object>();
            values.put("localChannelId", getLocalChannelId(connectorMessage.getChannelId()));
            values.put("metaDataColumnPlaceholders",
                    quoteChar + StringUtils.join(metaDataColumnNames, quoteChar + " = ?, " + quoteChar)
                            + quoteChar + " = ?");

            statement = connection.prepareStatement(querySource.getQuery("storeMetaData", values));
            int n = 1;

            for (MetaDataColumn metaDataColumn : metaDataColumns) {
                Object value = metaDataMap.get(metaDataColumn.getName());

                if (value != null) {
                    // @formatter:off
                    switch (metaDataColumn.getType()) {
                    case STRING:
                        statement.setString(n, (String) value);
                        break;
                    case NUMBER:
                        statement.setBigDecimal(n, (BigDecimal) value);
                        break;
                    case BOOLEAN:
                        statement.setBoolean(n, (Boolean) value);
                        break;
                    case TIMESTAMP:
                        statement.setTimestamp(n, new Timestamp(((Calendar) value).getTimeInMillis()));
                        break;
                    }
                    // @formatter:on

                    n++;
                }
            }

            statement.setLong(n++, connectorMessage.getMessageId());
            statement.setInt(n, connectorMessage.getMetaDataId());

            statement.executeUpdate();
        }
    } catch (Exception e) {
        throw new DonkeyDaoException("Failed to update connector message meta data", e);
    } finally {
        close(statement);
    }
}

From source file:edu.ucsb.eucalyptus.cloud.ws.WalrusManager.java

private void writeEvent(EntityManager em, final String eventType, final String account, final String opt,
        final String object_key, final Long size, final Boolean isFolder, final long syncid,
        final long lastModified, final String reqid, final int objseq) throws EucalyptusCloudException {

    Session sess = null;//from w  w  w.j  a  v  a2s.com
    try {
        sess = ((Session) em.getDelegate());
    } catch (Throwable t) {
        sess = null;
    }

    final java.sql.Timestamp mtime = new java.sql.Timestamp(lastModified);

    if ("webApp".equals(eventType)) {
        final String sql = "insert into web_opt_log(id,rectime,time,cssact,op,fpth,fsz,file_version,syncid,isfolder,rslt,inst_id, reqid) values(DEFAULT,CURRENT_TIMESTAMP AT TIME ZONE 'UTC +0',?,?,?,?,?,?,NULL,?,'succ','dummy',?)";
        if (sess != null) {
            sess.doWork(new Work() {
                public void execute(Connection connection) throws SQLException {
                    PreparedStatement stmt = null;
                    try {
                        stmt = connection.prepareStatement(sql);
                        stmt.setTimestamp(1, mtime);
                        stmt.setString(2, account);
                        stmt.setString(3, opt);
                        stmt.setString(4, object_key);
                        stmt.setLong(5, size);
                        stmt.setInt(6, objseq);
                        stmt.setBoolean(7, isFolder);
                        stmt.setString(8, reqid);
                        stmt.executeUpdate();
                    } finally {
                        if (stmt != null)
                            stmt.close();
                    }
                }
            });
        } else {
            em.createNativeQuery(sql).setParameter(1, mtime).setParameter(2, account).setParameter(3, opt)
                    .setParameter(4, object_key).setParameter(5, size).setParameter(6, objseq)
                    .setParameter(7, isFolder).setParameter(8, reqid).executeUpdate();
        }
    } else if ("mobileApp".equals(eventType)) {
    } else {
        final String sql = "insert into opt_log(id,rectime,time,cssact,op,fpth,fsz,file_version,syncid,isfolder,rslt,inst_id, reqid) values(DEFAULT,CURRENT_TIMESTAMP AT TIME ZONE 'UTC +0',?,?,?,?,?,?,?,?,'succ','dummy',?)";
        if (sess != null) {
            sess.doWork(new Work() {
                public void execute(Connection connection) throws SQLException {
                    PreparedStatement stmt = null;
                    try {
                        stmt = connection.prepareStatement(sql);
                        stmt.setTimestamp(1, mtime);
                        stmt.setString(2, account);
                        stmt.setString(3, opt);
                        stmt.setString(4, object_key);
                        stmt.setLong(5, size);
                        stmt.setInt(6, objseq);
                        stmt.setLong(7, syncid);
                        stmt.setBoolean(8, isFolder);
                        stmt.setString(9, reqid);
                        stmt.executeUpdate();
                    } finally {
                        if (stmt != null)
                            stmt.close();
                    }

                }
            }

            );
        } else {
            em.createNativeQuery(sql).setParameter(1, mtime).setParameter(2, account).setParameter(3, opt)
                    .setParameter(4, object_key).setParameter(5, size).setParameter(6, objseq)
                    .setParameter(7, syncid).setParameter(8, isFolder).setParameter(9, reqid).executeUpdate();
        }
    }
}

From source file:com.flexive.ejb.beans.PhraseEngineBean.java

/**
 * {@inheritDoc}//from  ww  w .ja  va 2 s  . c  om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long savePhrase(int category, String phraseKey, FxString value, FxPhraseSearchValueConverter converter,
        Object tag, long mandator) throws FxNoAccessException {
    Connection con = null;
    PreparedStatement ps = null;
    final UserTicket userTicket = FxContext.getUserTicket();
    checkMandatorAccess(mandator, userTicket);
    checkPhraseKey(phraseKey);
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        long phraseId;
        ps = con.prepareStatement("SELECT ID FROM " + TBL_PHRASE + " WHERE PKEY=? AND MANDATOR=? AND CAT=?");
        ps.setString(1, phraseKey);
        ps.setLong(2, mandator);
        ps.setInt(3, category);
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            phraseId = rs.getLong(1);
            rs.close();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_VALUES + " WHERE ID=? AND MANDATOR=?");
            ps.setLong(1, phraseId);
            ps.setLong(2, mandator);
            ps.executeUpdate();
        } else {
            try {
                phraseId = fetchNextPhraseId(mandator);
            } catch (FxApplicationException e) {
                EJBUtils.rollback(ctx);
                throw e.asRuntimeException();
            }
            ps.close();
            ps = con.prepareStatement(
                    "INSERT INTO " + TBL_PHRASE + "(ID,PKEY,MANDATOR,HID,CAT)VALUES(?,?,?,?,?)");
            ps.setLong(1, phraseId);
            ps.setString(2, phraseKey);
            ps.setLong(3, mandator);
            ps.setBoolean(4, false);
            ps.setInt(5, category);
            ps.executeUpdate();
        }
        if (!value.isEmpty()) {
            ps.close();
            ps = con.prepareStatement(
                    "INSERT INTO " + TBL_PHRASE_VALUES + "(ID,MANDATOR,LANG,PVAL,SVAL,TAG)VALUES(?,?,?,?,?,?)");
            ps.setLong(1, phraseId);
            ps.setLong(2, mandator);
            FxString fxTag = tag instanceof FxString ? (FxString) tag : null;
            for (long lang : value.getTranslatedLanguages()) {
                ps.setLong(3, lang);
                final String translation = value.getTranslation(lang);
                if (StringUtils.isBlank(translation))
                    continue;
                ps.setString(4, translation);
                if (converter != null)
                    ps.setString(5, converter.convert(translation, lang));
                else
                    ps.setString(5, translation.trim().toUpperCase());
                if (fxTag != null) {
                    if (!fxTag.isMultiLanguage() || fxTag.translationExists(lang))
                        ps.setString(6, fxTag.getTranslation(lang));
                    else
                        ps.setNull(6, Types.VARCHAR);
                } else {
                    if (tag != null && !StringUtils.isBlank(String.valueOf(tag)))
                        ps.setString(6, String.valueOf(tag));
                    else
                        ps.setNull(6, Types.VARCHAR);
                }
                ps.addBatch();
            }
            ps.executeBatch();
        }
        return phraseId;
    } 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.flexive.ejb.beans.structure.AssignmentEngineBean.java

/**
 * {@inheritDoc}//from   w w w .  ja va  2s .  c o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long createGroup(long typeId, FxGroupEdit group, String parentXPath, String assignmentAlias)
        throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.StructureManagement);
    Connection con = null;
    PreparedStatement ps = null;
    StringBuilder sql = new StringBuilder(2000);
    long newGroupId;
    long newAssignmentId;
    try {
        parentXPath = parentXPath.toUpperCase();
        assignmentAlias = assignmentAlias.toUpperCase();
        FxType type = CacheAdmin.getEnvironment().getType(typeId);
        FxAssignment tmp = type.getAssignment(parentXPath);
        if (tmp != null && tmp instanceof FxPropertyAssignment)
            throw new FxInvalidParameterException("ex.structure.assignment.noGroup", parentXPath);
        //parentXPath is valid, create the group, then assign it to root
        newGroupId = seq.getId(FxSystemSequencer.TYPEGROUP);
        con = Database.getDbConnection();
        ContentStorage storage = StorageManager.getContentStorage(type.getStorageMode());
        // do not allow to add mandatory groups (i.e. min multiplicity > 0) to types for which content exists
        if (storage.getTypeInstanceCount(con, typeId) > 0 && group.getMultiplicity().getMin() > 0) {
            throw new FxCreateException("ex.structure.group.creation.exisitingContentMultiplicityError",
                    group.getName(), group.getMultiplicity().getMin());
        }

        //create group
        sql.append("INSERT INTO ").append(TBL_STRUCT_GROUPS)
                .append("(ID,NAME,DEFMINMULT,DEFMAXMULT,MAYOVERRIDEMULT)VALUES(?,?,?,?,?)");
        ps = con.prepareStatement(sql.toString());
        ps.setLong(1, newGroupId);
        ps.setString(2, group.getName());
        ps.setInt(3, group.getMultiplicity().getMin());
        ps.setInt(4, group.getMultiplicity().getMax());
        ps.setBoolean(5, group.mayOverrideBaseMultiplicity());
        ps.executeUpdate();
        ps.close();
        sql.setLength(0);
        Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con, TBL_STRUCT_GROUPS,
                new String[] { "DESCRIPTION", "HINT" }, "ID", newGroupId);
        //calc new position
        sql.append("SELECT COALESCE(MAX(POS)+1,0) FROM ").append(TBL_STRUCT_ASSIGNMENTS)
                .append(" WHERE PARENTGROUP=? AND TYPEDEF=?");
        ps = con.prepareStatement(sql.toString());
        ps.setLong(1, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId()));
        ps.setLong(2, typeId);
        ResultSet rs = ps.executeQuery();
        long pos = 0;
        if (rs != null && rs.next())
            pos = rs.getLong(1);
        ps.close();
        storeOptions(con, TBL_STRUCT_GROUP_OPTIONS, "ID", newGroupId, null, group.getOptions());
        sql.setLength(0);
        //create root assignment
        sql.append("INSERT INTO ").append(TBL_STRUCT_ASSIGNMENTS).
        //               1  2     3       4       5       6       7       8   9     10     11   12          13     14
                append("(ID,ATYPE,ENABLED,TYPEDEF,MINMULT,MAXMULT,DEFMULT,POS,XPATH,XALIAS,BASE,PARENTGROUP,AGROUP,GROUPMODE)"
                        + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        ps = con.prepareStatement(sql.toString());
        newAssignmentId = seq.getId(FxSystemSequencer.ASSIGNMENT);
        ps.setLong(1, newAssignmentId);
        ps.setInt(2, FxAssignment.TYPE_GROUP);
        ps.setBoolean(3, true);
        ps.setLong(4, typeId);
        ps.setInt(5, group.getMultiplicity().getMin());
        ps.setInt(6, group.getMultiplicity().getMax());
        if (group.getMultiplicity().isValid(group.getAssignmentDefaultMultiplicity())) {
            ps.setInt(7, group.getAssignmentDefaultMultiplicity());
        } else {
            //default is min(min,1).
            ps.setInt(7, group.getMultiplicity().getMin() > 1 ? group.getMultiplicity().getMin() : 1);
        }
        ps.setLong(8, pos);
        if (parentXPath == null || "/".equals(parentXPath))
            parentXPath = "";
        ps.setString(9, type.getName() + XPathElement.stripType(parentXPath) + "/" + assignmentAlias);
        ps.setString(10, assignmentAlias);
        ps.setNull(11, java.sql.Types.NUMERIC);
        ps.setLong(12, (tmp == null ? FxAssignment.NO_PARENT : tmp.getId()));
        ps.setLong(13, newGroupId);
        ps.setInt(14, group.getAssignmentGroupMode().getId());
        ps.executeUpdate();
        Database.storeFxString(new FxString[] { group.getLabel(), group.getHint() }, con,
                TBL_STRUCT_ASSIGNMENTS, new String[] { "DESCRIPTION", "HINT" }, "ID", newAssignmentId);
        StructureLoader.reloadAssignments(FxContext.get().getDivisionId());
        htracker.track(type, "history.assignment.createGroup", group.getName(), type.getId(), type.getName());
        if (type.getId() != FxType.ROOT_ID)
            createInheritedAssignments(CacheAdmin.getEnvironment().getAssignment(newAssignmentId), con, sql,
                    type.getDerivedTypes());
    } catch (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxLoadException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (SQLException e) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(e);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation)
            throw new FxEntryExistsException("ex.structure.group.exists", group.getName(),
                    (parentXPath.length() == 0 ? "/" : parentXPath));
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(AssignmentEngineBean.class, con, ps);
    }
    return newAssignmentId;
}

From source file:org.apache.tajo.catalog.store.AbstractDBStore.java

@Override
public List<PartitionDescProto> getPartitionsByAlgebra(PartitionsByAlgebraProto request)
        throws UndefinedDatabaseException, UndefinedTableException, UndefinedPartitionMethodException,
        UnsupportedException {/* w w w  .  j  a v a2s  .  co  m*/
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet res = null;
    int currentIndex = 1;
    String selectStatement = null;
    Pair<String, List<PartitionFilterSet>> pair = null;

    List<PartitionDescProto> partitions = new ArrayList<>();
    List<PartitionFilterSet> filterSets = null;

    int databaseId = getDatabaseId(request.getDatabaseName());
    int tableId = getTableId(databaseId, request.getDatabaseName(), request.getTableName());
    if (!existPartitionMethod(request.getDatabaseName(), request.getTableName())) {
        throw new UndefinedPartitionMethodException(request.getTableName());
    }

    try {
        TableDescProto tableDesc = getTable(request.getDatabaseName(), request.getTableName());

        pair = getSelectStatementAndPartitionFilterSet(tableDesc.getTableName(),
                tableDesc.getPartition().getExpressionSchema().getFieldsList(), request.getAlgebra());

        selectStatement = pair.getFirst();
        filterSets = pair.getSecond();

        conn = getConnection();
        pstmt = conn.prepareStatement(selectStatement);

        // Set table id by force because first parameter of all direct sql is table id
        pstmt.setInt(currentIndex, tableId);
        currentIndex++;

        for (PartitionFilterSet filter : filterSets) {
            // Set table id by force because all filters have table id as first parameter.
            pstmt.setInt(currentIndex, tableId);
            currentIndex++;

            for (Pair<Type, Object> parameter : filter.getParameters()) {
                switch (parameter.getFirst()) {
                case BOOLEAN:
                    pstmt.setBoolean(currentIndex, (Boolean) parameter.getSecond());
                    break;
                case INT8:
                    pstmt.setLong(currentIndex, (Long) parameter.getSecond());
                    break;
                case FLOAT8:
                    pstmt.setDouble(currentIndex, (Double) parameter.getSecond());
                    break;
                case DATE:
                    pstmt.setDate(currentIndex, (Date) parameter.getSecond());
                    break;
                case TIMESTAMP:
                    pstmt.setTimestamp(currentIndex, (Timestamp) parameter.getSecond());
                    break;
                case TIME:
                    pstmt.setTime(currentIndex, (Time) parameter.getSecond());
                    break;
                default:
                    pstmt.setString(currentIndex, (String) parameter.getSecond());
                    break;
                }
                currentIndex++;
            }
        }

        res = pstmt.executeQuery();

        while (res.next()) {
            PartitionDescProto.Builder builder = PartitionDescProto.newBuilder();

            builder.setId(res.getInt(COL_PARTITIONS_PK));
            builder.setPartitionName(res.getString("PARTITION_NAME"));
            builder.setPath(res.getString("PATH"));
            builder.setNumBytes(res.getLong(COL_PARTITION_BYTES));

            partitions.add(builder.build());
        }
    } catch (SQLException se) {
        throw new TajoInternalError(se);
    } finally {
        CatalogUtil.closeQuietly(pstmt, res);
    }

    return partitions;
}

From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java

/**
 * Update a properties data and/or position or a groups position
 *
 * @param change  the change applied/*from   ww  w .j a va2  s  .  c  o m*/
 * @param prop    the property unless change is a group change
 * @param allData all content data unless change is a group change
 * @param con     an open and valid connection
 * @param ps      batch prepared statement for detail updates
 * @param pk      primary key
 * @param data    property data unless change is a group change
 * @throws SQLException        on errors
 * @throws FxDbException       on errors
 * @throws FxUpdateException   on errors
 * @throws FxNoAccessException for FxNoAccess values
 */
protected void updatePropertyData(FxDelta.FxDeltaChange change, FxProperty prop, List<FxData> allData,
        Connection con, PreparedStatement ps, FxPK pk, FxPropertyData data)
        throws SQLException, FxDbException, FxUpdateException, FxNoAccessException {
    if ((change.isProperty()
            && (data == null || data.isEmpty() || data.getPropertyAssignment().isFlatStorageEntry()))
            || !(change.isDataChange() || change.isPositionChange()))
        return;
    clearPreparedStatement(ps, 1, UPDATE_ID_POS);
    ps.setLong(3, 0); //FSELECT has to be set to 0 and not null!

    if (change.isPositionChange())
        ps.setInt(UPDATE_POS_POS, change.getNewData().getPos());
    else
        ps.setInt(UPDATE_POS_POS, change.getOriginalData().getPos());

    ps.setLong(UPDATE_ID_POS, pk.getId());
    ps.setInt(UPDATE_ID_POS + 1, pk.getVersion());
    ps.setLong(UPDATE_ID_POS + 3, change.getNewData().getAssignmentId());
    ps.setString(UPDATE_ID_POS + 4, FxArrayUtils.toStringArray(change.getNewData().getIndices(), ','));

    if (change.isGroup()) {
        ps.setInt(UPDATE_ID_POS + 2, (int) FxLanguage.SYSTEM_ID);
        ps.setBoolean(UPDATE_MLDEF_POS, true);
        if (batchContentDataChanges())
            ps.addBatch();
        else
            ps.executeUpdate();
        return;
    }

    if (change.isPositionChange() && !change.isDataChange()) {
        //just update positions
        assert data != null;
        for (long lang : data.getValue().getTranslatedLanguages()) {
            ps.setInt(UPDATE_ID_POS + 2, (int) lang);
            setPropertyData(false, prop, allData, con, data, ps, null, getUppercaseColumnPos(prop, false),
                    false);
        }
        return;
    }
    setPropertyData(false, prop, allData, con, data, ps, null, getUppercaseColumnPos(prop, false), true);
}