Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

In this page you can find the example usage for java.sql Connection rollback.

Prototype

void rollback() throws SQLException;

Source Link

Document

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

Usage

From source file:com.gtwm.pb.model.manageData.DataManagement.java

public void removeRecord(HttpServletRequest request, SessionDataInfo sessionData, DatabaseInfo databaseDefn,
        TableInfo table, int rowId, boolean cascade) throws SQLException, ObjectNotFoundException,
        CodingErrorException, CantDoThatException, DisallowedException, DataDependencyException {
    Map<TableInfo, String> recordDependencies = new LinkedHashMap<TableInfo, String>();
    Set<TableInfo> tables = this.authManager.getCompanyForLoggedInUser(request).getTables();
    Connection conn = null;
    try {/*from   ww  w .j a  v  a  2s .co m*/
        conn = this.dataSource.getConnection();
        conn.setAutoCommit(false);
        recordDependencies = getRecordsDependencies(conn, tables, sessionData, databaseDefn, table, rowId,
                recordDependencies);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    // check for cascading deletes:
    if (recordDependencies.size() > 0) {
        // check if user has permissions on all dependent tables:
        for (TableInfo dependentTable : recordDependencies.keySet()) {
            if (dependentTable.equals(table))
                continue;
            if (this.authManager.getAuthenticator().loggedInUserAllowedTo(request,
                    PrivilegeType.EDIT_TABLE_DATA, dependentTable))
                continue;
            if (this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.MANAGE_TABLE,
                    dependentTable))
                continue;
            throw new CantDoThatException(
                    // TODO: This should probably really
                    // be a DisallowedException
                    "Unable to delete record as you are not permitted to delete from the dependent table "
                            + dependentTable);
        }
        // user has permissions on all dependent data. however, deletion
        // should only continue if the user has opted to cascade deletion
        if (!cascade) {
            String warning = "";
            for (Map.Entry<TableInfo, String> dependency : recordDependencies.entrySet()) {
                warning += dependency.getKey().getSimpleName() + " - " + dependency.getValue() + "\n";
            }
            throw new DataDependencyException(warning);
        }
    }
    // First get all the content of the row we're deleting, for logging
    // purposes
    Map<BaseField, BaseValue> deletedRow = this.getTableDataRow(null, table, rowId, false);
    String SQLCode = "DELETE FROM " + table.getInternalTableName() + " WHERE "
            + table.getPrimaryKey().getInternalFieldName() + "=?";
    try {
        conn = this.dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement statement = conn.prepareStatement(SQLCode);
        TableDataInfo tableData = new TableData(table);
        if (tableData.isRecordLocked(conn, sessionData, rowId)) {
            throw new CantDoThatException(
                    "Record " + rowId + " can't be removed from " + table + " because it is locked");
        }
        statement.setInt(1, rowId);
        int numRowsDeleted = statement.executeUpdate();
        statement.close();
        // Make sure we don't delete more than one row
        if (numRowsDeleted > 1) {
            conn.rollback();
            throw new ObjectNotFoundException(
                    String.valueOf(numRowsDeleted) + " records deleted for row id " + String.valueOf(rowId));
        } else {
            // Delete comments for the record
            Set<String> internalFieldNamesSet = new HashSet<String>();
            for (BaseField field : table.getFields()) {
                if (!field.getHidden()) {
                    internalFieldNamesSet.add("'" + field.getInternalFieldName() + "'");
                }
            }
            String internalFieldNamesCsv = StringUtils.join(internalFieldNamesSet, ",");
            SQLCode = "DELETE FROM dbint_comments WHERE rowid=? AND internalfieldname IN ("
                    + internalFieldNamesCsv + ")";
            statement = conn.prepareStatement(SQLCode);
            statement.setInt(1, rowId);
            int numCommentsDeleted = statement.executeUpdate();
            if (numCommentsDeleted > 0) {
                logger.info("" + numCommentsDeleted + " comments deleted when deleting " + table + " record "
                        + rowId);
            }
            statement.close();
            conn.commit();
        }
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    this.removeUploadedFiles(table, rowId);
    this.logLastDataChangeTime(request);
    logLastTableDataChangeTime(table);
    UsageLogger usageLogger = new UsageLogger(dataSource);
    AppUserInfo user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    usageLogger.logDataChange(user, table, null, AppAction.REMOVE_RECORD, rowId, "Deleted data: " + deletedRow);
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:com.mysql.stresstool.RunnableQueryInsertDR.java

public void run() {

    BufferedReader d = null;//from   ww w .java 2s  .com
    Connection conn = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));
    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    if (conn != null) {

        try {

            Statement stmt = null;
            //                ResultSet rs = null;
            //                ResultSet rs2 = null;

            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            stmt.execute("SET AUTOCOMMIT=0");
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            populateLocalInfo(conn);

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval++;
                //IMPLEMENTING lazy
                Vector v = this.getTablesValues(lazy);

                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=1073741824");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            intBlobInterval = 0;

                        }
                    }
                    if (debug) {
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY1==" + insert1);
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY2==" + insert2);

                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    System.out.println("FAILED QUERY1==" + insert1);
                    System.out.println("FAILED QUERY2==" + insert2);
                    sqle.printStackTrace();
                    System.exit(1);
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

@RetrySemantics.ReadOnly
public ShowCompactResponse showCompact(ShowCompactRequest rqst) throws MetaException {
    ShowCompactResponse response = new ShowCompactResponse(new ArrayList<ShowCompactResponseElement>());
    Connection dbConn = null;
    Statement stmt = null;//  ww  w.ja  v a  2 s . c o m
    try {
        try {
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            String s = "select cq_database, cq_table, cq_partition, cq_state, cq_type, cq_worker_id, " +
            //-1 because 'null' literal doesn't work for all DBs...
                    "cq_start, -1 cc_end, cq_run_as, cq_hadoop_job_id, cq_id from COMPACTION_QUEUE union all "
                    + "select cc_database, cc_table, cc_partition, cc_state, cc_type, cc_worker_id, "
                    + "cc_start, cc_end, cc_run_as, cc_hadoop_job_id, cc_id from COMPLETED_COMPACTIONS";
            //what I want is order by cc_end desc, cc_start asc (but derby has a bug https://issues.apache.org/jira/browse/DERBY-6013)
            //to sort so that currently running jobs are at the end of the list (bottom of screen)
            //and currently running ones are in sorted by start time
            //w/o order by likely currently running compactions will be first (LHS of Union)
            LOG.debug("Going to execute query <" + s + ">");
            ResultSet rs = stmt.executeQuery(s);
            while (rs.next()) {
                ShowCompactResponseElement e = new ShowCompactResponseElement();
                e.setDbname(rs.getString(1));
                e.setTablename(rs.getString(2));
                e.setPartitionname(rs.getString(3));
                e.setState(compactorStateToResponse(rs.getString(4).charAt(0)));
                switch (rs.getString(5).charAt(0)) {
                case MAJOR_TYPE:
                    e.setType(CompactionType.MAJOR);
                    break;
                case MINOR_TYPE:
                    e.setType(CompactionType.MINOR);
                    break;
                default:
                    //do nothing to handle RU/D if we add another status
                }
                e.setWorkerid(rs.getString(6));
                long start = rs.getLong(7);
                if (!rs.wasNull()) {
                    e.setStart(start);
                }
                long endTime = rs.getLong(8);
                if (endTime != -1) {
                    e.setEndTime(endTime);
                }
                e.setRunAs(rs.getString(9));
                e.setHadoopJobId(rs.getString(10));
                e.setId(rs.getLong(11));
                response.addToCompacts(e);
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
        } catch (SQLException e) {
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "showCompact(" + rqst + ")");
            throw new MetaException(
                    "Unable to select from transaction database " + StringUtils.stringifyException(e));
        } finally {
            closeStmt(stmt);
            closeDbConn(dbConn);
        }
        return response;
    } catch (RetryException e) {
        return showCompact(rqst);
    }
}

From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java

public static synchronized RatingBean save(Connection db, int userId, int projectId, int objectId, String vote,
        String table, String uniqueField, int setInappropriateColumn) throws SQLException {
    boolean commit = false;
    try {//  w  w w .j a  va  2  s .  co m
        commit = db.getAutoCommit();
        if (commit) {
            db.setAutoCommit(false);
        }
        // Determine the current value
        int existingVote = queryUserRating(db, userId, objectId, table, uniqueField);
        int newVote = Integer.parseInt(vote);
        PreparedStatement pst = null;
        ResultSet rs = null;
        // Determine if an update, insert, or delete is required
        if (existingVote == -1) {
            // Perform an insert
            pst = db.prepareStatement("INSERT INTO " + table + "_rating " + "(project_id, "
                    + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : uniqueField + ", ")
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? "inappropriate, " : "")
                    + "rating, enteredby) " + "VALUES (?, "
                    + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : "?, ")
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? "?, " : "") + "?, ?)");
            int i = 0;
            pst.setInt(++i, projectId);
            if (!Project.PRIMARY_KEY.equals(uniqueField)) {
                pst.setInt(++i, objectId);
            }
            if (setInappropriateColumn != Constants.UNDEFINED) {
                pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE));
            }
            pst.setInt(++i, newVote);
            pst.setInt(++i, userId);
            pst.execute();
            pst.close();
        } else if (existingVote != newVote) {
            // Try an update
            pst = db.prepareStatement("UPDATE " + table + "_rating " + "SET rating = ?, entered = "
                    + DatabaseUtils.getCurrentTimestamp(db) + " "
                    + ((setInappropriateColumn != Constants.UNDEFINED) ? ", inappropriate = ? " : "") + "WHERE "
                    + uniqueField + " = ? AND enteredby = ? ");
            int i = 0;
            pst.setInt(++i, newVote);
            if (setInappropriateColumn != Constants.UNDEFINED) {
                pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE));
            }
            pst.setInt(++i, objectId);
            pst.setInt(++i, userId);
            pst.execute();
            pst.close();
        }
        if (existingVote != newVote) {
            // Update the object count and value
            pst = db.prepareStatement("UPDATE " + table + " "
                    + "SET rating_count = rating_count + ?, rating_value = rating_value + ?, "
                    + "rating_avg = ((rating_value + ?) / (rating_count + ?)) " + "WHERE " + uniqueField
                    + " = ? ");
            int i = 0;
            if (existingVote == -1) {
                if (newVote == INAPPROPRIATE_COMMENT) {
                    //rating count is incremented, but no change in rating value, therefore, rating average decreases
                    pst.setInt(++i, 1);
                    pst.setInt(++i, 0);
                    pst.setInt(++i, 0);
                    pst.setInt(++i, 1);
                } else {
                    pst.setInt(++i, 1);
                    pst.setInt(++i, newVote);
                    pst.setInt(++i, newVote);
                    pst.setInt(++i, 1);
                }
            } else {
                if (newVote == INAPPROPRIATE_COMMENT || existingVote == INAPPROPRIATE_COMMENT) {
                    if (newVote == INAPPROPRIATE_COMMENT) {
                        //The effects of the previous rating are reversed.
                        pst.setInt(++i, 0);
                        pst.setInt(++i, (-1) * existingVote);
                        pst.setInt(++i, (-1) * existingVote);
                        pst.setInt(++i, 0);
                    } else if (existingVote == INAPPROPRIATE_COMMENT) {
                        //The new rating by the user is recorded,
                        //as an existing inappropriate comment was never considered towards rating value, no additional math is required
                        pst.setInt(++i, 0);
                        pst.setInt(++i, newVote);
                        pst.setInt(++i, newVote);
                        pst.setInt(++i, 0);
                    }
                } else {
                    pst.setInt(++i, 0);
                    pst.setInt(++i, newVote - existingVote);
                    pst.setInt(++i, newVote - existingVote);
                    pst.setInt(++i, 0);
                }
            }
            pst.setInt(++i, objectId);
            //System.out.println(pst);
            pst.execute();
            pst.close();
        }

        if (setInappropriateColumn != Constants.UNDEFINED) {
            int inappropriateCount = 0;
            pst = db.prepareStatement("SELECT count(*) AS ic " + "FROM " + table + "_rating " + "WHERE "
                    + uniqueField + " = ? AND inappropriate = ?");
            int i = 0;
            pst.setInt(++i, objectId);
            pst.setBoolean(++i, true);
            rs = pst.executeQuery();
            if (rs.next()) {
                inappropriateCount = rs.getInt("ic");
            }
            rs.close();
            pst.close();

            pst = db.prepareStatement("UPDATE " + table + " " + "SET  inappropriate_count = ? " + "WHERE "
                    + uniqueField + " = ? ");
            i = 0;
            pst.setInt(++i, inappropriateCount);
            pst.setInt(++i, objectId);
            pst.execute();
            pst.close();
        }

        // Retrieve the values
        pst = db.prepareStatement(
                "SELECT rating_count, rating_value " + "FROM " + table + " WHERE " + uniqueField + " = ?");
        pst.setInt(1, objectId);
        rs = pst.executeQuery();
        int count = 0;
        int value = 0;
        if (rs.next()) {
            count = rs.getInt("rating_count");
            value = rs.getInt("rating_value");
        }
        rs.close();
        pst.close();
        if (commit) {
            db.commit();
        }
        // Share the rating bean
        RatingBean rating = new RatingBean();
        rating.setItemId(objectId);
        rating.setCount(count);
        rating.setValue(value);
        return rating;
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        LOG.error("save", e);
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

@Override
@RetrySemantics.ReadOnly/*  w ww .  ja v a2 s . c om*/
public GetOpenTxnsInfoResponse getOpenTxnsInfo() throws MetaException {
    try {
        // We need to figure out the current transaction number and the list of
        // open transactions.  To avoid needing a transaction on the underlying
        // database we'll look at the current transaction number first.  If it
        // subsequently shows up in the open list that's ok.
        Connection dbConn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            /**
             * This method can run at READ_COMMITTED as long as long as
             * {@link #openTxns(org.apache.hadoop.hive.metastore.api.OpenTxnRequest)} is atomic.
             * More specifically, as long as advancing TransactionID in NEXT_TXN_ID is atomic with
             * adding corresponding entries into TXNS.  The reason is that any txnid below HWM
             * is either in TXNS and thus considered open (Open/Aborted) or it's considered Committed.
             */
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();
            String s = "select ntxn_next - 1 from NEXT_TXN_ID";
            LOG.debug("Going to execute query <" + s + ">");
            rs = stmt.executeQuery(s);
            if (!rs.next()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, no record found in next_txn_id");
            }
            long hwm = rs.getLong(1);
            if (rs.wasNull()) {
                throw new MetaException(
                        "Transaction tables not properly " + "initialized, null record found in next_txn_id");
            }
            close(rs);
            List<TxnInfo> txnInfos = new ArrayList<TxnInfo>();
            //need the WHERE clause below to ensure consistent results with READ_COMMITTED
            s = "select txn_id, txn_state, txn_user, txn_host, txn_started, txn_last_heartbeat from "
                    + "TXNS where txn_id <= " + hwm;
            LOG.debug("Going to execute query<" + s + ">");
            rs = stmt.executeQuery(s);
            while (rs.next()) {
                char c = rs.getString(2).charAt(0);
                TxnState state;
                switch (c) {
                case TXN_ABORTED:
                    state = TxnState.ABORTED;
                    break;

                case TXN_OPEN:
                    state = TxnState.OPEN;
                    break;

                default:
                    throw new MetaException("Unexpected transaction state " + c + " found in txns table");
                }
                TxnInfo txnInfo = new TxnInfo(rs.getLong(1), state, rs.getString(3), rs.getString(4));
                txnInfo.setStartedTime(rs.getLong(5));
                txnInfo.setLastHeartbeatTime(rs.getLong(6));
                txnInfos.add(txnInfo);
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
            return new GetOpenTxnsInfoResponse(hwm, txnInfos);
        } catch (SQLException e) {
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "getOpenTxnsInfo");
            throw new MetaException("Unable to select from transaction database: " + getMessage(e)
                    + StringUtils.stringifyException(e));
        } finally {
            close(rs, stmt, dbConn);
        }
    } catch (RetryException e) {
        return getOpenTxnsInfo();
    }
}

From source file:no.kantega.publishing.common.ao.ContentAOJdbcImpl.java

@Override
public Content checkInContent(Content content, ContentStatus newStatus) throws SystemException {
    Connection c = null;

    try {//  www . j  a va  2s  . c o  m
        c = dbConnectionFactory.getConnection();

        // We only use transactions if it has been enabled
        if (dbConnectionFactory.useTransactions()) {
            c.setAutoCommit(false);
        }

        // Try to lock content in database
        addContentTransactionLock(content.getId(), c);

        boolean isNew = content.isNew();

        boolean newVersionIsActive = false;

        // Insert base information, no history
        insertOrUpdateContentTable(c, content);

        if (newStatus != ContentStatus.GHOSTDRAFT || content.getStatus() == newStatus) {
            deleteTempContentVersion(content);
        }

        if (newStatus == ContentStatus.PUBLISHED || newStatus == ContentStatus.PUBLISHED_WAITING) { //waiting hearing
            deleteOldGhostdrafts(content);
        }

        if (isNew || newStatus == ContentStatus.PUBLISHED) {
            newVersionIsActive = true;
            //                deleteOldGhostdrafts(content);
        }

        if (!isNew) {
            newVersionIsActive = archiveOldVersion(c, content, newStatus, newVersionIsActive);
        }

        addContentVersion(c, content, newStatus, newVersionIsActive);

        setVersionAsActive(c, content);

        // Add page attributes
        insertAttributes(c, content, AttributeDataType.CONTENT_DATA);
        insertAttributes(c, content, AttributeDataType.META_DATA);

        // Insert associations if new
        List<Association> associations = content.getAssociations();
        for (Association association : associations) {
            if (association.getId() == -1) {
                // New association: add
                association.setContentId(content.getId());
                AssociationAO.addAssociation(association);
            }
        }

        // Update contentid on attachments saved in database before the page was saved
        List<Attachment> attachments = content.getAttachments();
        if (attachments != null) {
            for (Attachment a : attachments) {
                if (a.getContentId() == -1) {
                    a.setContentId(content.getId());
                    attachmentAO.setAttachment(a);
                }
            }
        }

        // Update contentid on multimedia saved in database before the page was saved
        List<Multimedia> multimedia = content.getMultimedia();
        if (multimedia != null && !multimedia.isEmpty()) {
            try (PreparedStatement st = c
                    .prepareStatement("update multimedia set ContentId = ?  where Id = ?")) {
                for (Multimedia m : multimedia) {
                    st.setInt(1, content.getId());
                    st.setInt(2, m.getId());
                    st.addBatch();
                }
                st.executeBatch();
            }
        }

        // Delete all existing topic associations before insertion.
        topicDao.deleteTopicAssociationsForContent(content.getId());

        // Insert topics
        List<Topic> topics = content.getTopics();
        if (topics != null) {
            for (Topic t : topics) {
                topicDao.addTopicToContentAssociation(t, content.getId());
            }
        }

        // Get old version if exists
        Content oldContent = null;
        if (!isNew) {
            ContentIdentifier oldCid = ContentIdentifier
                    .fromAssociationId(content.getAssociation().getAssociationId());
            oldContent = getContent(oldCid, true);
        }

        // Update subpages if these fields are changed
        if (oldContent != null) {
            if (!oldContent.getOwner().equals(content.getOwner())) {
                updateChildren(content.getAssociation().getId(), "owner", content.getOwner(),
                        oldContent.getOwner());
            }
            if (!oldContent.getOwnerPerson().equals(content.getOwnerPerson())) {
                updateChildren(content.getAssociation().getId(), "ownerperson", content.getOwnerPerson(),
                        oldContent.getOwnerPerson());
            }
            if (oldContent.getGroupId() != content.getGroupId()) {
                updateChildren(content.getAssociation().getId(), "GroupId",
                        String.valueOf(content.getGroupId()), String.valueOf(oldContent.getGroupId()));
            }
        }

        // Set page as not checked out
        content.setIsCheckedOut(false);

        // Mark as not modified
        content.setIsModified(false);

        // Remove lock
        removeContentTransactionLock(content.getId(), c);

        // We only use transactions for databases which support it
        if (dbConnectionFactory.useTransactions()) {
            c.commit();
        }
    } catch (TransactionLockException tle) {
        if (c != null) {
            try {
                if (dbConnectionFactory.useTransactions()) {
                    c.rollback();
                }
            } catch (SQLException e1) {
                log.error("Error rolling back transaction", e1);
            }
        }
        throw tle;
    } catch (Exception e) {
        if (c != null) {
            try {
                if (dbConnectionFactory.useTransactions()) {
                    c.rollback();
                }
            } catch (SQLException e1) {
                log.error("Error rolling back transaction", e);
            }
        }
        throw new SystemException("Feil ved lagring", e);
    } finally {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            // Could not close connection, probably closed already
        }
        if (!dbConnectionFactory.useTransactions()) {
            // Remove lock
            try {
                removeContentTransactionLock(content.getId(), c);
            } catch (SQLException e) {
                log.error("Error when removeContentTransactionLock for " + content.getId(), e);
            }
        }
    }

    // Delete old versions (only keep last n versions)
    ContentTemplate ct = contentTemplateAO.getTemplateById(content.getContentTemplateId());

    int keepVersions = ct.computeKeepVersions();
    // -1 = keep all versions
    if (keepVersions != -1) {
        deleteOldContentVersions(content, keepVersions);
    }

    // Set new status
    content.setStatus(newStatus);

    return content;
}

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;/*from  w  w  w.jav a 2s.c  o m*/
    Connection conn = null;

    if (conn == null) {

        try {
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {

                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=10737418");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        System.out.println("FAILED QUERY1==" + insert1);
                        System.out.println("FAILED QUERY2==" + insert2);
                        sqle.printStackTrace();
                        System.exit(1);
                    }
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

                conn.close();
                conn = null;
            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}

From source file:com.netflix.metacat.usermetadata.mysql.MysqlUserMetadataService.java

@Override
public void saveMetadatas(final String user, final List<? extends HasMetadata> metadatas, final boolean merge) {
    try {//from w  ww .java 2 s  .co m
        final Connection conn = poolingDataSource.getConnection();
        try {
            @SuppressWarnings("unchecked")
            final List<List<HasMetadata>> subLists = Lists.partition((List<HasMetadata>) metadatas,
                    config.getUserMetadataMaxInClauseItems());
            for (List<HasMetadata> hasMetadatas : subLists) {
                final List<String> uris = Lists.newArrayList();
                final List<QualifiedName> names = Lists.newArrayList();
                // Get the names and uris
                final List<HasDefinitionMetadata> definitionMetadatas = Lists.newArrayList();
                final List<HasDataMetadata> dataMetadatas = Lists.newArrayList();
                hasMetadatas.stream().forEach(hasMetadata -> {
                    if (hasMetadata instanceof HasDefinitionMetadata) {
                        final HasDefinitionMetadata oDef = (HasDefinitionMetadata) hasMetadata;
                        names.add(oDef.getDefinitionName());
                        if (oDef.getDefinitionMetadata() != null) {
                            definitionMetadatas.add(oDef);
                        }
                    }
                    if (hasMetadata instanceof HasDataMetadata) {
                        final HasDataMetadata oData = (HasDataMetadata) hasMetadata;
                        if (oData.isDataExternal() && oData.getDataMetadata() != null
                                && oData.getDataMetadata().size() > 0) {
                            uris.add(oData.getDataUri());
                            dataMetadatas.add(oData);
                        }
                    }
                });
                if (!definitionMetadatas.isEmpty() || !dataMetadatas.isEmpty()) {
                    // Get the existing metadata based on the names and uris
                    final Map<String, ObjectNode> definitionMap = getDefinitionMetadataMap(names);
                    final Map<String, ObjectNode> dataMap = getDataMetadataMap(uris);
                    // Curate the list of existing and new metadatas
                    final List<Object[]> insertDefinitionMetadatas = Lists.newArrayList();
                    final List<Object[]> updateDefinitionMetadatas = Lists.newArrayList();
                    final List<Object[]> insertDataMetadatas = Lists.newArrayList();
                    final List<Object[]> updateDataMetadatas = Lists.newArrayList();
                    definitionMetadatas.stream().forEach(oDef -> {
                        final QualifiedName qualifiedName = oDef.getDefinitionName();
                        if (qualifiedName != null && oDef.getDefinitionMetadata() != null
                                && oDef.getDefinitionMetadata().size() != 0) {
                            final String name = qualifiedName.toString();
                            final ObjectNode oNode = definitionMap.get(name);
                            if (oNode == null) {
                                insertDefinitionMetadatas.add(
                                        new Object[] { metacatJson.toJsonString(oDef.getDefinitionMetadata()),
                                                user, user, name, });
                            } else {
                                metacatJson.mergeIntoPrimary(oNode, oDef.getDefinitionMetadata());
                                updateDefinitionMetadatas
                                        .add(new Object[] { metacatJson.toJsonString(oNode), user, name });
                            }
                        }
                    });
                    dataMetadatas.stream().forEach(oData -> {
                        final String uri = oData.getDataUri();
                        final ObjectNode oNode = dataMap.get(uri);
                        if (oData.getDataMetadata() != null && oData.getDataMetadata().size() != 0) {
                            if (oNode == null) {
                                insertDataMetadatas.add(new Object[] {
                                        metacatJson.toJsonString(oData.getDataMetadata()), user, user, uri, });
                            } else {
                                metacatJson.mergeIntoPrimary(oNode, oData.getDataMetadata());
                                updateDataMetadatas
                                        .add(new Object[] { metacatJson.toJsonString(oNode), user, uri });
                            }
                        }
                    });
                    //Now run the queries
                    final QueryRunner runner = new QueryRunner();
                    if (!insertDefinitionMetadatas.isEmpty()) {
                        runner.batch(conn, SQL.INSERT_DEFINITION_METADATA, insertDefinitionMetadatas
                                .toArray(new Object[insertDefinitionMetadatas.size()][4]));
                    }
                    if (!updateDefinitionMetadatas.isEmpty()) {
                        runner.batch(conn, SQL.UPDATE_DEFINITION_METADATA, updateDefinitionMetadatas
                                .toArray(new Object[updateDefinitionMetadatas.size()][3]));
                    }
                    if (!insertDataMetadatas.isEmpty()) {
                        runner.batch(conn, SQL.INSERT_DATA_METADATA,
                                insertDataMetadatas.toArray(new Object[insertDataMetadatas.size()][4]));
                    }
                    if (!updateDataMetadatas.isEmpty()) {
                        runner.batch(conn, SQL.UPDATE_DATA_METADATA,
                                updateDataMetadatas.toArray(new Object[updateDataMetadatas.size()][3]));
                    }
                }
            }
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    } catch (SQLException e) {
        log.error("Sql exception", e);
        throw new UserMetadataServiceException("Failed to save metadata", e);
    }
}

From source file:dao.PersonalinfoDaoDb.java

/**
 * Given a login return the updated personal info page.
 * @param member//from   w  w w.  j  a  va2s .c  o  m
 * @param dob
 * @param title
 * @param ihave
 * @param iwant
 * @param industry
 * @param company
 * @param pwebsite
 * @param cwebsite
 * @param blogsite
 * @param education
 * @param city
 * @param state
 * @param country
 * @param description
 * @param interests
 * @param zipcode
 * @param pm
 * @param bb
 * @param fd
 * @param mykeywords
 * @param yourkeywords
 * @param fname
 * @param lname
 * @param mname
 * @param email
 * @param gender
 * @param nickname
 * @param designation
 * @param bcity
 * @param bstate
 * @param bcountry
 * @param bzipcode
 * @param hphone
 * @param cphone
 * @param bphone
 * @param blobStreamLabel 
 * @param docLabel - the documents label
 * @param password - password
 * @param street - street
 * @param bstreet - busstreet
 * @param zone - zone
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void updatePersonalinfo(String member, String dob, String title, String ihave, String iwant,
        String industry, String company, String pwebsite, String cwebsite, String blogsite, String education,
        String city, String state, String country, String description, String interests, String zipcode, int pm,
        int bb, int fd, String mykeywords, String yourkeywords, String fname, String lname, String mname,
        String email, int gender, String nickname, String designation, String bcity, String bstate,
        String bcountry, String bzipcode, String hphone, String cphone, String bphone, String yim, String aim,
        String msn, String icq, String blobStreamLabel, String docLabel, String password, String street,
        String bstreet, String zone, String contact) throws BaseDaoException {

    Hdlogin hdlogin = getLoginid(member);
    if (hdlogin == null) {
        throw new BaseDaoException("hdlogin is null for member " + member);
    }

    String memberId = hdlogin.getValue(DbConstants.LOGIN_ID);
    if (RegexStrUtil.isNull(memberId)) {
        throw new BaseDaoException("memberId is null for member " + member);
    }

    Object[] params = { (Object) memberId };

    boolean myUsertabExists, myHdprofileExists, myKeywordsExists, yourKeywordExists;
    myUsertabExists = myHdprofileExists = myKeywordsExists = yourKeywordExists = false;

    myUsertabExists = doesMyUserTabExist(params);
    myHdprofileExists = doesMyHdprofileExist(params);
    myKeywordsExists = doesMyKeywordExist(params);
    yourKeywordExists = doesYourKeywordExist(params);

    /**
     *  Get scalability datasource for usertab/hdprofile/mykeywords/yourkeywords - not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, updatePersonalInfo() " + sourceName);
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);

        /**
         *  hdlogin is not partitioned 
         */
        updateHdloginQuery.run(conn, memberId, fname, lname, mname, email, password, contact);

        // no entry? add entry 
        if (!myUsertabExists) {
            String[] myparams = new String[35];
            myparams[0] = dob;
            myparams[1] = title;
            myparams[2] = ihave;
            myparams[3] = iwant;
            myparams[4] = industry;
            myparams[5] = company;
            myparams[6] = pwebsite;
            myparams[7] = cwebsite;
            myparams[8] = blogsite;
            myparams[9] = education;
            myparams[10] = city;
            myparams[11] = state;
            myparams[12] = country;
            myparams[13] = description;
            myparams[14] = interests;
            myparams[15] = zipcode;
            myparams[16] = new Integer(gender).toString();
            myparams[17] = nickname;
            myparams[18] = designation;
            myparams[19] = bcity;
            myparams[20] = bstate;
            myparams[21] = bcountry;
            myparams[22] = bzipcode;
            myparams[23] = hphone;
            myparams[24] = cphone;
            myparams[25] = bphone;
            myparams[26] = yim;
            myparams[27] = aim;
            myparams[28] = msn;
            myparams[29] = icq;
            // memberid is the LAST_INSERT_ID
            myparams[30] = blobStreamLabel;
            myparams[31] = docLabel;
            myparams[32] = street;
            myparams[33] = bstreet;
            myparams[34] = zone;

            String queryName = scalabilityManager.getWriteZeroScalability("personalinfoaddquery");
            addUserQuery = getQueryMapper().getCommonQuery(queryName);
            addUserQuery.run(conn, myparams);
            //addUserQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone,  yim, aim, msn,icq, memberId, blobStreamLabel, docLabel);
        } else {
            // exists! update entry
            updateQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite,
                    education, city, state, country, description, interests, zipcode, gender, nickname,
                    designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq,
                    memberId, blobStreamLabel, docLabel, street, bstreet, zone);
        }

        /**
         *  hdprofile - not partitioned
              *  no entry? add entry
           addUserQuery.run(conn, params);
           //addUserQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone,  yim, aim, msn,icq, memberId, blobStreamLabel, docLabel);
             } else {
                // exists! update entry
           updateQuery.run(conn, dob, title, ihave, iwant, industry, company, pwebsite, cwebsite, blogsite, education, city, state, country, description, interests, zipcode, gender, nickname, designation, bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, memberId, blobStreamLabel, docLabel);
             }
                
        /**
         *  hdprofile - not partitioned
              *  no entry? add entry
         */
        if (!myHdprofileExists) {
            String pmStr = new Integer(pm).toString();
            String bbStr = new Integer(bb).toString();
            String fdStr = new Integer(fd).toString();
            String profileParams[] = { pmStr, bbStr, fdStr, memberId };

            String queryName = scalabilityManager.getWriteZeroScalability("addpreferencesquery");
            addPreferencesQuery = getQueryMapper().getCommonQuery(queryName);
            addPreferencesQuery.run(conn, profileParams);
        } else {
            /**
            *  add entry in hdprofile - not partitioned
             **/
            profileUpdateQuery.run(conn, pm, bb, fd, memberId);
        }

        /**
         *  mykeywords - not partitioned
         *  Add mykeywords
              *  exists! zap keywords
         */
        if (myKeywordsExists) {
            myKeywordsDeleteQuery.run(conn, memberId);
        }
        if (!RegexStrUtil.isNull(mykeywords)) {
            String[] mykeys = mykeywords.split(",");
            for (int i = 0; i < mykeys.length; i++) {
                myKeywordsAddQuery.run(conn, mykeys[i], memberId);
            }
        }

        /**
         *  Add yourkeywords
         *  yourkeywords - not partitioned
         */
        if (yourKeywordExists) {
            yourKeywordsDeleteQuery.run(conn, memberId);
        }
        if (!RegexStrUtil.isNull(yourkeywords)) {
            String[] yourkeys = yourkeywords.split(",");
            for (int i = 0; i < yourkeys.length; i++) {
                yourKeywordsAddQuery.run(conn, yourkeys[i], memberId);
            }
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "connection close exception for preferences/deleting/adding keywords", e2);
            }
            throw new BaseDaoException(
                    "error occured while rollingback entries updateing preferences/deleting/adding mykeywords/your keywords ",
                    e1);
        }
        throw new BaseDaoException(
                "error occured while updating preferences/deleting/adding mykeywords/yourkeywords", e);
    }

    // committing transaction
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit exception for preferences/deleting/adding keywords", e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("connection close exception", e1);
        }

        throw new BaseDaoException("connection close exception for preferences/deleting/adding keywords", e4);
    }

    // currently not used as it always updates it
    Fqn fqn = cacheUtil.fqn(DbConstants.ID_INFO);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.LOGIN_INFO);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    Object dirs = null;
    fqn = cacheUtil.fqn(DbConstants.AUTHORS_DIRECTORIES);
    if (treeCache.exists(fqn, member)) {
        dirs = treeCache.get(fqn, member);
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.AUTHOR_BLOCKED_DIRS);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_COPY);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_MOVE);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    StringBuffer sb = new StringBuffer();
    if (dirs != null) {
        for (int i = 0; i < ((List) dirs).size(); i++) {
            String directoryId = ((Directory) ((List) dirs).get(i)).getValue(DbConstants.DIRECTORY_ID);
            sb.delete(0, sb.length());
            sb.append(directoryId);
            sb.append("-");
            sb.append(memberId);
            String key = sb.toString();
            fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
            if (treeCache.exists(fqn, key)) {
                treeCache.remove(fqn, key);
            }

            fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
            if (treeCache.exists(fqn, directoryId)) {
                treeCache.remove(fqn, directoryId);
            }
        }
    }
    /*
    fqn = cacheUtil.fqn(DbConstants.COLLABRUM_LIST);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }
    */

    // delete collabrum related cache
    Object collabrums = null;
    fqn = cacheUtil.fqn(DbConstants.MEM_AS_ORGANIZER_LIST);
    if (treeCache.exists(fqn, member)) {
        collabrums = treeCache.get(fqn, member);
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.BLOCKED_COLLABRUM_LIST);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    /** get authors related collabrums */
    if (collabrums != null) {
        for (int i = 0; i < ((List) collabrums).size(); i++) {
            String collabrumId = ((Collabrum) ((List) collabrums).get(i)).getValue(DbConstants.COLLABRUM_ID);

            /*
                       fqn = cacheUtil.fqn(DbConstants.COLLABRUM_EDIT);
                       if (treeCache.exists(fqn, collabrumId)) {
                           treeCache.remove(fqn, collabrumId);
                       } 
            */

            fqn = cacheUtil.fqn(DbConstants.COLLABRUM);
            if (treeCache.exists(fqn, collabrumId)) {
                treeCache.remove(fqn, collabrumId);
            }

            fqn = cacheUtil.fqn(DbConstants.ORGANIZERS);
            if (treeCache.exists(fqn, collabrumId)) {
                treeCache.remove(fqn, collabrumId);
            }

            sb.delete(0, sb.length());
            sb.append(collabrumId);
            sb.append("-");
            sb.append(memberId);
            fqn = cacheUtil.fqn(DbConstants.ORGANIZER);
            if (treeCache.exists(fqn, sb.toString())) {
                treeCache.remove(fqn, sb.toString());
            }
        }
    }
}

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.
 * // w  ww .j av  a  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);
        }
    }
}