Example usage for java.sql PreparedStatement executeBatch

List of usage examples for java.sql PreparedStatement executeBatch

Introduction

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

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

/**
 * This method inserts data into the data table. If any data points in the
 * list fail to get added (e.g. because of a constraint violation), it will
 * be returned in the result list.//from w  w w . j a  v  a 2 s .c  o m
 * 
 * @param conn The connection.
 * @param data The data points to insert.
 * @param continueOnSQLException <code>true</code> to continue inserting the
 *        rest of the data points even after a <code>SQLException</code>
 *        occurs; <code>false</code> to throw the <code>SQLException</code>.
 * @return The list of data points that were not inserted.
 * @throws SQLException only if there is an exception for one of the data
 *         point batch inserts and <code>continueOnSQLException</code> is
 *         set to <code>false</code>.
 */
private List<DataPoint> insertData(Connection conn, List<DataPoint> data, boolean continueOnSQLException)
        throws SQLException {
    PreparedStatement stmt = null;
    final List<DataPoint> left = new ArrayList<DataPoint>();
    final Map<String, List<DataPoint>> buckets = MeasRangeObj.getInstance().bucketData(data);
    final HQDialect dialect = measurementDAO.getHQDialect();
    final boolean supportsDupInsStmt = dialect.supportsDuplicateInsertStmt();
    final boolean supportsPLSQL = dialect.supportsPLSQL();
    final StringBuilder buf = new StringBuilder();
    for (final Entry<String, List<DataPoint>> entry : buckets.entrySet()) {
        buf.setLength(0);
        final String table = entry.getKey();
        final List<DataPoint> dpts = entry.getValue();
        try {
            if (supportsDupInsStmt) {
                stmt = conn.prepareStatement(buf.append("INSERT INTO ").append(table)
                        .append(" (measurement_id, timestamp, value) VALUES (?, ?, ?)")
                        .append(" ON DUPLICATE KEY UPDATE value = ?").toString());
            } else if (supportsPLSQL) {
                final String sql = PLSQL.replaceAll(":table", table);
                stmt = conn.prepareStatement(sql);
            } else {
                stmt = conn.prepareStatement(buf.append("INSERT INTO ").append(table)
                        .append(" (measurement_id, timestamp, value) VALUES (?, ?, ?)").toString());
            }
            // TODO need to set synchronous commit to off
            for (DataPoint pt : dpts) {
                Integer metricId = pt.getMeasurementId();
                MetricValue val = pt.getMetricValue();
                BigDecimal bigDec;
                bigDec = new BigDecimal(val.getValue());
                stmt.setInt(1, metricId.intValue());
                stmt.setLong(2, val.getTimestamp());
                stmt.setBigDecimal(3, getDecimalInRange(bigDec, metricId));
                if (supportsDupInsStmt) {
                    stmt.setBigDecimal(4, getDecimalInRange(bigDec, metricId));
                } else if (supportsPLSQL) {
                    stmt.setBigDecimal(4, getDecimalInRange(bigDec, metricId));
                    stmt.setLong(5, val.getTimestamp());
                    stmt.setInt(6, metricId.intValue());
                }
                stmt.addBatch();
            }
            int[] execInfo = stmt.executeBatch();
            left.addAll(getRemainingDataPoints(dpts, execInfo));
        } catch (BatchUpdateException e) {
            if (!continueOnSQLException) {
                throw e;
            }
            left.addAll(getRemainingDataPointsAfterBatchFail(dpts, e.getUpdateCounts()));
        } catch (SQLException e) {
            if (!continueOnSQLException) {
                throw e;
            }
            // If the batch insert is not within a transaction, then we
            // don't know which of the inserts completed successfully.
            // Assume they all failed.
            left.addAll(dpts);
            if (log.isDebugEnabled()) {
                log.debug("A general SQLException occurred during the insert. " + "Assuming that none of the "
                        + dpts.size() + " data points were inserted.", e);
            }
        } finally {
            DBUtil.closeStatement(LOG_CTX, stmt);
        }
    }
    return left;
}

From source file:com.oltpbenchmark.benchmarks.tpcc.TPCCLoader.java

protected int loadStock(int whseKount, int itemKount) {

    int k = 0;//from ww  w  . j a v a  2  s  .c  o  m
    int t = 0;
    int randPct = 0;
    int len = 0;
    int startORIGINAL = 0;

    try {

        PreparedStatement stckPrepStmt = getInsertStatement(TPCCConstants.TABLENAME_STOCK);

        now = new java.util.Date();
        t = (whseKount * itemKount);
        LOG.debug("\nStart Stock Load for " + t + " units @ " + now + " ...");

        if (outputFiles == true) {
            out = new PrintWriter(new FileOutputStream(fileLocation + "stock.csv"));
            LOG.debug("\nWriting Stock file to: " + fileLocation + "stock.csv");
        }

        Stock stock = new Stock();

        for (int i = 1; i <= itemKount; i++) {

            for (int w = 1; w <= whseKount; w++) {

                stock.s_i_id = i;
                stock.s_w_id = w;
                stock.s_quantity = TPCCUtil.randomNumber(10, 100, gen);
                stock.s_ytd = 0;
                stock.s_order_cnt = 0;
                stock.s_remote_cnt = 0;

                // s_data
                randPct = TPCCUtil.randomNumber(1, 100, gen);
                len = TPCCUtil.randomNumber(26, 50, gen);
                if (randPct > 10) {
                    // 90% of time i_data isa random string of length [26 ..
                    // 50]
                    stock.s_data = TPCCUtil.randomStr(len);
                } else {
                    // 10% of time i_data has "ORIGINAL" crammed somewhere
                    // in middle
                    startORIGINAL = TPCCUtil.randomNumber(2, (len - 8), gen);
                    stock.s_data = TPCCUtil.randomStr(startORIGINAL - 1) + "ORIGINAL"
                            + TPCCUtil.randomStr(len - startORIGINAL - 9);
                }

                stock.s_dist_01 = TPCCUtil.randomStr(24);
                stock.s_dist_02 = TPCCUtil.randomStr(24);
                stock.s_dist_03 = TPCCUtil.randomStr(24);
                stock.s_dist_04 = TPCCUtil.randomStr(24);
                stock.s_dist_05 = TPCCUtil.randomStr(24);
                stock.s_dist_06 = TPCCUtil.randomStr(24);
                stock.s_dist_07 = TPCCUtil.randomStr(24);
                stock.s_dist_08 = TPCCUtil.randomStr(24);
                stock.s_dist_09 = TPCCUtil.randomStr(24);
                stock.s_dist_10 = TPCCUtil.randomStr(24);

                k++;
                if (outputFiles == false) {
                    stckPrepStmt.setLong(1, stock.s_w_id);
                    stckPrepStmt.setLong(2, stock.s_i_id);
                    stckPrepStmt.setLong(3, stock.s_quantity);
                    stckPrepStmt.setDouble(4, stock.s_ytd);
                    stckPrepStmt.setLong(5, stock.s_order_cnt);
                    stckPrepStmt.setLong(6, stock.s_remote_cnt);
                    stckPrepStmt.setString(7, stock.s_data);
                    stckPrepStmt.setString(8, stock.s_dist_01);
                    stckPrepStmt.setString(9, stock.s_dist_02);
                    stckPrepStmt.setString(10, stock.s_dist_03);
                    stckPrepStmt.setString(11, stock.s_dist_04);
                    stckPrepStmt.setString(12, stock.s_dist_05);
                    stckPrepStmt.setString(13, stock.s_dist_06);
                    stckPrepStmt.setString(14, stock.s_dist_07);
                    stckPrepStmt.setString(15, stock.s_dist_08);
                    stckPrepStmt.setString(16, stock.s_dist_09);
                    stckPrepStmt.setString(17, stock.s_dist_10);
                    stckPrepStmt.addBatch();
                    if ((k % configCommitCount) == 0) {
                        long tmpTime = new java.util.Date().getTime();
                        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                                + "                    ";
                        LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                        lastTimeMS = tmpTime;
                        stckPrepStmt.executeBatch();
                        stckPrepStmt.clearBatch();
                        transCommit();
                    }
                } else {
                    String str = "";
                    str = str + stock.s_i_id + ",";
                    str = str + stock.s_w_id + ",";
                    str = str + stock.s_quantity + ",";
                    str = str + stock.s_ytd + ",";
                    str = str + stock.s_order_cnt + ",";
                    str = str + stock.s_remote_cnt + ",";
                    str = str + stock.s_data + ",";
                    str = str + stock.s_dist_01 + ",";
                    str = str + stock.s_dist_02 + ",";
                    str = str + stock.s_dist_03 + ",";
                    str = str + stock.s_dist_04 + ",";
                    str = str + stock.s_dist_05 + ",";
                    str = str + stock.s_dist_06 + ",";
                    str = str + stock.s_dist_07 + ",";
                    str = str + stock.s_dist_08 + ",";
                    str = str + stock.s_dist_09 + ",";
                    str = str + stock.s_dist_10;
                    out.println(str);

                    if ((k % configCommitCount) == 0) {
                        long tmpTime = new java.util.Date().getTime();
                        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                                + "                    ";
                        LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                        lastTimeMS = tmpTime;
                    }
                }

            } // end for [w]

        } // end for [i]

        long tmpTime = new java.util.Date().getTime();
        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + "                    ";
        LOG.debug(etStr.substring(0, 30) + "  Writing final records " + k + " of " + t);
        lastTimeMS = tmpTime;
        if (outputFiles == false) {
            stckPrepStmt.executeBatch();
        }
        transCommit();

        now = new java.util.Date();
        LOG.debug("End Stock Load @  " + now);

    } catch (SQLException se) {
        LOG.debug(se.getMessage());
        transRollback();

    } catch (Exception e) {
        e.printStackTrace();
        transRollback();
    }

    return (k);

}

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

/**
 * {@inheritDoc}//from   w  ww.  j  av  a2 s  .c  o m
 */
@Override
public void rebuildIndexForProperty(long propertyId) {
    PreparedStatement ps = null;
    Statement stmtAssignment = null;
    Statement stmtFetch = null;
    try {
        final DBStorage storage = StorageManager.getStorageImpl();
        final ContentStorage contentStorage = storage.getContentStorage(TypeStorageMode.Hierarchical);
        final String TRUE = storage.getBooleanTrueExpression();
        stmtAssignment = con.createStatement();
        stmtFetch = con.createStatement();
        //                                                   1     2           3         4          5          6    7        8     9              10         11
        ResultSet rs = stmtAssignment.executeQuery(
                "SELECT a.id, p.datatype, m.typeid, m.tblname, m.colname, m.lvl, a.xpath, p.id, p.sysinternal, s.tbltype, m.group_assid "
                        + "FROM " + DatabaseConst.TBL_STRUCT_PROPERTIES + " p, "
                        + DatabaseConst.TBL_STRUCT_ASSIGNMENTS + " a LEFT JOIN "
                        + DatabaseConst.TBL_STRUCT_FLATSTORE_MAPPING + " m ON (m.assid=a.id) LEFT JOIN "
                        + DatabaseConst.TBL_STRUCT_FLATSTORE_INFO + " s ON (m.tblname=s.tblname)"
                        + "WHERE p.ISFULLTEXTINDEXED=" + TRUE + " AND a.APROPERTY=p.id"
                        + (propertyId >= 0 ? " AND p.id=" + propertyId : "") + " ORDER BY p.datatype");
        //1..ID,2..VER,3..LANG,4..ASSIGN,5..XMULT,6..VALUE
        ps = con.prepareStatement(getInsertSql());
        int batchCounter;
        long totalCount = 0;
        while (rs != null && rs.next()) {
            long assignmentId = rs.getLong(1);
            ps.setLong(4, assignmentId); //assignment id
            long currentPropertyId = rs.getLong(8);
            FxDataType dataType = FxDataType.getById(rs.getInt(2));
            boolean systemInternalProperty = rs.getBoolean(9);
            if (systemInternalProperty || !dataType.isTextType())
                continue; //do not index system internal properties or non-text properties
            long flatTypeId = rs.getLong(3);
            if (!rs.wasNull()) {
                //flatstorage
                String xpath = rs.getString(7);
                final String xmult;
                int xpathDepth = 1;
                if (!StringUtils.isEmpty(xpath)) {
                    xpathDepth = XPathElement.getDepth(xpath);
                    xmult = XPathElement.addDefaultIndices("", xpathDepth);
                } else {
                    xmult = "1";
                }
                ps.setString(5, xmult);
                final FxFlatStorageInfo.Type flatType = FxFlatStorageInfo.Type.forId(rs.getInt(10));
                //                                                1  2   3      4
                ResultSet rsData = stmtFetch.executeQuery("SELECT ID,VER,LANG," + rs.getString(5) +
                //                          5
                        (flatType == TypeGroups ? ",XMULT" : "") + " FROM " + rs.getString(4) + " WHERE TYPEID="
                        + flatTypeId + " AND LVL=" + rs.getInt(6)
                        + (flatType == TypeGroups ? " AND GROUP_ASSID=" + rs.getLong(11) : ""));
                batchCounter = 0;
                while (rsData != null && rsData.next()) {
                    String value = rsData.getString(4);
                    if (rsData.wasNull() || StringUtils.isEmpty(value))
                        continue;
                    ps.setLong(1, rsData.getLong(1));
                    ps.setInt(2, rsData.getInt(2));
                    ps.setInt(3, rsData.getInt(3));
                    if (flatType == TypeGroups) {
                        // xmult is based on the base group's xmult
                        final String groupXMult = rsData.getString(5);
                        final int missingIndices = Math.max(0, xpathDepth - XPathElement.getDepth(groupXMult));
                        ps.setString(5, XPathElement.addDefaultIndices(groupXMult, missingIndices));
                    }
                    ps.setString(6, value.trim().toUpperCase());
                    ps.addBatch();
                    batchCounter++;
                    totalCount++;
                    if (batchCounter % 1000 == 0)
                        ps.executeBatch(); //insert every 1000 rows
                }
                if (rsData != null)
                    rsData.close();
                ps.executeBatch();
            } else {
                //hierarchical storage
                String[] columns = contentStorage.getColumns(currentPropertyId, systemInternalProperty,
                        dataType);

                final String columnSelect = dataType == FxDataType.Binary ? "b.XMLMETA" : "d." + columns[0]; //first column is the one responsible for indexing
                final String tableAppend = dataType == FxDataType.Binary
                        ? "," + DatabaseConst.TBL_CONTENT_BINARY + " b"
                        : "";
                final String whereAppend = dataType == FxDataType.Binary
                        ? " AND b.ID=d." + columns[0] + " AND b.VER=1 AND b.QUALITY=1"
                        : "";
                //                                                  1    2     3      4               5
                ResultSet rsData = stmtFetch.executeQuery("SELECT d.ID,d.VER,d.LANG,d.XMULT," + columnSelect
                        + " FROM " + DatabaseConst.TBL_CONTENT_DATA + " d" + tableAppend + " WHERE d.ASSIGN="
                        + assignmentId + whereAppend);
                batchCounter = 0;
                while (rsData != null && rsData.next()) {
                    String value = rsData.getString(4);
                    if (rsData.wasNull() || StringUtils.isEmpty(value))
                        continue;
                    ps.setLong(1, rsData.getLong(1));
                    ps.setInt(2, rsData.getInt(2));
                    ps.setInt(3, rsData.getInt(3));
                    ps.setString(5, rsData.getString(4));
                    final String ftValue;
                    switch (dataType) {
                    case Binary:
                        final String xmlMeta = rsData.getString(5);
                        ftValue = FxXMLUtils.getElementData(xmlMeta, "text");
                        break;
                    case HTML:
                    case String1024:
                    case Text:
                        ftValue = rsData.getString(5);
                        break;
                    default:
                        ftValue = null;
                    }
                    if (!StringUtils.isEmpty(ftValue)) {
                        ps.setString(6, ftValue.trim().toUpperCase());
                        ps.addBatch();
                        batchCounter++;
                        totalCount++;
                    }
                    if (batchCounter % 1000 == 0)
                        ps.executeBatch(); //insert every 1000 rows
                }
                if (rsData != null)
                    rsData.close();
                ps.executeBatch();
            }

        }
        LOG.info("Added " + totalCount + " entries to fulltext index.");
        commitChanges();
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
    } catch (FxNotFoundException e) {
        //ContentStorage was not found
        throw e.asRuntimeException();
    } finally {
        Database.closeObjects(GenericSQLFulltextIndexer.class, ps, stmtAssignment, stmtFetch);
    }
}

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

/**
 * Create a new type// w w  w  .  j av  a2  s .c o m
 *
 * @param type the type to create
 * @return id of the new type
 * @throws FxApplicationException on errors
 */
private long create(FxTypeEdit type) throws FxApplicationException {
    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.create.nameMissing");
    if (!type.getStorageMode().isSupported())
        throw new FxInvalidParameterException("STORAGEMODE", "ex.structure.typeStorageMode.notSupported",
                type.getStorageMode().getLabel().getBestTranslation(ticket));
    if (type.getACL().getCategory() != ACLCategory.STRUCTURE)
        throw new FxInvalidParameterException("aclId", "ex.acl.category.invalid",
                type.getACL().getCategory().name(), ACLCategory.STRUCTURE.name());
    if (type.hasDefaultInstanceACL() && type.getDefaultInstanceACL().getCategory() != ACLCategory.INSTANCE)
        throw new FxInvalidParameterException("DEFACL", "ex.acl.category.invalid",
                type.getDefaultInstanceACL().getCategory(), ACLCategory.INSTANCE);
    Connection con = null;
    PreparedStatement ps = null;
    long newId = seq.getId(FxSystemSequencer.TYPEDEF);
    final long NOW = System.currentTimeMillis();
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement(TYPE_CREATE);
        ps.setLong(1, newId);
        ps.setString(2, type.getName());
        if (type.getParent() != null)
            ps.setLong(3, type.getParent().getId());
        else
            ps.setNull(3, java.sql.Types.INTEGER);
        ps.setInt(4, type.getStorageMode().getId());
        ps.setInt(5, type.getCategory().getId());
        ps.setInt(6, type.getMode().getId());
        ps.setInt(7, type.getLanguage().getId());
        ps.setInt(8, type.getState().getId());
        ps.setByte(9, type.getBitCodedPermissions());
        ps.setBoolean(10, type.isTrackHistory());
        ps.setLong(11, type.getHistoryAge());
        ps.setLong(12, type.getMaxVersions());
        ps.setInt(13, type.getMaxRelSource());
        ps.setInt(14, type.getMaxRelDestination());
        ps.setLong(15, ticket.getUserId());
        ps.setLong(16, NOW);
        ps.setLong(17, ticket.getUserId());
        ps.setLong(18, NOW);
        ps.setLong(19, type.getACL().getId());
        ps.setLong(20, type.getWorkflow().getId());
        if (type.getIcon().isEmpty())
            ps.setNull(21, java.sql.Types.INTEGER);
        else
            ps.setLong(21, type.getIcon().getDefaultTranslation().getId());
        ps.setBoolean(22, type.isUseInstancePermissions() && type.isMultipleContentACLs());
        ps.setBoolean(23, type.isIncludedInSupertypeQueries());
        if (type.hasDefaultInstanceACL())
            ps.setLong(24, type.getDefaultInstanceACL().getId());
        else
            ps.setNull(24, java.sql.Types.INTEGER);
        ps.setBoolean(25, type.isAutoVersion());
        ps.executeUpdate();
        Database.storeFxString(type.getLabel(), con, TBL_STRUCT_TYPES, "DESCRIPTION", "ID", newId);

        StructureLoader.reload(con);
        FxType thisType = CacheAdmin.getEnvironment().getType(newId);
        htracker.track(thisType, "history.type.create", type.getName(), newId);

        //store relations
        ps.close();
        if (type.getAddedRelations().size() > 0) {
            ps = con.prepareStatement("INSERT INTO " + TBL_STRUCT_TYPERELATIONS
                    + " (TYPEDEF,TYPESRC,TYPEDST,MAXSRC,MAXDST)VALUES(?,?,?,?,?)");
            ps.setLong(1, thisType.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(thisType, "history.type.create.relation.add", type.getName(),
                        rel.getSource().getName(), rel.getMaxSource(), rel.getDestination().getName(),
                        rel.getMaxDestination());
            }
            ps.executeBatch();
        }

        if (type.getParent() == null) {
            for (FxPropertyAssignment spa : environment.getSystemInternalRootPropertyAssignments()) {
                final FxPropertyAssignmentEdit derived = FxPropertyAssignmentEdit.createNew(spa, thisType,
                        spa.getAlias(), "/");
                assignmentEngine.save(
                        updateAclAssignmentMultiplicity(type, derived).setEnabled(true)._setSystemInternal(),
                        false);
            }
        } else {
            //create parent assignments
            List<FxAssignment> parentAssignments = type.getParent().getConnectedAssignments("/");
            for (FxAssignment as : parentAssignments) {
                if (as instanceof FxPropertyAssignment) {
                    FxPropertyAssignmentEdit pae = FxPropertyAssignmentEdit.createNew((FxPropertyAssignment) as,
                            thisType, as.getAlias(), "/");
                    pae.setEnabled(type.isEnableParentAssignments());
                    assignmentEngine.save(updateAclAssignmentMultiplicity(type, pae), false);
                } else if (as instanceof FxGroupAssignment) {
                    FxGroupAssignmentEdit pge = FxGroupAssignmentEdit.createNew((FxGroupAssignment) as,
                            thisType, as.getAlias(), "/");
                    pge.setEnabled(type.isEnableParentAssignments());
                    assignmentEngine.save(pge, true);
                }
            }
        }

        // store structure options
        storeTypeOptions(con, TBL_STRUCT_TYPES_OPTIONS, "ID", newId, type.getOptions(), false);

        StructureLoader.reload(con);
    } catch (SQLException e) {
        if (StorageManager.isUniqueConstraintViolation(e)) {
            EJBUtils.rollback(ctx);
            throw new FxCreateException("ex.structure.type.exists", type.getName());
        }
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.db.sqlError", e.getMessage());
    } catch (FxCacheException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(LOG, e, "ex.cache", e.getMessage());
    } catch (FxLoadException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxNotFoundException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxEntryExistsException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } catch (FxUpdateException e) {
        EJBUtils.rollback(ctx);
        throw new FxCreateException(e);
    } finally {
        Database.closeObjects(TypeEngineBean.class, con, ps);
    }
    return newId;
}

From source file:com.alfaariss.oa.engine.session.jdbc.JDBCSessionFactory.java

/**
 * Uses a batch update to persist all supplied sessions.
 * @param sessions The sessions to persist.
 * @throws PersistenceException If persistance fails.
 * /*from  w w w  . j a  va  2  s .c  o m*/
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCSession[] sessions) throws PersistenceException {
    if (sessions == null)
        throw new IllegalArgumentException("Suplied session array is empty or invalid");

    Connection connection = null;
    PreparedStatement psInsert = null;
    PreparedStatement psDelete = null;
    PreparedStatement psUpdate = null;
    try {
        connection = _oDataSource.getConnection(); //Manage connection
        connection.setAutoCommit(false);

        psInsert = connection.prepareStatement(_sInsertQuery);
        psDelete = connection.prepareStatement(_sRemoveQuery);
        psUpdate = connection.prepareStatement(_sUpdateQuery);

        for (JDBCSession session : sessions) {
            String id = session.getId();
            if (id == null) {
                byte[] baId = new byte[ISession.ID_BYTE_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                session.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setString(2, session.getTGTId());
                psInsert.setInt(3, session.getState().ordinal());
                psInsert.setString(4, session.getRequestorId());
                psInsert.setString(5, session.getProfileURL());
                psInsert.setBytes(6, Serialize.encode(session.getUser()));
                psInsert.setTimestamp(7, new Timestamp(expiration));
                psInsert.setBoolean(8, session.isForcedAuthentication());
                psInsert.setBoolean(9, session.isPassive());
                psInsert.setBytes(10, Serialize.encode(session.getAttributes()));
                psInsert.setString(11, session.getForcedUserID());
                psInsert.setBytes(12, Serialize.encode(session.getLocale()));
                psInsert.setBytes(13, Serialize.encode(session.getSelectedAuthNProfile()));
                psInsert.setBytes(14, Serialize.encode(session.getAuthNProfiles()));
                psInsert.addBatch();
            } else if (session.isExpired()) //Expired
            {
                _logger.info("Session Expired: " + id);

                _eventLogger.info(new UserEventLogItem(session, null, UserEvent.SESSION_EXPIRED, this, null));

                psDelete.setString(1, id);
                psDelete.addBatch();
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psUpdate.setString(1, session.getTGTId());
                psUpdate.setInt(2, session.getState().ordinal());
                psUpdate.setString(3, session.getRequestorId());
                psUpdate.setString(4, session.getProfileURL());
                psUpdate.setBytes(5, Serialize.encode(session.getUser()));
                psUpdate.setTimestamp(6, new Timestamp(expiration));
                psUpdate.setBoolean(7, session.isForcedAuthentication());
                psInsert.setBoolean(8, session.isPassive());
                psUpdate.setBytes(9, Serialize.encode(session.getAttributes()));
                psUpdate.setString(10, session.getForcedUserID());
                psUpdate.setBytes(11, Serialize.encode(session.getLocale()));
                psUpdate.setBytes(12, Serialize.encode(session.getSelectedAuthNProfile()));
                psUpdate.setBytes(13, Serialize.encode(session.getAuthNProfiles()));
                psUpdate.setString(14, id);
                psUpdate.addBatch();
            }
        }
        try {
            int[] iResult = psInsert.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalAdded = 0;
                for (int i : iResult)
                    iTotalAdded += i;

                _logger.info(iTotalAdded + " new session(s) added by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }
        try {
            int[] iResult = psDelete.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalDeleted = 0;
                for (int i : iResult)
                    iTotalDeleted += i;

                _logger.info(iTotalDeleted + " session(s) deleted by batch");
            }

        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }
        try {
            int[] iResult = psUpdate.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalUpdated = 0;
                for (int i : iResult)
                    iTotalUpdated += i;

                _logger.info(iTotalUpdated + " session(s) updated by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();
    } catch (SQLException e) {
        _logger.error("Could not execute batch", e);
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }

        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
    } catch (PersistenceException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }
        throw e;
    } catch (Exception e) {
        _logger.error("Internal error during session persist", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } finally {
        try {
            if (psInsert != null)
                psInsert.close();
        } catch (SQLException e) {
            _logger.debug("Could not close insert statement", e);
        }
        try {
            if (psDelete != null)
                psDelete.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete statement", e);
        }
        try {
            if (psUpdate != null)
                psUpdate.close();
        } catch (SQLException e) {
            _logger.debug("Could not close update statement", e);
        }
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

public/* synchronized */Map<String, HotRestoreInfo> pause(Map<String, HotRestoreInfo> hriMap) {
    if (isClosed())
        return null;
    if (!USE_CHECKPOINTS_AS_PAUSE_TABLE)
        return pauseBatchIndividually(hriMap);

    String updateCmdNoLogIndex = "update " + (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable())
            + " set serialized=?, has_serialized=true where  paxos_id=?";

    Map<String, HotRestoreInfo> paused = new HashMap<String, HotRestoreInfo>();
    HotRestoreInfo[] hris = hriMap.values().toArray(new HotRestoreInfo[0]);
    PreparedStatement pstmt = null;
    Connection conn = null;/*  w  w  w.ja  v  a  2s .c  om*/
    try {
        Map<String, HotRestoreInfo> batch = new HashMap<String, HotRestoreInfo>();
        for (int i = 0; i < hris.length; i++) {
            String paxosID = hris[i].paxosID;
            if (conn == null) {
                conn = this.getDefaultConn();
                conn.setAutoCommit(false);
                pstmt = conn.prepareStatement(updateCmdNoLogIndex);
            }
            pstmt.setString(1, hriMap.get(paxosID).toString());
            pstmt.setString(2, paxosID);

            pstmt.addBatch();
            batch.put(paxosID, hris[i]);
            if ((i + 1) % MAX_DB_BATCH_SIZE == 0 || (i + 1) == hriMap.size()) {
                pstmt.executeBatch();
                conn.commit();
                pstmt.clearBatch();
                paused.putAll(batch);

                log.log(Level.FINE, "{0} paused [{1}] ,[{2}]",
                        new Object[] { this, Util.truncatedLog(batch.keySet(), 16) });
                batch.clear();
            }
        }
    } catch (SQLException e) {
        log.severe(this + " failed to pause batch " + Util.truncatedLog(hriMap.keySet(), 10));
        e.printStackTrace();
    } finally {
        cleanup(pstmt);
        cleanup(conn);
    }
    paused.putAll(this.pauseBatchIndividually(this.diffHRI(hriMap, paused)));
    return paused;
}

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

/**
 * {@inheritDoc}//from www . java  2s. c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void assignPhrases(int category, long position, long assignmentOwner, long nodeId, long nodeMandator,
        FxPhrase[] phrases) throws FxApplicationException {
    if (phrases == null || phrases.length == 0)
        return;
    checkMandatorAccess(assignmentOwner, FxContext.getUserTicket());
    Connection con = null;
    PreparedStatement ps = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        //check categories
        ps = con.prepareStatement("SELECT ID FROM " + TBL_PHRASE_TREE + " WHERE ID=? AND MANDATOR=? AND CAT=?");
        ps.setLong(1, nodeId);
        ps.setLong(2, nodeMandator);
        ps.setInt(3, category);
        ResultSet rs = ps.executeQuery();
        if (rs == null || !(rs.next()))
            throw new FxNotFoundException("ex.phrases.node.notFound.id", nodeId, nodeMandator);
        ps.close();
        long startPhraseId = -1, startPhraseMandator = -1;
        ps = con.prepareStatement("SELECT PHRASEID,PMANDATOR FROM " + TBL_PHRASE_MAP
                + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND POS>=? AND CAT=? AND DIRECT=TRUE ORDER BY POS ASC");
        ps.setLong(1, assignmentOwner);
        ps.setLong(2, nodeId);
        ps.setLong(3, nodeMandator);
        ps.setLong(4, position);
        ps.setInt(5, category);
        rs = ps.executeQuery();
        while (rs != null && rs.next()) {
            long pid = rs.getLong(1);
            long mid = rs.getLong(2);
            if (!phrasesContains(phrases, pid, mid)) {
                startPhraseId = pid;
                startPhraseMandator = mid;
                break;
            }
        }
        ps.close();
        boolean useMaxPos = startPhraseId == -1 || startPhraseMandator == -1;
        //remove all contained phrases
        ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_MAP
                + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=? AND CAT=? AND DIRECT=TRUE");
        ps.setLong(1, assignmentOwner);
        ps.setLong(2, nodeId);
        ps.setLong(3, nodeMandator);
        ps.setInt(6, category);
        for (FxPhrase rm : phrases) {
            ps.setLong(4, rm.getId());
            ps.setLong(5, rm.getMandator());
            ps.addBatch();
        }
        ps.executeBatch();
        ps.close();
        //close gaps and reposition
        updatePhrasePosition(con, category, assignmentOwner, nodeId, nodeMandator, -1, -1, 0, true);
        int insertPos = -1;
        if (!useMaxPos) {
            ps = con.prepareStatement("SELECT POS FROM " + TBL_PHRASE_MAP
                    + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=? AND CAT=? AND DIRECT=?");
            ps.setLong(1, assignmentOwner);
            ps.setLong(2, nodeId);
            ps.setLong(3, nodeMandator);
            ps.setLong(4, startPhraseId);
            ps.setLong(5, startPhraseMandator);
            ps.setInt(6, category);
            ps.setBoolean(7, true);
            rs = ps.executeQuery();
            if (rs != null && rs.next())
                insertPos = rs.getInt(1);
            ps.close();
        }
        if (insertPos == -1)
            useMaxPos = true;
        if (!useMaxPos) {
            //make room for the phrases to insert
            ps = con.prepareStatement("UPDATE " + TBL_PHRASE_MAP + " SET POS=POS+" + (phrases.length)
                    + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND POS>? AND CAT=? AND DIRECT=?");
            ps.setLong(1, assignmentOwner);
            ps.setLong(2, nodeId);
            ps.setLong(3, nodeMandator);
            ps.setLong(4, insertPos);
            ps.setInt(5, category);
            ps.setBoolean(6, true);
            ps.executeUpdate();
            ps.close();
        } else {
            ps = con.prepareStatement("SELECT MAX(POS) FROM " + TBL_PHRASE_MAP
                    + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND CAT=? AND DIRECT=?");
            ps.setLong(1, assignmentOwner);
            ps.setLong(2, nodeId);
            ps.setLong(3, nodeMandator);
            ps.setInt(4, category);
            ps.setBoolean(5, true);
            rs = ps.executeQuery();
            if (rs != null && rs.next())
                insertPos = rs.getInt(1);
            else
                insertPos = 1; //fallback: first entry
            ps.close();
        }
        ps = con.prepareStatement("INSERT INTO " + TBL_PHRASE_MAP
                + "(MANDATOR,CAT,NODEID,NODEMANDATOR,PHRASEID,PMANDATOR,POS,DIRECT)VALUES(?,?,?,?,?,?,?,?)");
        ps.setLong(1, assignmentOwner);
        ps.setInt(2, category);
        ps.setLong(3, nodeId);
        ps.setLong(4, nodeMandator);
        ps.setBoolean(8, true);
        for (FxPhrase phrase : phrases) {
            ps.setLong(5, phrase.getId());
            ps.setLong(6, phrase.getMandator());
            ps.setLong(7, ++insertPos);
            ps.addBatch();
        }
        ps.executeBatch();
        if (phrases.length > 10)
            rebuildPhraseChildMapping(con, assignmentOwner, category, -1, -1);
        else {
            for (FxPhrase phrase : phrases) {
                rebuildPhraseChildMapping(con, assignmentOwner, category, phrase.getId(), phrase.getMandator());
            }
        }
    } 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.PhraseEngineBean.java

private void updatePhrasePosition(Connection con, int category, long assignmentOwner, long nodeId,
        long nodeMandator, long phraseId, long phraseMandator, long pos, boolean checkPositioning)
        throws SQLException {
    PreparedStatement psUpdate = null, psFetch = null;
    try {/*from  ww  w .java  2  s  . c  om*/
        //                                                                     1                2            3                  4              5               6         7
        psUpdate = con.prepareStatement("UPDATE " + TBL_PHRASE_MAP
                + " SET POS=? WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND PHRASEID=? AND PMANDATOR=? AND CAT=?");
        psUpdate.setLong(2, assignmentOwner);
        psUpdate.setLong(3, nodeId);
        psUpdate.setLong(4, nodeMandator);
        psUpdate.setInt(7, category);
        if (checkPositioning) {
            //                                                                                                         1            2                  3         4
            psFetch = con.prepareStatement("SELECT POS, PHRASEID, PMANDATOR FROM " + TBL_PHRASE_MAP
                    + " WHERE MANDATOR=? AND NODEID=? AND NODEMANDATOR=? AND CAT=? AND DIRECT=TRUE ORDER BY POS");
            psFetch.setLong(1, assignmentOwner);
            psFetch.setLong(2, nodeId);
            psFetch.setLong(3, nodeMandator);
            psFetch.setInt(4, category);
            ResultSet rs = psFetch.executeQuery();
            long currPos = 0;
            while (rs != null && rs.next()) {
                long _pos = rs.getLong(1);
                long _phraseId = rs.getLong(2);
                long _phraseMandatorId = rs.getLong(3);
                //                    if (phraseId == _phraseId && phraseMandator == _phraseMandatorId)
                //                        continue;
                currPos++;
                if (currPos == pos)
                    continue;
                if (_pos == currPos)
                    continue;
                psUpdate.setLong(1, currPos);
                psUpdate.setLong(5, _phraseId);
                psUpdate.setLong(6, _phraseMandatorId);
                psUpdate.addBatch();
            }
        }
        psUpdate.setLong(1, pos);
        psUpdate.setLong(5, phraseId);
        psUpdate.setLong(6, phraseMandator);
        psUpdate.addBatch();
        psUpdate.executeBatch();
    } finally {
        Database.closeObjects(PhraseEngineBean.class, psFetch, psUpdate);
    }
}

From source file:HSqlManager.java

public static void primerAnalysis(Connection connection, int bps) throws SQLException, IOException {
    long time = System.currentTimeMillis();
    DpalLoad.main(new String[1]);
    HSqlPrimerDesign.Dpal_Inst = DpalLoad.INSTANCE_WIN64;
    String base = new File("").getAbsolutePath();
    CSV.makeDirectory(new File(base + "/PhageData"));
    INSTANCE = ImportPhagelist.getInstance();
    INSTANCE.parseAllPhages(bps);//from w  w w.  j  a v  a 2  s .  c o  m
    System.out.println((System.currentTimeMillis() - time) / Math.pow(10, 3) / 60);
    time = System.currentTimeMillis();
    written = true;
    Connection db = connection;
    db.setAutoCommit(false);
    Statement stat = db.createStatement();
    stat.execute("SET FILES LOG FALSE\n");
    //        PreparedStatement st = db.prepareStatement("Insert INTO Primerdb.Primers" +
    //                "(Bp,Sequence, CommonP, UniqueP, Picked, Strain, Cluster)" +
    //                " Values(?,?,true,false,false,?,?)");
    PreparedStatement st = db.prepareStatement(
            "INSERT INTO Primerdb.Primers" + "(Bp,Sequence,Strain,Cluster,Tm,GC,UniqueP,CommonP,Hairpin) "
                    + "VALUES(?,?,?,?,?,?,true,true,?)");
    ResultSet call = stat.executeQuery("Select * From Primerdb.Phages;");
    List<String[]> phages = new ArrayList<>();
    while (call.next()) {
        String[] r = new String[3];
        r[0] = call.getString("Strain");
        r[1] = call.getString("Cluster");
        r[2] = call.getString("Name");
        phages.add(r);

        //            if(strain.equals("-myco")) {
        //                if (r[2].equals("xkcd")) {
        //                    strain = r[0];
        //                }
        //            }else if(strain.equals("-arthro")){
        //                if (r[2].equals("ArV1")) {
        //                    strain = r[0];
        //                }
        //            }
    }
    call.close();

    Set<String> strains = phages.stream().map(y -> y[0]).collect(Collectors.toSet());
    for (String x : strains) {
        Set<String> clust = phages.stream().filter(y -> y[0].equals(x)).map(y -> y[1])
                .collect(Collectors.toSet());
        Map<String, Integer> clustersNum = new HashMap<>();
        Map<Integer, String> clustersName = new HashMap<>();
        Map<Integer, List<String>> clusters = new HashMap<>();
        Map<Bytes, Primer> primers = new HashMap<>();
        int i = 0;
        for (String cluster : clust) {
            clustersName.put(i, cluster);
            clustersNum.put(cluster, i);
            i++;
        }
        clust.parallelStream()
                .forEach(cluster -> clusters.put(clustersNum.get(cluster),
                        phages.stream().filter(a -> a[0].equals(x) && a[1].equals(cluster)).map(a -> a[2])
                                .collect(Collectors.toList())));
        for (int z : clusters.keySet()) {
            //            try {
            List<String> clustphages = clusters.get(z);
            for (String phage : clustphages) {
                Set<Bytes> phagprimers =
                        //Read from CSV file here
                        //Premade CSV files of all possible
                        //primers in a phage genome
                        CSV.readCSV(base + "/PhageData/" + Integer.toString(bps) + phage + ".csv").stream()
                                .map(l -> new Bytes(l.getBytes())).collect(Collectors.toSet());
                for (Bytes primer : phagprimers) {
                    if (!primers.containsKey(primer)) {
                        primers.put(primer, new Primer(z));
                    } else {
                        Primer select = primers.get(primer);
                        select.phageCount++;
                        if (!select.containsCluster(z)) {
                            select.addCluster(z);
                        }
                    }

                }

            }
            System.out.println(clustersName.get(z));
        }
        int count = 0;
        Iterator<Map.Entry<Bytes, Primer>> primersSet = primers.entrySet().iterator();
        while (primersSet.hasNext()) {
            Map.Entry<Bytes, Primer> primer = primersSet.next();
            Primer primerInf = primer.getValue();
            if (primerInf.clusters.length != 1) {
                primer.setValue(null);
            } else {
                int primerClust = -1;
                for (int cluster : primerInf.clusters) {
                    primerClust = cluster;
                }
                if (primerInf.phageCount != clusters.get(primerClust).size()) {
                    primer.setValue(null);
                } else {
                    count++;
                }
            }
        }
        System.out.print("Unique Count: ");
        System.out.println(count);
        System.out.print("Primer Count: ");
        System.out.println(primers.size());
        i = 0;
        for (Bytes a : primers.keySet()) {
            Primer primerInf = primers.get(a);
            if (primerInf != null) {
                String primerClust = "";
                for (int cluster : primerInf.clusters) {
                    primerClust = clustersName.get(cluster);
                }
                String str = new String(a.bytes);
                try {
                    st.setInt(1, bps);
                    st.setString(2, str);
                    st.setString(3, x);
                    st.setString(4, primerClust);
                    //                        st.setDouble(5, HSqlPrimerDesign.primerTm(str, 0, 800, 1.5, 0.2));
                    st.setDouble(5, HSqlPrimerDesign.easytm(str));
                    st.setDouble(6, HSqlPrimerDesign.gcContent(str));
                    st.setBoolean(7, HSqlPrimerDesign.calcHairpin(str, 4));
                    st.addBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("Error occurred at " + x + " " + primerClust);
                }
                i++;
                if (i == 1000) {
                    i = 0;
                    st.executeBatch();
                    db.commit();
                }
            }
        }
        if (i > 0) {
            st.executeBatch();
            db.commit();
        }

        //        }

        System.out.println("Unique Updated");
        System.out.println((System.currentTimeMillis() - time) / Math.pow(10, 3) / 60);
    }
    stat.execute("SET FILES LOG TRUE;");
    st.close();
    stat.close();
}

From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java

/**
 * Uses a batch update to persist all supplied tgts.
 * @param tgts The TGTs to persist./*w  w w. j av  a  2s. c o m*/
 * @throws PersistenceException If persistance fails.
 * 
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCTGT[] tgts) throws PersistenceException {
    if (tgts == null)
        throw new IllegalArgumentException("Suplied tgt array is empty or invalid");

    List<TGTEventError> listTGTEventErrors = new Vector<TGTEventError>();

    Connection connection = null;
    PreparedStatement psInsert = null;
    PreparedStatement psDelete = null;
    PreparedStatement psDeleteAliasR = null;
    PreparedStatement psDeleteAliasF = null;
    PreparedStatement psUpdate = null;
    try {
        connection = _oDataSource.getConnection(); //Manage connection
        connection.setAutoCommit(false);

        if (_aliasStoreSP != null)
            psDeleteAliasR = connection.prepareStatement(_aliasStoreSP.getQueryAliasRemove());

        if (_aliasStoreIDP != null)
            psDeleteAliasF = connection.prepareStatement(_aliasStoreIDP.getQueryAliasRemove());

        psInsert = connection.prepareStatement(_sInsertQuery);
        psDelete = connection.prepareStatement(_sRemoveQuery);
        psUpdate = connection.prepareStatement(_sUpdateQuery);

        Vector<ITGT> vCreate = new Vector<ITGT>();
        Vector<ITGT> vUpdate = new Vector<ITGT>();
        Vector<ITGT> vRemove = new Vector<ITGT>();

        for (JDBCTGT tgt : tgts) //For all tgts
        {
            String id = tgt.getId();
            if (id == null) //New TGT
            {
                byte[] baId = new byte[ITGT.TGT_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create tgt id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                tgt.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setTimestamp(2, new Timestamp(expiration));
                psInsert.setBytes(3, Serialize.encode(tgt.getUser()));
                psInsert.setBytes(4, Serialize.encode(tgt.getAuthenticationProfile()));
                psInsert.setBytes(5, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psInsert.setBytes(6, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psInsert.setBytes(7, Serialize.encode(tgt.getAttributes()));
                psInsert.addBatch();

                vCreate.add(tgt);
            } else if (tgt.isExpired()) //Expired
            {
                _logger.debug("TGT Expired: " + id);

                if (psDeleteAliasR != null) {
                    psDeleteAliasR.setString(1, id);
                    psDeleteAliasR.addBatch();
                }

                if (psDeleteAliasF != null) {
                    psDeleteAliasF.setString(1, id);
                    psDeleteAliasF.addBatch();
                }

                vRemove.add(tgt);
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                //Update tgt
                psUpdate.setTimestamp(1, new Timestamp(expiration));
                psUpdate.setBytes(2, Serialize.encode(tgt.getUser()));
                psUpdate.setBytes(3, Serialize.encode(tgt.getAuthenticationProfile()));
                psUpdate.setBytes(4, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psUpdate.setBytes(5, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psUpdate.setBytes(6, Serialize.encode(tgt.getAttributes()));
                psUpdate.setString(7, id);
                psUpdate.addBatch();

                vUpdate.add(tgt);
            }
        }

        try {
            int iTotalAdded = 0;
            for (int i : psInsert.executeBatch()) {
                iTotalAdded += i;
            }
            _logger.debug(iTotalAdded + " new TGT(s) added by batch");

            for (ITGT tgt : vCreate) {
                try {
                    processEvent(TGTListenerEvent.ON_CREATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }

        try {
            for (ITGT tgt : vRemove) {
                IUser tgtUser = tgt.getUser();
                _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.TGT_EXPIRED,
                        tgtUser.getID(), tgtUser.getOrganization(), null, null, this, null));

                try {
                    processEvent(TGTListenerEvent.ON_REMOVE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }

            int iTotalDeleted = 0;
            for (int i : psDelete.executeBatch()) {
                iTotalDeleted += i;
            }
            _logger.debug(iTotalDeleted + " TGT(s) deleted by batch");
        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }

        if (psDeleteAliasR != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasR.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (requestor based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (requestor based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        if (psDeleteAliasF != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasF.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (remote enitity based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (remote enitity based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        try {
            int iTotalUpdated = 0;
            for (int i : psUpdate.executeBatch()) {
                iTotalUpdated += i;
            }
            _logger.debug(iTotalUpdated + " TGT(s) updated by batch");

            for (ITGT tgt : vUpdate) {
                try {
                    processEvent(TGTListenerEvent.ON_UPDATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();

        if (listTGTEventErrors != null) {//TGT Event processing failed, error has been logged already
            throw new TGTListenerException(listTGTEventErrors);
        }
    } catch (SQLException e) {
        _logger.error("Could not execute Batch", e);
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }

        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
    } catch (PersistenceException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }
        throw e;
    } catch (Exception e) {
        _logger.error("Could not connect to JDBC resource", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } finally {
        try {
            if (psInsert != null)
                psInsert.close();
        } catch (SQLException e) {
            _logger.debug("Could not close insert statement", e);
        }

        try {
            if (psDelete != null)
                psDelete.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete statement", e);
        }

        try {
            if (psDeleteAliasR != null)
                psDeleteAliasR.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (requestor based) alias statement", e);
        }

        try {
            if (psDeleteAliasF != null)
                psDeleteAliasF.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (remote entity based) alias statement", e);
        }

        try {
            if (psUpdate != null)
                psUpdate.close();
        } catch (SQLException e) {
            _logger.debug("Could not close update statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}