Example usage for java.sql Types INTEGER

List of usage examples for java.sql Types INTEGER

Introduction

In this page you can find the example usage for java.sql Types INTEGER.

Prototype

int INTEGER

To view the source code for java.sql Types INTEGER.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type INTEGER.

Usage

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

public boolean setHibernateType(@Nullable SimpleValue value,
        com.manydesigns.portofino.model.database.Column column, Class javaType, final int jdbcType) {
    String typeName;//from  w ww. j  ava 2  s. c  o m
    Properties typeParams = null;
    if (javaType == null) {
        return false;
    }
    if (javaType == Long.class) {
        typeName = LongType.INSTANCE.getName();
    } else if (javaType == Short.class) {
        typeName = ShortType.INSTANCE.getName();
    } else if (javaType == Integer.class) {
        typeName = IntegerType.INSTANCE.getName();
    } else if (javaType == Byte.class) {
        typeName = ByteType.INSTANCE.getName();
    } else if (javaType == Float.class) {
        typeName = FloatType.INSTANCE.getName();
    } else if (javaType == Double.class) {
        typeName = DoubleType.INSTANCE.getName();
    } else if (javaType == Character.class) {
        typeName = CharacterType.INSTANCE.getName();
    } else if (javaType == String.class) {
        typeName = StringType.INSTANCE.getName();
    } else if (java.util.Date.class.isAssignableFrom(javaType)) {
        switch (jdbcType) {
        case Types.DATE:
            typeName = DateType.INSTANCE.getName();
            break;
        case Types.TIME:
            typeName = TimeType.INSTANCE.getName();
            break;
        case Types.TIMESTAMP:
            typeName = TimestampType.INSTANCE.getName();
            break;
        default:
            typeName = null;
        }
    } else if (javaType == Boolean.class) {
        if (jdbcType == Types.BIT || jdbcType == Types.BOOLEAN) {
            typeName = BooleanType.INSTANCE.getName();
        } else if (jdbcType == Types.NUMERIC || jdbcType == Types.DECIMAL || jdbcType == Types.INTEGER
                || jdbcType == Types.SMALLINT || jdbcType == Types.TINYINT || jdbcType == Types.BIGINT) {
            typeName = NumericBooleanType.INSTANCE.getName();
        } else if (jdbcType == Types.CHAR || jdbcType == Types.VARCHAR) {
            typeName = StringBooleanType.class.getName();
            typeParams = new Properties();
            typeParams.setProperty("true", trueString != null ? trueString : StringBooleanType.NULL);
            typeParams.setProperty("false", falseString != null ? falseString : StringBooleanType.NULL);
            typeParams.setProperty("sqlType", String.valueOf(jdbcType));
        } else {
            typeName = null;
        }
    } else if (javaType == BigDecimal.class) {
        typeName = BigDecimalType.INSTANCE.getName();
    } else if (javaType == BigInteger.class) {
        typeName = BigIntegerType.INSTANCE.getName();
    } else if (javaType == byte[].class) {
        typeName = BlobType.INSTANCE.getName();
    } else {
        typeName = null;
    }

    if (typeName == null) {
        logger.error("Unsupported type (java type: {}, jdbc type: {}) " + "for column '{}'.",
                new Object[] { javaType, jdbcType, column.getColumnName() });
        return false;
    }

    if (value != null) {
        value.setTypeName(typeName);
        if (typeParams != null) {
            value.setTypeParameters(typeParams);
        }
    }
    return true;
}

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

/**
 * Update an existing type/* w  ww.  ja  va 2 s. c  o  m*/
 *
 * @param type the type to update
 * @return id of the type
 * @throws FxApplicationException on errors
 */
private long update(FxTypeEdit type) throws FxApplicationException {
    if (!type.isChanged())
        return type.getId();

    final UserTicket ticket = FxContext.getUserTicket();
    FxPermissionUtils.checkRole(ticket, Role.StructureManagement);
    final FxEnvironment environment = CacheAdmin.getEnvironment();

    if (StringUtils.isEmpty(type.getName()))
        throw new FxInvalidParameterException("NAME", "ex.structure.update.nameMissing");

    //security checks start
    if (!ticket.mayEditACL(type.getACL().getId(), 0))
        throw new FxNoAccessException("ex.acl.noAccess.edit", type.getACL().getName());
    //security checks end

    boolean needReload = false; //full reload only needed if assignments have changed
    Connection con = null;
    PreparedStatement ps = null;
    FxType orgType = environment.getType(type.getId());

    StringBuilder sql = new StringBuilder(500);

    try {
        con = Database.getDbConnection();
        long instanceCount = -1; //number of instances
        //start name change
        if (!orgType.getName().equals(type.getName())) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET NAME=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setString(1, type.getName());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            //update all xpaths affected
            ps.close();
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_ASSIGNMENTS)
                    .append(" SET XPATH=REPLACE(XPATH, ?, ?) WHERE TYPEDEF=? AND ")
                    .append(StorageManager.getRegExpLikeOperator("XPATH", "?"));
            ps = con.prepareStatement(sql.toString());
            ps.setString(1, orgType.getName() + "/");
            ps.setString(2, type.getName() + "/");
            ps.setLong(3, type.getId());
            ps.setString(4, "^" + orgType.getName() + "/");
            int changed = ps.executeUpdate();
            if (changed > 0)
                needReload = true;
            htracker.track(orgType, "history.type.update.name", orgType.getName(), type.getName(), type.getId(),
                    changed);
        }
        //end name change

        //start description change
        if (!orgType.getLabel().equals(type.getLabel())) {
            Database.storeFxString(type.getLabel(), con, TBL_STRUCT_TYPES, "DESCRIPTION", "ID", type.getId());
            htracker.track(orgType, "history.type.update.description", orgType.getLabel(), type.getLabel());
        }
        //end description change

        //start type mode changes
        if (type.getMode().getId() != orgType.getMode().getId()) {
            if (instanceCount < 0)
                instanceCount = getInstanceCount(con, type.getId());
            //allow relation => content (removing all relation specific entries) but content => relation requires 0 instances!
            if ((type.getMode() == TypeMode.Relation && orgType.getMode() == TypeMode.Content
                    && instanceCount > 0) || orgType.getMode() == TypeMode.Preload
                    || type.getMode() == TypeMode.Preload)
                throw new FxUpdateException("ex.structure.type.typeMode.notUpgradeable", orgType.getMode(),
                        type.getMode(), orgType.getName());
            if (type.getMode() == TypeMode.Content) {
                if (type.getRelations().size() > 0) {
                    //TODO: remove relation mappings
                    throw new FxUpdateException("ex.notImplemented", "Remove all relation mappings for type");
                }
                if (instanceCount > 0) {
                    //TODO: remove all relation specific entries for existing contents
                    throw new FxUpdateException("ex.notImplemented",
                            "Remove all relation specific entries for existing contents");
                }
            }
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET TYPE_MODE=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getMode().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.typeMode", orgType.getMode(), type.getMode());
        }
        //end type mode changes

        //start relation changes
        if (type.getAddedRelations().size() > 0) {
            sql.setLength(0);
            sql.append("INSERT INTO ").append(TBL_STRUCT_TYPERELATIONS)
                    .append(" (TYPEDEF,TYPESRC,TYPEDST,MAXSRC,MAXDST)VALUES(?,?,?,?,?)");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getId());
            for (FxTypeRelation rel : type.getAddedRelations()) {
                if (rel.getSource().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getSource().getName());
                if (rel.getDestination().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getDestination().getName());
                ps.setLong(2, rel.getSource().getId());
                ps.setLong(3, rel.getDestination().getId());
                ps.setLong(4, rel.getMaxSource());
                ps.setLong(5, rel.getMaxDestination());
                ps.addBatch();
                htracker.track(type, "history.type.update.relation.add", type.getName(),
                        rel.getSource().getName(), rel.getMaxSource(), rel.getDestination().getName(),
                        rel.getMaxDestination());
            }
            ps.executeBatch();
        }
        if (type.getUpdatedRelations().size() > 0) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPERELATIONS).
            //                  1        2               3             4             5
                    append(" SET MAXSRC=?,MAXDST=? WHERE TYPEDEF=? AND TYPESRC=? AND TYPEDST=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(3, type.getId());
            for (FxTypeRelation rel : type.getUpdatedRelations()) {
                if (rel.getSource().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getSource().getName());
                if (rel.getDestination().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getDestination().getName());
                //TODO: check if maxSource/maxDestination is not violated if > 0
                ps.setLong(4, rel.getSource().getId());
                ps.setLong(5, rel.getDestination().getId());
                ps.setLong(1, rel.getMaxSource());
                ps.setLong(2, rel.getMaxDestination());
                ps.addBatch();
                htracker.track(type, "history.type.update.relation.update", type.getName(),
                        rel.getSource().getName(), rel.getMaxSource(), rel.getDestination().getName(),
                        rel.getMaxDestination());
            }
            ps.executeBatch();
        }
        if (type.getRemovedRelations().size() > 0) {
            sql.setLength(0);
            sql.append("DELETE FROM ").append(TBL_STRUCT_TYPERELATIONS).
            //                     1            2              3
                    append(" WHERE TYPEDEF=? AND TYPESRC=? AND TYPEDST=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getId());
            for (FxTypeRelation rel : type.getRemovedRelations()) {
                if (rel.getSource().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getSource().getName());
                if (rel.getDestination().isRelation())
                    throw new FxInvalidParameterException("ex.structure.type.relation.wrongTarget",
                            type.getName(), rel.getDestination().getName());
                int[] rels = getRelationCount(con, type.getId(), rel.getSource().getId(),
                        rel.getDestination().getId());
                if (!type.isRemoveInstancesWithRelationTypes() && rels[0] > 0)
                    throw new FxRemoveException("ex.structure.type.relation.relationsExist", type.getName(),
                            rel.getSource().getName(), rel.getDestination().getName(), rels[0]);
                else if (type.isRemoveInstancesWithRelationTypes() && rels[0] > 0) {
                    removeRelationEntries(con, type.getId(), rel.getSource().getId(),
                            rel.getDestination().getId());
                }
                ps.setLong(2, rel.getSource().getId());
                ps.setLong(3, rel.getDestination().getId());
                ps.addBatch();
                htracker.track(type, "history.type.update.relation.remove", type.getName(),
                        rel.getSource().getName(), rel.getMaxSource(), rel.getDestination().getName(),
                        rel.getMaxDestination());
            }
            ps.executeBatch();
        }
        //end relation changes

        //start ACL changes
        if (!type.getACL().equals(orgType.getACL())) {
            if (type.getACL().getCategory() != ACLCategory.STRUCTURE)
                throw new FxInvalidParameterException("ACL", "ex.acl.category.invalid",
                        type.getACL().getCategory(), ACLCategory.STRUCTURE);
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET ACL=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getACL().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.acl", orgType.getACL(), type.getACL());
        }
        //end ACL changes

        //start default instance ACL changes
        if (type.hasDefaultInstanceACL() != orgType.hasDefaultInstanceACL()
                || !type.getDefaultInstanceACL().equals(orgType.getDefaultInstanceACL())) {
            if (type.hasDefaultInstanceACL()
                    && type.getDefaultInstanceACL().getCategory() != ACLCategory.INSTANCE)
                throw new FxInvalidParameterException("DEFACL", "ex.acl.category.invalid",
                        type.getDefaultInstanceACL().getCategory(), ACLCategory.INSTANCE);
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET DEFACL=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            if (type.hasDefaultInstanceACL())
                ps.setLong(1, type.getDefaultInstanceACL().getId());
            else
                ps.setNull(1, java.sql.Types.INTEGER);
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.defacl",
                    orgType.hasDefaultInstanceACL() ? orgType.getACL() : "-",
                    type.hasDefaultInstanceACL() ? type.getDefaultInstanceACL() : "-");
        }
        //end default instance ACL changes

        //start Workflow changes
        if (!type.getWorkflow().equals(orgType.getWorkflow())) {

            if (instanceCount < 0)
                instanceCount = getInstanceCount(con, type.getId());
            if (instanceCount > 0) {
                //Workflow can not be changed with existing instances -> there is no way to reliably
                //map steps of one workflow to steps of another (even not using stepdefinitions since they
                //can be used multiple times). A possible solution would be to provide a mapping when changing
                //workflows but this should be to seldom the case to bother implementing it
                throw new FxUpdateException("ex.notImplemented", "Workflow changes with existing instance");
            }
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET WORKFLOW=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getWorkflow().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.workflow", orgType.getWorkflow(), type.getWorkflow());
        }
        //end Workflow changes

        //start Category changes
        if (!type.getCategory().equals(orgType.getCategory())) {
            if (!ticket.isGlobalSupervisor())
                throw new FxUpdateException("ex.structure.type.category.notSupervisor", orgType.getCategory(),
                        type.getCategory(), orgType.getName());
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET CATEGORY=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setInt(1, type.getCategory().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
        }
        //end Category changes

        //start language mode changes
        if (!type.getLanguage().equals(orgType.getLanguage())) {
            if (instanceCount < 0)
                instanceCount = getInstanceCount(con, type.getId());
            if (instanceCount <= 0 || orgType.getLanguage().isUpgradeable(type.getLanguage())) {
                sql.setLength(0);
                sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET LANG_MODE=? WHERE ID=?");
                if (ps != null)
                    ps.close();
                ps = con.prepareStatement(sql.toString());
                ps.setInt(1, type.getLanguage().getId());
                ps.setLong(2, type.getId());
                ps.executeUpdate();
                htracker.track(type, "history.type.update.languageMode", orgType.getLanguage().name(),
                        type.getLanguage().name());
            } else
                throw new FxUpdateException("ex.structure.type.languageMode.notUpgradeable",
                        orgType.getLanguage(), type.getLanguage(), orgType.getName());
        }
        //end language mode changes

        //start state changes
        if (type.getState().getId() != orgType.getState().getId()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET TYPE_STATE=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setInt(1, type.getState().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.state", orgType.getState().name(),
                    type.getState().name());
        }
        //end state changes

        //start permission changes
        if (type.getBitCodedPermissions() != orgType.getBitCodedPermissions()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET SECURITY_MODE=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setInt(1, type.getBitCodedPermissions());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.perm",
                    FxPermissionUtils.toString(orgType.getBitCodedPermissions()),
                    FxPermissionUtils.toString(type.getBitCodedPermissions()));
        }
        //end permission changes

        //start multiple ACL setting changes
        if (type.isMultipleContentACLs() != orgType.isMultipleContentACLs()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET MULTIPLE_CONTENT_ACLS=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setBoolean(1, type.isMultipleContentACLs());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.multipleContentACLs", orgType.isMultipleContentACLs(),
                    type.isMultipleContentACLs());
        }
        //end multiple ACL setting changes

        //start isIncludedInSupertypeQueries setting changes
        if (type.isIncludedInSupertypeQueries() != orgType.isIncludedInSupertypeQueries()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET INSUPERTYPEQUERY=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setBoolean(1, type.isIncludedInSupertypeQueries());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.inSupertypeQueries",
                    orgType.isIncludedInSupertypeQueries(), type.isIncludedInSupertypeQueries());
        }
        //end isIncludedInSupertypeQueries setting changes

        //start history track/age changes
        if (type.isTrackHistory() != orgType.isTrackHistory()
                || type.getHistoryAge() != orgType.getHistoryAge()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES)
                    .append(" SET TRACKHISTORY=?, HISTORY_AGE=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setBoolean(1, type.isTrackHistory());
            ps.setLong(2, type.getHistoryAge());
            ps.setLong(3, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.history", orgType.isTrackHistory(), type.isTrackHistory(),
                    orgType.getHistoryAge(), type.getHistoryAge());
        }
        //end history track/age changes

        //start max.ver changes
        if (type.getMaxVersions() != orgType.getMaxVersions()) {
            //TODO: remove any versions that would exceed this count
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET MAX_VERSIONS=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getMaxVersions());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.maxVersions", orgType.getMaxVersions(),
                    type.getMaxVersions());
        }
        //end max.ver changes

        //start isAutoVersion setting changes
        if (type.isAutoVersion() != orgType.isAutoVersion()) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET AUTO_VERSION=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setBoolean(1, type.isAutoVersion());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.isAutoVersion", orgType.isAutoVersion(),
                    type.isAutoVersion());
        }
        //end isAutoVersion setting changes

        //start max source relations changes
        if (type.isRelation() && type.getMaxRelSource() != orgType.getMaxRelSource()) {
            //TODO: check if the new condition is not violated by existing data
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET REL_TOTAL_MAXSRC=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getMaxRelSource());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.maxRelSource", orgType.getMaxRelSource(),
                    type.getMaxRelSource());
        }
        //end max source relations changes

        //start max destination relations changes
        if (type.isRelation() && type.getMaxRelDestination() != orgType.getMaxRelDestination()) {
            //TODO: check if the new condition is not violated by existing data
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET REL_TOTAL_MAXDST=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            ps.setLong(1, type.getMaxRelDestination());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            htracker.track(type, "history.type.update.maxRelDest", orgType.getMaxRelDestination(),
                    type.getMaxRelDestination());
        }
        //end max destination relations changes

        //start icon
        if (!type.getIcon().equals(orgType.getIcon())) {
            sql.setLength(0);
            sql.append("UPDATE ").append(TBL_STRUCT_TYPES).append(" SET ICON_REF=? WHERE ID=?");
            if (ps != null)
                ps.close();
            ps = con.prepareStatement(sql.toString());
            if (type.getIcon().isEmpty())
                ps.setNull(1, java.sql.Types.INTEGER);
            else
                ps.setLong(1, type.getIcon().getDefaultTranslation().getId());
            ps.setLong(2, type.getId());
            ps.executeUpdate();
            needReload = true;
            htracker.track(type, "history.type.update.icon", orgType.getIcon().getDefaultTranslation().getId(),
                    type.getIcon().getDefaultTranslation().getId());
        }
        //end icon

        // structure option changes
        boolean optionsChanged = updateTypeOptions(con, type, orgType);
        // check if any type options must be propagated to derived types
        if (type.getDerivedTypes().size() > 0) {
            final List<FxStructureOption> inherit = new ArrayList<FxStructureOption>(type.getOptions().size());
            for (FxStructureOption o : type.getOptions()) {
                if (o.getIsInherited()) {
                    inherit.add(o);
                }
            }
            if (inherit.size() > 0) {
                for (FxType derived : type.getDerivedTypes()) {
                    updateDerivedTypeOptions(con, derived, inherit);
                }
            }
        }

        //sync back to cache
        try {
            if (needReload)
                StructureLoader.reload(con);
            else {
                StructureLoader.updateType(FxContext.get().getDivisionId(), loadType(con, type.getId()));
                // reload any derived types if type options have changed
                if (optionsChanged && type.getDerivedTypes().size() > 0) {
                    for (FxType derivedType : type.getDerivedTypes()) {
                        StructureLoader.updateType(FxContext.get().getDivisionId(),
                                loadType(con, derivedType.getId()));
                    }
                }
            }
        } catch (FxLoadException e) {
            throw new FxUpdateException(e);
        } catch (FxCacheException e) {
            LOG.fatal(e.getMessage(), e);
        }
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(TypeEngineBean.class, con, ps);
    }
    return type.getId();
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private SiteKey createMenu(User user, CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException, VerticalSecurityException {

    Element rootElement = doc.getDocumentElement();

    // Get site key:
    String tmp;//w w  w .java2 s  .co  m

    // Prepare insertion into the database
    SiteKey siteKey = null;
    Connection con = null;
    PreparedStatement preparedStmt = null;
    try {
        con = getConnection();

        tmp = rootElement.getAttribute("key");
        if (!useOldKey || tmp == null || tmp.length() == 0) {
            // generate key:
            siteKey = new SiteKey(getNextKey(MENU_TABLE));
        } else {
            siteKey = new SiteKey(tmp);
        }

        preparedStmt = con.prepareStatement(MENU_INSERT);

        if (copyContext != null) {
            copyContext.putMenuKey(Integer.parseInt(tmp), siteKey.toInt());
        }
        preparedStmt.setInt(1, siteKey.toInt());

        // name:
        Element tmpElement = XMLTool.getElement(rootElement, "name");
        String name = null;
        if (tmpElement != null) {
            name = XMLTool.getElementText(tmpElement);
        }
        if (name != null) {
            preparedStmt.setString(6, name);
        } else {
            preparedStmt.setNull(6, Types.VARCHAR);
        }

        // firstpage:
        tmpElement = XMLTool.getElement(rootElement, "firstpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(2, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(2, Types.INTEGER);
        }

        // loginpage:
        tmpElement = XMLTool.getElement(rootElement, "loginpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(3, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(3, Types.INTEGER);
        }

        // errorpage:
        tmpElement = XMLTool.getElement(rootElement, "errorpage");
        tmp = tmpElement.getAttribute("key");
        if (tmp != null && tmp.length() > 0) {
            preparedStmt.setInt(4, Integer.parseInt(tmp));
        } else {
            preparedStmt.setNull(4, Types.INTEGER);
        }

        // default pagetemplate:
        tmpElement = XMLTool.getElement(rootElement, "defaultpagetemplate");
        if (tmpElement != null) {
            tmp = tmpElement.getAttribute("pagetemplatekey");
            if (tmp != null && tmp.length() > 0) {
                preparedStmt.setInt(5, Integer.parseInt(tmp));
            } else {
                preparedStmt.setNull(5, Types.INTEGER);
            }
        } else {
            preparedStmt.setNull(5, Types.INTEGER);
        }

        SiteData siteData = new SiteData();

        // DeviceClassResolver:
        tmpElement = XMLTool.getElement(rootElement, "deviceclassresolver");
        if (tmpElement != null) {
            String deviceClassResolverUrl = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(deviceClassResolverUrl)) {
                siteData.setDeviceClassResolver(new ResourceKey(deviceClassResolverUrl));
            }
        }

        // Default localization resource:
        tmpElement = XMLTool.getElement(rootElement, "defaultlocalizationresource");
        if (tmpElement != null) {
            String defaultLocalizationResource = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(defaultLocalizationResource)) {
                siteData.setDefaultLocalizationResource(new ResourceKey(defaultLocalizationResource));
            }
        }

        // locale resolver
        tmpElement = XMLTool.getElement(rootElement, "localeresolver");
        if (tmpElement != null) {
            String localeResolver = tmpElement.getAttribute("key");
            if (StringUtils.isNotEmpty(localeResolver)) {
                siteData.setLocaleResolver(new ResourceKey(localeResolver));
            }
        }

        // Path to public home:
        String pathToPublicHome = rootElement.getAttribute("path-to-public-home-resources");
        if (StringUtils.isNotEmpty(pathToPublicHome)) {
            siteData.setPathToPublicResources(new ResourceKey(pathToPublicHome));
        }

        // Path to home:
        String pathToHome = rootElement.getAttribute("path-to-home-resources");
        if (StringUtils.isNotEmpty(pathToHome)) {
            siteData.setPathToResources(new ResourceKey(pathToHome));
        }

        tmpElement = XMLTool.getElement(rootElement, "menudata");
        if (tmpElement != null) {
            parseAndAddMenudataToSiteData(tmpElement, siteData);
        }

        final byte[] xmldata = siteData.getAsBytes();
        preparedStmt.setBinaryStream(7, new ByteArrayInputStream(xmldata), xmldata.length);

        // language key:
        preparedStmt.setInt(8, Integer.parseInt(rootElement.getAttribute("languagekey")));

        Element detailsElement = XMLTool.getElement(rootElement, "details");

        // Statistics URL:
        tmpElement = XMLTool.getElement(detailsElement, "statistics");
        if (tmpElement != null) {
            String statisticsURL = XMLTool.getElementText(tmpElement);
            if (statisticsURL != null) {
                preparedStmt.setString(9, statisticsURL);
            } else {
                preparedStmt.setNull(9, Types.VARCHAR);
            }
        } else {
            preparedStmt.setNull(9, Types.VARCHAR);
        }

        // Run As User:
        String runAsUserKey = rootElement.getAttribute("runas");
        if (StringUtils.isNotEmpty(runAsUserKey)) {
            preparedStmt.setString(10, runAsUserKey);
        } else {
            preparedStmt.setNull(10, Types.VARCHAR);
        }

        // insert the data:
        preparedStmt.executeUpdate();

        // create default menu access rights
        GroupHandler groupHandler = getGroupHandler();
        String groupKey = groupHandler.getAdminGroupKey();

        Document tmpDoc = XMLTool.createDocument("accessrights");
        Element root = tmpDoc.getDocumentElement();
        root.setAttribute("type", String.valueOf(AccessRight.MENUITEM_DEFAULT));
        root.setAttribute("key", String.valueOf(siteKey));

        Element accessrightElem = XMLTool.createElement(tmpDoc, root, "accessright");
        accessrightElem.setAttribute("groupkey", groupKey);
        accessrightElem.setAttribute("grouptype", GroupType.ADMINS.toInteger().toString());

        accessrightElem.setAttribute("read", "true");
        accessrightElem.setAttribute("create", "true");
        accessrightElem.setAttribute("update", "true");
        accessrightElem.setAttribute("delete", "true");
        accessrightElem.setAttribute("publish", "true");
        accessrightElem.setAttribute("add", "true");
        accessrightElem.setAttribute("administrate", "true");

        getSecurityHandler().updateAccessRights(user, tmpDoc);

        //////// Create menuitems:
        Element itemsElement = XMLTool.getElement(rootElement, "menuitems");
        if (itemsElement != null) {
            Element[] itemElems = XMLTool.getElements(itemsElement);

            for (int i = 0; i < itemElems.length; i++) {
                createMenuItem(user, copyContext, itemElems[i], siteKey, i, null, useOldKey);
            }
        }
    } catch (SQLException sqle) {
        String msg = "Failed to create menu: %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, msg, sqle);
    } catch (VerticalKeyException gke) {
        String msg = "Unable to generate key for table %0.";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, msg, MENU_TABLE, gke);
    } catch (VerticalUpdateException e) {
        VerticalEngineLogger.errorCreate(this.getClass(), 10, "Error creating default access rights: %t", e);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return siteKey;
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleContactListTable.java

public void updateContactList(CFAccAuthorization Authorization, CFAccContactListBuff Buff) {
    final String S_ProcName = "updateContactList";
    ResultSet resultSet = null;//from w w  w .j  a v a 2  s. c  om
    Connection cnx = schema.getCnx();
    CallableStatement stmtUpdateByPKey = null;
    List<CFAccContactListBuff> buffList = new LinkedList<CFAccContactListBuff>();
    try {
        long ContactListId = Buff.getRequiredContactListId();
        long TenantId = Buff.getRequiredTenantId();
        String Description = Buff.getRequiredDescription();
        Integer StripDigits = Buff.getOptionalStripDigits();
        int Revision = Buff.getRequiredRevision();
        stmtUpdateByPKey = cnx
                .prepareCall("begin " + schema.getLowerSchemaDbName() + ".upd_ctclst( ?, ?, ?, ?, ?, ?, ?"
                        + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "?" + ", " + "? ); end;");
        int argIdx = 1;
        stmtUpdateByPKey.registerOutParameter(argIdx++, OracleTypes.CURSOR);
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtUpdateByPKey.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtUpdateByPKey.setLong(argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
        stmtUpdateByPKey.setString(argIdx++, "CTL");
        stmtUpdateByPKey.setLong(argIdx++, ContactListId);
        stmtUpdateByPKey.setLong(argIdx++, TenantId);
        stmtUpdateByPKey.setString(argIdx++, Description);
        if (StripDigits != null) {
            stmtUpdateByPKey.setInt(argIdx++, StripDigits.intValue());
        } else {
            stmtUpdateByPKey.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        stmtUpdateByPKey.setInt(argIdx++, Revision);
        stmtUpdateByPKey.execute();
        resultSet = (ResultSet) stmtUpdateByPKey.getObject(1);
        if (resultSet != null) {
            try {
                if (resultSet.next()) {
                    CFAccContactListBuff updatedBuff = unpackContactListResultSetToBuff(resultSet);
                    if (resultSet.next()) {
                        resultSet.last();
                        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                                "Did not expect multi-record response, " + resultSet.getRow()
                                        + " rows selected");
                    }
                    Buff.setRequiredDescription(updatedBuff.getRequiredDescription());
                    Buff.setOptionalStripDigits(updatedBuff.getOptionalStripDigits());
                    Buff.setRequiredRevision(updatedBuff.getRequiredRevision());
                } else {
                    throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                            "Expected a single-record response, " + resultSet.getRow() + " rows selected");
                }
            } catch (SQLException e) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "upd_ctclst() did not return a valid result cursor");
            } finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                    }
                    resultSet = null;
                }
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "upd_ctclst() did not return a result cursor");
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
        if (stmtUpdateByPKey != null) {
            try {
                stmtUpdateByPKey.close();
            } catch (SQLException e) {
            }
            stmtUpdateByPKey = null;
        }
    }
}

From source file:net.sourceforge.msscodefactory.cfcrm.v2_1.CFCrmMSSql.CFCrmMSSqlAttachmentTable.java

public CFCrmAttachmentBuff[] readBuffByMimeTypeIdx(CFCrmAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;/*from w  w w . j av  a  2 s. c o  m*/
    try {
        Connection cnx = schema.getCnx();
        String sql = "{ call sp_read_attchmnt_by_mimetypeidx( ?, ?, ?, ?, ?" + ", " + "?" + " ) }";
        if (stmtReadBuffByMimeTypeIdx == null) {
            stmtReadBuffByMimeTypeIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecTenantId());
        if (MimeTypeId != null) {
            stmtReadBuffByMimeTypeIdx.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtReadBuffByMimeTypeIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        resultSet = stmtReadBuffByMimeTypeIdx.executeQuery();
        List<CFCrmAttachmentBuff> buffList = new LinkedList<CFCrmAttachmentBuff>();
        if (resultSet != null) {
            while (resultSet.next()) {
                CFCrmAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
                buffList.add(buff);
            }
        }
        int idx = 0;
        CFCrmAttachmentBuff[] retBuff = new CFCrmAttachmentBuff[buffList.size()];
        Iterator<CFCrmAttachmentBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private static int getColumnType(Class<?> javaType, Method method, ColumnMetadata foreignReference) {
    final int dimensions = ReflectionUtils.getArrayDimensions(javaType);
    javaType = ReflectionUtils.mapType(ReflectionUtils.getComponentType(javaType));
    if (dimensions > 1) {
        throw new UnsupportedColumnTypeError("Arrays of dimension > 1 are not supported");
    }/*from  w w  w.j a  v a  2s  .  c  o  m*/
    if (Byte.class.equals(javaType) && dimensions == 0) {
        return Types.TINYINT;
    } else if (Short.class.equals(javaType)) {
        return Types.SMALLINT;
    } else if (Integer.class.equals(javaType)) {
        return Types.INTEGER;
    } else if (Long.class.equals(javaType)) {
        return Types.BIGINT;
    } else if (Float.class.equals(javaType)) {
        return Types.FLOAT;
    } else if (Double.class.equals(javaType)) {
        return Types.DOUBLE;
    } else if (BigDecimal.class.equals(javaType)) {
        return Types.DECIMAL;
    } else if (BigInteger.class.equals(javaType)) {
        return Types.NUMERIC;
    } else if (Character.class.equals(javaType)) {
        return Types.CHAR;
    } else if (String.class.equals(javaType) || Class.class.equals(javaType)) {
        if (method != null && method.isAnnotationPresent(Column.class)
                && method.getAnnotation(Column.class).length() > 0) {
            return Types.VARCHAR;
        } else {
            return Types.LONGVARCHAR;
        }
    } else if (Date.class.isAssignableFrom(javaType)) {
        if (javaType.equals(java.sql.Date.class)) {
            return Types.DATE;
        } else if (javaType.equals(Time.class)) {
            return Types.TIME;
        } else if (javaType.equals(java.sql.Timestamp.class)) {
            return Types.TIMESTAMP;
        }
        final TemporalType temporalType = method != null && method.isAnnotationPresent(Temporal.class)
                ? method.getAnnotation(Temporal.class).value()
                : null;
        return (temporalType == null || temporalType.equals(TemporalType.TIMESTAMP)) ? Types.TIMESTAMP
                : (temporalType.equals(TemporalType.DATE) ? Types.DATE : Types.TIME);
    } else if (Byte.class.equals(javaType) && dimensions > 0) {
        return Types.VARBINARY;
    } else if (Enum.class.isAssignableFrom(javaType)) {
        return Types.VARCHAR;
    } else if (Boolean.class.equals(javaType)) {
        return Types.BOOLEAN;
    } else if (Collection.class.isAssignableFrom(javaType)
            && method.isAnnotationPresent(BasicCollection.class)) {
        return Types.LONGVARCHAR;
    }
    if (foreignReference != null) {
        return Integer.MIN_VALUE;
    }
    return Types.LONGVARCHAR;
}

From source file:net.sourceforge.msscodefactory.cfcrm.v2_1.CFCrmMySql.CFCrmMySqlAttachmentTable.java

public CFCrmAttachmentBuff[] readBuffByMimeTypeIdx(CFCrmAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;//www. j a va 2  s.  co m
    try {
        Connection cnx = schema.getCnx();
        String sql = "call " + schema.getLowerDbSchemaName() + ".sp_read_attchmnt_by_mimetypeidx( ?, ?, ?, ?, ?"
                + ", " + "?" + " )";
        if (stmtReadBuffByMimeTypeIdx == null) {
            stmtReadBuffByMimeTypeIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecTenantId());
        if (MimeTypeId != null) {
            stmtReadBuffByMimeTypeIdx.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtReadBuffByMimeTypeIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        try {
            resultSet = stmtReadBuffByMimeTypeIdx.executeQuery();
        } catch (SQLException e) {
            if (e.getErrorCode() != 1329) {
                throw e;
            }
            resultSet = null;
        }
        List<CFCrmAttachmentBuff> buffList = new LinkedList<CFCrmAttachmentBuff>();
        while ((resultSet != null) && resultSet.next()) {
            CFCrmAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
            buffList.add(buff);
        }
        int idx = 0;
        CFCrmAttachmentBuff[] retBuff = new CFCrmAttachmentBuff[buffList.size()];
        Iterator<CFCrmAttachmentBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * This method will insert a database entry and <b>SHOULD</b> run asynchronously
 *
 * @param offlinePlayer player to be muted
 * @param moderator     the administrator that muted the player, can be null (Console)
 * @param reason        the reason to be muted
 * @param muteDuration  duration to be muted
 * @return a response to send to the administrator
 *///from   w ww . jav  a 2 s.c o m
public MuteResponse mutePlayer(@NotNull OfflinePlayer offlinePlayer, @Nullable OnlinePlayer moderator,
        @NotNull final String reason, @NotNull final long muteDuration) {
    // Check if player is registered
    if (!offlinePlayer.isRegistered())
        return MuteResponse.PLAYER_NOT_REGISTERED;

    // Set variables
    int playerId = offlinePlayer.getPlayerId();
    long recordDate = System.currentTimeMillis();
    long unmuteDate = recordDate + muteDuration;

    // Check if reason has right size
    if (!Util.checkStringLength(reason, 4, 128))
        return MuteResponse.INVALID_REASON_LENGTH;

    try {
        // Retrieve connection
        Connection connection = LobsterCraft.dataSource.getConnection();

        // Prepare statement
        PreparedStatement preparedStatement = connection.prepareStatement(
                "INSERT INTO `minecraft`.`mod_muted_players`(`user_mutedId`, `user_moderatorId`, `muteDate`, `unmuteDate`, `reason`) VALUES (?, ?, ?, ?, ?);",
                Statement.RETURN_GENERATED_KEYS);

        // Set variables for query
        preparedStatement.setInt(1, playerId);
        if (moderator != null)
            preparedStatement.setInt(2, moderator.getOfflinePlayer().getPlayerId()); // will write null if is null
        else
            preparedStatement.setNull(2, Types.INTEGER);
        preparedStatement.setLong(3, recordDate);
        preparedStatement.setLong(4, unmuteDate);
        preparedStatement.setString(5, reason);

        // Execute statement
        preparedStatement.execute();

        // Retrieve generated keys
        ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

        // Throw error if there is no generated key
        if (!generatedKeys.next())
            throw new SQLException("There is no generated key");

        // Create entry
        MutePlayerEntry mutedPlayerEntry = new MutePlayerEntry(generatedKeys.getLong("mute_index"),
                moderator != null ? moderator.getOfflinePlayer().getPlayerId() : null, recordDate, unmuteDate,
                reason);

        // Add entry to storage
        synchronized (playerMuteEntries) {
            playerMuteEntries.putIfAbsent(playerId, new HashSet<>());
            playerMuteEntries.get(playerId).add(mutedPlayerEntry);
        }

        // Close everything
        generatedKeys.close();
        preparedStatement.close();
        connection.close();

        // Check if player is online and warn him
        OnlinePlayer onlinePlayer = offlinePlayer.getOnlinePlayer(null);
        if (onlinePlayer != null) {
            StringBuilder stringBuilder = new StringBuilder("cVoc foi silenciado");
            if (moderator != null)
                stringBuilder.append(" por ").append(moderator.getPlayer().getDisplayName());
            stringBuilder.append("c at ").append(Util.formatDate(unmuteDate)).append('\n')
                    .append("pela razo: 4\"").append(reason).append('\"');
            onlinePlayer.getPlayer().sendMessage(stringBuilder.toString());
        }

        return MuteResponse.SUCCESSFULLY_EXECUTED;
    } catch (SQLException exception) {
        exception.printStackTrace();
        return MuteResponse.ERROR_OCCURRED;
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccMSSql.CFAccMSSqlAttachmentTable.java

public CFAccAttachmentBuff[] readBuffByMimeTypeIdx(CFAccAuthorization Authorization, Integer MimeTypeId) {
    final String S_ProcName = "readBuffByMimeTypeIdx";
    ResultSet resultSet = null;/* w w  w.  java  2s. c  o  m*/
    try {
        Connection cnx = schema.getCnx();
        String sql = "{ call sp_read_attchmnt_by_mimetypeidx( ?, ?, ?, ?, ?" + ", " + "?" + " ) }";
        if (stmtReadBuffByMimeTypeIdx == null) {
            stmtReadBuffByMimeTypeIdx = cnx.prepareStatement(sql);
        }
        int argIdx = 1;
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecUserId().toString());
        stmtReadBuffByMimeTypeIdx.setString(argIdx++,
                (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecClusterId());
        stmtReadBuffByMimeTypeIdx.setLong(argIdx++,
                (Authorization == null) ? 0 : Authorization.getSecTenantId());
        if (MimeTypeId != null) {
            stmtReadBuffByMimeTypeIdx.setInt(argIdx++, MimeTypeId.intValue());
        } else {
            stmtReadBuffByMimeTypeIdx.setNull(argIdx++, java.sql.Types.INTEGER);
        }
        resultSet = stmtReadBuffByMimeTypeIdx.executeQuery();
        List<CFAccAttachmentBuff> buffList = new LinkedList<CFAccAttachmentBuff>();
        if (resultSet != null) {
            while (resultSet.next()) {
                CFAccAttachmentBuff buff = unpackAttachmentResultSetToBuff(resultSet);
                buffList.add(buff);
            }
        }
        int idx = 0;
        CFAccAttachmentBuff[] retBuff = new CFAccAttachmentBuff[buffList.size()];
        Iterator<CFAccAttachmentBuff> iter = buffList.iterator();
        while (iter.hasNext()) {
            retBuff[idx++] = iter.next();
        }
        return (retBuff);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            }
            resultSet = null;
        }
    }
}

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

/**
 * Import data from a zip archive to a database table
 *
 * @param stmt               statement to use
 * @param zip                zip archive containing the zip entry
 * @param ze                 zip entry within the archive
 * @param xpath              xpath containing the entries to import
 * @param table              name of the table
 * @param executeInsertPhase execute the insert phase?
 * @param executeUpdatePhase execute the update phase?
 * @param updateColumns      columns that should be set to <code>null</code> in a first pass (insert)
 *                           and updated to the provided values in a second pass (update),
 *                           columns that should be used in the where clause have to be prefixed
 *                           with "KEY:", to assign a default value use the expression "columnname:default value",
 *                           if the default value is "@", it will be a negative counter starting at 0, decreasing.
 *                           If the default value starts with "%", it will be set to the column following the "%"
 *                           character in the first pass
 * @throws Exception on errors//ww w .  ja  v a 2s  .co  m
 */
protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath,
        final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase,
        final String... updateColumns) throws Exception {
    //analyze the table
    final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
    StringBuilder sbInsert = new StringBuilder(500);
    StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null;
    if (rs == null)
        throw new IllegalArgumentException("Can not analyze table [" + table + "]!");
    sbInsert.append("INSERT INTO ").append(table).append(" (");
    final ResultSetMetaData md = rs.getMetaData();
    final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0
            ? new HashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0
            ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null;
    //preset to a referenced column (%column syntax)
    final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10)
            : null;
    final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null;
    final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>(
            md.getColumnCount() + (counters != null ? counters.size() : 0));
    int insertIndex = 1;
    int updateSetIndex = 1;
    int updateClauseIndex = 1;
    boolean first = true;
    for (int i = 0; i < md.getColumnCount(); i++) {
        final String currCol = md.getColumnName(i + 1).toLowerCase();
        if (updateColumns.length > 0) {
            boolean abort = false;
            for (String col : updateColumns) {
                if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) {
                    String value = col.substring(col.indexOf(':') + 1);
                    col = col.substring(0, col.indexOf(':'));
                    if ("@".equals(value)) {
                        if (currCol.equalsIgnoreCase(col)) {
                            counters.put(col, 0);
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                        }
                    } else if (value.startsWith("%")) {
                        if (currCol.equalsIgnoreCase(col)) {
                            presetRefColumns.put(col, value.substring(1));
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                            //                                System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1));
                        }
                    } else if (!presetColumns.containsKey(col))
                        presetColumns.put(col, value);
                }
                if (currCol.equalsIgnoreCase(col)) {
                    abort = true;
                    updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++));
                    break;
                }
            }
            if (abort)
                continue;
        }
        if (first) {
            first = false;
        } else
            sbInsert.append(',');
        sbInsert.append(currCol);
        insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
    }
    if (updateColumns.length > 0 && executeUpdatePhase) {
        sbUpdate.append("UPDATE ").append(table).append(" SET ");
        int counter = 0;
        for (String updateColumn : updateSetColumns.keySet()) {
            if (counter++ > 0)
                sbUpdate.append(',');
            sbUpdate.append(updateColumn).append("=?");
        }
        sbUpdate.append(" WHERE ");
        boolean hasKeyColumn = false;
        for (String col : updateColumns) {
            if (!col.startsWith("KEY:"))
                continue;
            hasKeyColumn = true;
            String keyCol = col.substring(4);
            for (int i = 0; i < md.getColumnCount(); i++) {
                if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol))
                    continue;
                updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++));
                sbUpdate.append(keyCol).append("=? AND ");
                break;
            }

        }
        if (!hasKeyColumn)
            throw new IllegalArgumentException("Update columns require a KEY!");
        sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND "
        //"shift" clause indices
        for (String col : updateClauseColumns.keySet()) {
            GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col);
            ci.index += (updateSetIndex - 1);
        }
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(key);
    }
    sbInsert.append(")VALUES(");
    for (int i = 0; i < insertColumns.size(); i++) {
        if (i > 0)
            sbInsert.append(',');
        sbInsert.append('?');
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(presetColumns.get(key));
    }
    sbInsert.append(')');
    if (DBG) {
        LOG.info("Insert statement:\n" + sbInsert.toString());
        if (updateColumns.length > 0)
            LOG.info("Update statement:\n" + sbUpdate.toString());
    }
    //build a map containing all nodes that require attributes
    //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data"
    final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5);
    for (String pElem : xpath.split("/")) {
        if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0))
            continue;
        List<String> att = new ArrayList<String>(5);
        for (String pAtt : pElem.split("@")) {
            if (!(pAtt.indexOf('=') > 0))
                continue;
            att.add(pAtt.substring(0, pAtt.indexOf('=')));
        }
        queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att);
    }
    final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString());
    final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase
            ? stmt.getConnection().prepareStatement(sbUpdate.toString())
            : null;
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            int counter;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            boolean insertMode = true;

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

            /**
             * {@inheritDoc}
             */
            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                if (target != null && target.startsWith("fx_")) {
                    if (target.equals("fx_mode"))
                        insertMode = "insert".equals(data);
                } else
                    super.processingInstruction(target, data);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                if (insertMode)
                    LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath
                            + "]");
                else
                    LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpath)) {
                    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 {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            private void pushPath(String qName, Attributes att) {
                if (att.getLength() > 0 && queryAttributes.containsKey(qName)) {
                    String curr = qName + "[";
                    boolean first = true;
                    final List<String> attList = queryAttributes.get(qName);
                    for (int i = 0; i < att.getLength(); i++) {
                        if (!attList.contains(att.getQName(i)))
                            continue;
                        if (first)
                            first = false;
                        else
                            curr += ',';
                        curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'";
                    }
                    curr += ']';
                    path.add(curr);
                } else
                    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(xpath)) {
                    if (DBG)
                        LOG.info("Insert [" + xpath + "]: [" + data + "]");
                    inTag = false;
                    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);
            }

            /**
             * Process a column set
             *
             * @param columns the columns to process
             * @param ps prepared statement to use
             * @return if data other than <code>null</code> has been set
             * @throws SQLException on errors
             * @throws ParseException on date/time conversion errors
             */
            private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps)
                    throws SQLException, ParseException {
                boolean dataSet = false;
                for (String col : columns.keySet()) {
                    ColumnInfo ci = columns.get(col);
                    String value = data.get(col);
                    if (insertMode && counters != null && counters.get(col) != null) {
                        final int newVal = counters.get(col) - 1;
                        value = String.valueOf(newVal);
                        counters.put(col, newVal);
                        //                            System.out.println("new value for " + col + ": " + newVal);
                    }
                    if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) {
                        value = data.get(presetRefColumns.get(col));
                        //                            System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]");
                    }

                    if (value == null)
                        ps.setNull(ci.index, ci.columnType);
                    else {
                        dataSet = true;
                        switch (ci.columnType) {
                        case Types.BIGINT:
                        case Types.NUMERIC:
                            if (DBG)
                                LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value));
                            ps.setBigDecimal(ci.index, new BigDecimal(value));
                            break;
                        case java.sql.Types.DOUBLE:
                            if (DBG)
                                LOG.info("Double " + ci.index + "->" + Double.parseDouble(value));
                            ps.setDouble(ci.index, Double.parseDouble(value));
                            break;
                        case java.sql.Types.FLOAT:
                        case java.sql.Types.REAL:
                            if (DBG)
                                LOG.info("Float " + ci.index + "->" + Float.parseFloat(value));
                            ps.setFloat(ci.index, Float.parseFloat(value));
                            break;
                        case java.sql.Types.TIMESTAMP:
                        case java.sql.Types.DATE:
                            if (DBG)
                                LOG.info("Timestamp/Date " + ci.index + "->"
                                        + FxFormatUtils.getDateTimeFormat().parse(value));
                            ps.setTimestamp(ci.index,
                                    new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime()));
                            break;
                        case Types.TINYINT:
                        case Types.SMALLINT:
                            if (DBG)
                                LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value));
                            ps.setInt(ci.index, Integer.valueOf(value));
                            break;
                        case Types.INTEGER:
                        case Types.DECIMAL:
                            try {
                                if (DBG)
                                    LOG.info("Long " + ci.index + "->" + Long.valueOf(value));
                                ps.setLong(ci.index, Long.valueOf(value));
                            } catch (NumberFormatException e) {
                                //Fallback (temporary) for H2 if the reported long is a big decimal (tree...)
                                ps.setBigDecimal(ci.index, new BigDecimal(value));
                            }
                            break;
                        case Types.BIT:
                        case Types.CHAR:
                        case Types.BOOLEAN:
                            if (DBG)
                                LOG.info("Boolean " + ci.index + "->" + value);
                            if ("1".equals(value) || "true".equals(value))
                                ps.setBoolean(ci.index, true);
                            else
                                ps.setBoolean(ci.index, false);
                            break;
                        case Types.LONGVARBINARY:
                        case Types.VARBINARY:
                        case Types.BLOB:
                        case Types.BINARY:
                            ZipEntry bin = zip.getEntry(value);
                            if (bin == null) {
                                LOG.error("Failed to lookup binary [" + value + "]!");
                                ps.setNull(ci.index, ci.columnType);
                                break;
                            }
                            try {
                                ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize());
                            } catch (IOException e) {
                                LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e);
                            }
                            break;
                        case Types.CLOB:
                        case Types.LONGVARCHAR:
                        case Types.VARCHAR:
                        case SQL_LONGNVARCHAR:
                        case SQL_NCHAR:
                        case SQL_NCLOB:
                        case SQL_NVARCHAR:
                            if (DBG)
                                LOG.info("String " + ci.index + "->" + value);
                            ps.setString(ci.index, value);
                            break;
                        default:
                            LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]");
                        }
                    }
                }
                return dataSet;
            }

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

        };
        handler.processingInstruction("fx_mode", "insert");
        parser.parse(zip.getInputStream(ze), handler);
        if (updateColumns.length > 0 && executeUpdatePhase) {
            handler.processingInstruction("fx_mode", "update");
            parser.parse(zip.getInputStream(ze), handler);
        }
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate);
    }
}