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:org.apache.hadoop.hive.metastore.txn.TxnHandler.java

@Override
@RetrySemantics.Idempotent// w  ww.j a  va 2s . c  om
public CompactionResponse compact(CompactionRequest rqst) throws MetaException {
    // Put a compaction request in the queue.
    try {
        Connection dbConn = null;
        Statement stmt = null;
        TxnStore.MutexAPI.LockHandle handle = null;
        try {
            lockInternal();
            /**
             * MUTEX_KEY.CompactionScheduler lock ensures that there is only 1 entry in
             * Initiated/Working state for any resource.  This ensures that we don't run concurrent
             * compactions for any resource.
             */
            handle = getMutexAPI().acquireLock(MUTEX_KEY.CompactionScheduler.name());
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();

            long id = generateCompactionQueueId(stmt);

            StringBuilder sb = new StringBuilder("select cq_id, cq_state from COMPACTION_QUEUE where")
                    .append(" cq_state IN(").append(quoteChar(INITIATED_STATE)).append(",")
                    .append(quoteChar(WORKING_STATE)).append(") AND cq_database=")
                    .append(quoteString(rqst.getDbname())).append(" AND cq_table=")
                    .append(quoteString(rqst.getTablename())).append(" AND ");
            if (rqst.getPartitionname() == null) {
                sb.append("cq_partition is null");
            } else {
                sb.append("cq_partition=").append(quoteString(rqst.getPartitionname()));
            }

            LOG.debug("Going to execute query <" + sb.toString() + ">");
            ResultSet rs = stmt.executeQuery(sb.toString());
            if (rs.next()) {
                long enqueuedId = rs.getLong(1);
                String state = compactorStateToResponse(rs.getString(2).charAt(0));
                LOG.info("Ignoring request to compact " + rqst.getDbname() + "/" + rqst.getTablename() + "/"
                        + rqst.getPartitionname() + " since it is already " + quoteString(state) + " with id="
                        + enqueuedId);
                return new CompactionResponse(enqueuedId, state, false);
            }
            close(rs);
            StringBuilder buf = new StringBuilder(
                    "insert into COMPACTION_QUEUE (cq_id, cq_database, " + "cq_table, ");
            String partName = rqst.getPartitionname();
            if (partName != null)
                buf.append("cq_partition, ");
            buf.append("cq_state, cq_type");
            if (rqst.getProperties() != null) {
                buf.append(", cq_tblproperties");
            }
            if (rqst.getRunas() != null)
                buf.append(", cq_run_as");
            buf.append(") values (");
            buf.append(id);
            buf.append(", '");
            buf.append(rqst.getDbname());
            buf.append("', '");
            buf.append(rqst.getTablename());
            buf.append("', '");
            if (partName != null) {
                buf.append(partName);
                buf.append("', '");
            }
            buf.append(INITIATED_STATE);
            buf.append("', '");
            switch (rqst.getType()) {
            case MAJOR:
                buf.append(MAJOR_TYPE);
                break;

            case MINOR:
                buf.append(MINOR_TYPE);
                break;

            default:
                LOG.debug("Going to rollback");
                dbConn.rollback();
                throw new MetaException("Unexpected compaction type " + rqst.getType().toString());
            }
            if (rqst.getProperties() != null) {
                buf.append("', '");
                buf.append(new StringableMap(rqst.getProperties()).toString());
            }
            if (rqst.getRunas() != null) {
                buf.append("', '");
                buf.append(rqst.getRunas());
            }
            buf.append("')");
            String s = buf.toString();
            LOG.debug("Going to execute update <" + s + ">");
            stmt.executeUpdate(s);
            LOG.debug("Going to commit");
            dbConn.commit();
            return new CompactionResponse(id, INITIATED_RESPONSE, true);
        } catch (SQLException e) {
            LOG.debug("Going to rollback");
            rollbackDBConn(dbConn);
            checkRetryable(dbConn, e, "compact(" + rqst + ")");
            throw new MetaException(
                    "Unable to select from transaction database " + StringUtils.stringifyException(e));
        } finally {
            closeStmt(stmt);
            closeDbConn(dbConn);
            if (handle != null) {
                handle.releaseLocks();
            }
            unlockInternal();
        }
    } catch (RetryException e) {
        return compact(rqst);
    }
}

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

public void run() {

    BufferedReader d = null;/*  www.j a  v  a  2s  . com*/
    Connection conn = null;

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

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    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++) {
            if (!stikyconnection) {
                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) {
                    for (int icon = 0; icon <= 3; icon++) {
                        try {
                            Thread.sleep(10000);
                            SoftReference sf = new SoftReference(
                                    DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                            conn = (Connection) sf.get();
                        } catch (SQLException ex2) {
                            ex2.printStackTrace();
                        }
                    }
                    //ex.printStackTrace();
                }

            }
            if (conn != null) {
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");

                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 = executeSQL(stmt);
                    //                            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 (SQLException 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();
                    if (conn != null && !conn.isClosed()) {
                        try {
                            stmt.addBatch("COMMIT");
                            executeSQL(stmt);
                        } catch (SQLException sqle) {
                            System.out.println(
                                    "#####################\n[Warning] Cannot explicitly commit given error\n#################");
                            conn.close();
                            continue;
                        }
                    } else {
                        System.out.println(
                                "#####################\n[Warning] Cannot explicitly commit given connection was interrupted unexpectedly\n#################");
                    }
                    //                            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.cocoon.acting.modular.DatabaseAction.java

/**
 * Add a record to the database.  This action assumes that
 * the file referenced by the "descriptor" parameter conforms
 * to the AbstractDatabaseAction specifications.
 *//*ww  w  .ja  v a 2 s . co  m*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param)
        throws Exception {

    DataSourceComponent datasource = null;
    Connection conn = null;
    Map results = new HashMap();
    int rows = 0;
    boolean failed = false;

    // read global parameter settings
    boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;

    // call specific default modes apart from output mode are not supported
    // set request attribute
    String outputMode = param.getParameter("output", (String) defaultModeNames.get(MODE_OUTPUT));

    if (this.settings.containsKey("reloadable")) {
        reloadable = Boolean.valueOf((String) this.settings.get("reloadable")).booleanValue();
    }
    // read local parameter settings
    try {
        Configuration conf = this.getConfiguration(
                param.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver,
                param.getParameterAsBoolean("reloadable", reloadable));

        // get database connection and try to turn off autocommit
        datasource = this.getDataSource(conf, param);
        conn = datasource.getConnection();
        if (conn.getAutoCommit() == true) {
            try {
                conn.setAutoCommit(false);
            } catch (Exception ex) {
                String tmp = param.getParameter("use-transactions",
                        (String) this.settings.get("use-transactions", null));
                if (tmp != null && (tmp.equalsIgnoreCase("no") || tmp.equalsIgnoreCase("false")
                        || tmp.equalsIgnoreCase("0"))) {
                    if (getLogger().isErrorEnabled())
                        getLogger().error(
                                "This DB connection does not support transactions. If you want to risk your data's integrity by continuing nonetheless set parameter \"use-transactions\" to \"no\".");
                    throw ex;
                }
            }
        }

        // find tables to work with
        Configuration[] tables = conf.getChildren("table");
        String tablesetname = param.getParameter("table-set", (String) this.settings.get("table-set"));

        Map modeTypes = null;

        if (tablesetname == null) {
            modeTypes = new HashMap(6);
            modeTypes.put(MODE_AUTOINCR, "autoincr");
            modeTypes.put(MODE_OTHERS, "others");
            modeTypes.put(MODE_OUTPUT, outputMode);
            for (int i = 0; i < tables.length; i++) {
                rows += processTable(tables[i], conn, objectModel, results, modeTypes);
            }
        } else {
            // new set based behaviour

            // create index for table names / aliases
            Map tableIndex = new HashMap(2 * tables.length);
            String tableName = null;
            Object result = null;
            for (int i = 0; i < tables.length; i++) {
                tableName = tables[i].getAttribute("alias", tables[i].getAttribute("name", ""));
                result = tableIndex.put(tableName, new Integer(i));
                if (result != null) {
                    throw new IOException(
                            "Duplicate table entry for " + tableName + " at positions " + result + " and " + i);
                }
            }

            Configuration[] tablesets = conf.getChildren("table-set");
            String setname = null;
            boolean found = false;

            // find tables contained in tableset
            int j = 0;
            for (j = 0; j < tablesets.length; j++) {
                setname = tablesets[j].getAttribute("name", "");
                if (tablesetname.trim().equals(setname.trim())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new IOException(" given set " + tablesetname + " does not exists in a description file.");
            }

            Configuration[] set = tablesets[j].getChildren("table");

            for (int i = 0; i < set.length; i++) {
                // look for alternative mode types
                modeTypes = new HashMap(6);
                modeTypes.put(MODE_AUTOINCR, set[i].getAttribute("autoincr-mode", "autoincr"));
                modeTypes.put(MODE_OTHERS, set[i].getAttribute("others-mode", "others"));
                modeTypes.put(MODE_OUTPUT, outputMode);
                tableName = set[i].getAttribute("name", "");
                if (tableIndex.containsKey(tableName)) {
                    j = ((Integer) tableIndex.get(tableName)).intValue();
                    rows += processTable(tables[j], conn, objectModel, results, modeTypes);
                } else {
                    throw new IOException(
                            " given table " + tableName + " does not exists in a description file.");
                }
            }
        }

        if (conn.getAutoCommit() == false) {
            conn.commit();
        }

        // obtain output mode module and rollback output
        ServiceSelector outputSelector = null;
        OutputModule output = null;
        try {
            outputSelector = (ServiceSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR);
            if (outputMode != null && outputSelector != null && outputSelector.isSelectable(outputMode)) {
                output = (OutputModule) outputSelector.select(outputMode);
            }
            if (output != null) {
                output.commit(null, objectModel);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn("Could not select output mode " + outputMode);
            }
        } catch (ServiceException e) {
            if (getLogger().isWarnEnabled()) {
                getLogger().warn("Could not select output mode " + outputMode + ":" + e.getMessage());
            }
        } finally {
            if (outputSelector != null) {
                if (output != null) {
                    outputSelector.release(output);
                }
                this.manager.release(outputSelector);
            }
        }
    } catch (Exception e) {
        failed = true;
        if (conn != null) {
            try {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Rolling back transaction. Caused by " + e.getMessage());
                    e.printStackTrace();
                }
                conn.rollback();
                results = null;

                // obtain output mode module and commit output
                ServiceSelector outputSelector = null;
                OutputModule output = null;
                try {
                    outputSelector = (ServiceSelector) this.manager.lookup(OUTPUT_MODULE_SELECTOR);
                    if (outputMode != null && outputSelector != null
                            && outputSelector.isSelectable(outputMode)) {
                        output = (OutputModule) outputSelector.select(outputMode);
                    }
                    if (output != null) {
                        output.rollback(null, objectModel, e);
                    } else if (getLogger().isWarnEnabled()) {
                        getLogger().warn("Could not select output mode " + outputMode);
                    }
                } catch (ServiceException e2) {
                    if (getLogger().isWarnEnabled()) {
                        getLogger().warn("Could not select output mode " + outputMode + ":" + e2.getMessage());
                    }
                } finally {
                    if (outputSelector != null) {
                        if (output != null) {
                            outputSelector.release(output);
                        }
                        this.manager.release(outputSelector);
                    }
                }
            } catch (SQLException se) {
                if (getLogger().isDebugEnabled())
                    getLogger().debug("There was an error rolling back the transaction", se);
            }
        }

        //throw new ProcessingException("Could not add record :position = " + currentIndex, e);

        // don't throw an exception, an error has been signalled, that should suffice

        String throwException = (String) this.settings.get("throw-exception",
                param.getParameter("throw-exception", null));
        if (throwException != null && BooleanUtils.toBoolean(throwException)) {
            throw new ProcessingException("Cannot process the requested SQL statement ", e);
        }
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqe) {
                getLogger().warn("There was an error closing the datasource", sqe);
            }
        }

        if (datasource != null)
            this.dbselector.release(datasource);
    }
    if (results != null) {
        if (rows > 0 || (!failed && !this.failOnEmpty)) {
            results.put("row-count", new Integer(rows));
        } else {
            results = null;
        }
    } else {
        if (rows > 0) {
            results = new HashMap(1);
            results.put("row-count", new Integer(rows));
        }
    }

    return results; // (results == null? results : Collections.unmodifiableMap(results));
}

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> wfrequest)
        throws ProvisioningException {
    User foundUser = null;//from  w w w .ja  v  a 2 s. co m

    int approvalID = 0;

    if (wfrequest.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) wfrequest.get("APPROVAL_ID");
    }

    Workflow workflow = (Workflow) wfrequest.get("WORKFLOW");

    Set<String> attributesForSearch = new HashSet<String>();
    attributesForSearch.addAll(attributes);
    if (!attributesForSearch.contains(this.userPrimaryKey)) {
        attributesForSearch.add(this.userPrimaryKey);
    }

    try {
        //logger.info("Lookin up user : " + user.getUserID());
        foundUser = this.findUser(user.getUserID(), attributesForSearch, wfrequest);
        //logger.info("Lookin up user result : " + foundUser);

        if (foundUser == null) {
            this.createUser(user, attributes, wfrequest);
            return;
        }
    } catch (Exception e) {
        //logger.info("Creating new user",e);
        if (logger.isDebugEnabled()) {
            logger.debug("Could not create user", e);
        }
        this.createUser(user, attributes, wfrequest);
        return;
    }

    String userID = foundUser.getAttribs().get(this.userPrimaryKey).getValues().get(0);
    int userIDnum = -1;

    try {
        userIDnum = Integer.parseInt(userID);
    } catch (Throwable t) {
        //do nothing
    }

    Connection con;
    try {
        con = this.ds.getConnection();
    } catch (SQLException e) {
        throw new ProvisioningException("Could not obtain connection", e);
    }

    try {
        con.setAutoCommit(false);
        Map<String, Object> request = new HashMap<String, Object>();
        if (this.customDBProvider != null) {
            this.customDBProvider.beginUpdate(con, userIDnum, request);
        }

        StringBuffer b = new StringBuffer();
        for (String attrName : attributes) {
            if (user.getAttribs().containsKey(attrName) && foundUser.getAttribs().containsKey(attrName)
                    && !user.getAttribs().get(attrName).getValues().get(0)
                            .equals(foundUser.getAttribs().get(attrName).getValues().get(0))) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.updateField(con, userIDnum, request, attrName,
                            foundUser.getAttribs().get(attrName).getValues().get(0),
                            user.getAttribs().get(attrName).getValues().get(0));

                } else {
                    PreparedStatement ps = updateField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID,
                        workflow, attrName, user.getAttribs().get(attrName).getValues().get(0));

            } else if (user.getAttribs().containsKey(attrName)
                    && !foundUser.getAttribs().containsKey(attrName)) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.updateField(con, userIDnum, request, attrName, null,
                            user.getAttribs().get(attrName).getValues().get(0));
                } else {
                    PreparedStatement ps = updateField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                        workflow, attrName, user.getAttribs().get(attrName).getValues().get(0));

            } else if (!user.getAttribs().containsKey(attrName) && foundUser.getAttribs().containsKey(attrName)
                    && !addOnly) {
                if (this.customDBProvider != null) {
                    this.customDBProvider.clearField(con, userIDnum, request, attrName,
                            foundUser.getAttribs().get(attrName).getValues().get(0));
                } else {
                    PreparedStatement ps = clearField(user, con, b, attrName, userID, userIDnum);
                }

                this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete, approvalID,
                        workflow, attrName, foundUser.getAttribs().get(attrName).getValues().get(0));
            }
        }

        if (this.customDBProvider != null) {
            this.customDBProvider.completeUpdate(con, userIDnum, request);
        }

        switch (this.groupMode) {
        case None:
            break;
        case One2Many:

            b.setLength(0);
            b.append("INSERT INTO ").append(this.groupTable).append(" (");
            this.getFieldName(this.groupName, b).append(",");
            this.getFieldName(this.groupUserKey, b).append(") VALUES (?,?)");
            PreparedStatement ps = con.prepareStatement(b.toString());

            for (String groupName : user.getGroups()) {
                if (!foundUser.getGroups().contains(groupName)) {
                    ps.setString(1, groupName);
                    ps.setInt(2, userIDnum);
                    ps.executeUpdate();

                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                            workflow, "group", groupName);
                }
            }

            b.setLength(0);
            b.append("DELETE FROM ").append(this.groupTable).append(" WHERE ");
            this.getFieldName(this.groupUserKey, b).append("=? AND ");
            this.getFieldName(this.groupName, b).append("=?");
            ps = con.prepareStatement(b.toString());

            if (!addOnly) {
                for (String groupName : foundUser.getGroups()) {
                    if (!user.getGroups().contains(groupName)) {
                        ps.setInt(1, userIDnum);
                        ps.setString(2, groupName);
                        ps.executeUpdate();
                        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete,
                                approvalID, workflow, "group", groupName);
                    }
                }
            }

            break;
        case Many2Many:
            many2manySyncGroups(user, addOnly, foundUser, userIDnum, con, b, wfrequest);
            break;
        case Custom:
            for (String groupName : user.getGroups()) {
                if (!foundUser.getGroups().contains(groupName)) {
                    this.customDBProvider.addGroup(con, userIDnum, groupName);
                    this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID,
                            workflow, "group", groupName);
                }
            }

            if (!addOnly) {
                for (String groupName : foundUser.getGroups()) {
                    if (!user.getGroups().contains(groupName)) {
                        this.customDBProvider.deleteGroup(con, userIDnum, groupName);
                        this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete,
                                approvalID, workflow, "group", groupName);
                    }
                }
            }
        }

        con.commit();

    } catch (Throwable t) {
        if (con != null) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                //do nothing
            }
        }

        throw new ProvisioningException("Could noy sync user", t);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                //do nothing
            }
        }
    }

}

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

public void run() {

    if (doDelete) {
        Connection conn = null;

        try {//from   ww w .j  ava 2  s.c om
            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;

                conn.setAutoCommit(false);
                {
                    SoftReference sf = new SoftReference(conn.createStatement());
                    stmt = (Statement) sf.get();
                }

                //                      stmt2 = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                long execTime = 0;
                int pkStart = 0;
                int pkEnds = 0;
                ThreadInfo thInfo;

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

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

                StressTool.setInfoDelete(this.ID, thInfo);

                int deletedRows = 0;

                int[] pkStartAr = null;
                int[] pkEndsAr = null;
                String[][] sqlParameterValues;
                int[] iLine = { 0, 0 };

                //                      for(int repeat = 0 ; repeat < repeatNumber ; repeat++ ){
                //                      pkEndsAr[repeat] = StressTool.getNumberFromRandom(2147483647).intValue();
                //                      pkStartAr[repeat] = StressTool.getNumberFromRandom(pkEndsAr[repeat]- 10).intValue();
                //
                //                 }

                for (int repeat = 0; repeat < repeatNumber; repeat++) {
                    int maxDel = 0;
                    totalLineDeleted = 0;
                    //                         pkStart = pkStartAr[repeat];
                    //                          pkEnds = pkEndsAr[repeat];

                    //                              System.gc();

                    String deleteCheck1 = "";
                    long timeStart = System.currentTimeMillis();

                    try {
                        stmt.execute("BEGIN");

                        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                            ResultSet rsToDelete = stmt
                                    .executeQuery("Select max(a),min(a) from tbtest" + iTable);
                            rsToDelete.next();
                            DecimalFormat df = new DecimalFormat("#.000000");
                            long maxDelete = rsToDelete.getLong(1);
                            long minDelete = rsToDelete.getLong(2);
                            long maxToDelete = new Double(
                                    ((double) this.getDeleterowmaxpct() * maxDelete) / 100).longValue();

                            PreparedStatement pstmt = null;
                            {
                                SoftReference sf = new SoftReference(conn.prepareStatement(
                                        "DELETE FROM tbtest" + iTable + " where a between  ? and ?"));
                                pstmt = (PreparedStatement) sf.get();
                            }

                            int deleted = 0;
                            if (maxDelete > 0) {

                                for (long iCdelete = minDelete; iCdelete < maxToDelete; iCdelete += getDeleterowsinterval()) {
                                    pstmt.setLong(1, iCdelete);
                                    pstmt.setLong(2, iCdelete += getDeleterowsinterval());
                                    int rows = pstmt.executeUpdate();
                                    if (rows > 0)
                                        deleted += rows;

                                    if (deleted >= maxToDelete) {
                                        totalLineDeleted += deleted;
                                        break;
                                    }
                                    stmt.execute("COMMIT");
                                }

                            }
                            stmt.execute("COMMIT");

                        }

                        if (!doSimplePk) {
                            for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                                ResultSet rsToDelete = stmt
                                        .executeQuery("Select max(a),min(a) from tbtest_child" + iTable);
                                rsToDelete.next();
                                DecimalFormat df = new DecimalFormat("#.000000");
                                long maxDelete = rsToDelete.getLong(1);
                                long minDelete = rsToDelete.getLong(2);
                                long maxToDelete = new Double(
                                        ((double) this.getDeleterowmaxpct() * maxDelete) / 100).longValue();

                                PreparedStatement pstmt = conn.prepareStatement(
                                        "DELETE FROM tbtest_child" + iTable + " where a between  ? and ?");
                                int deleted = 0;
                                if (maxDelete > 0) {

                                    for (long iCdelete = minDelete; iCdelete < maxToDelete; iCdelete += getDeleterowsinterval()) {
                                        pstmt.setLong(1, iCdelete);
                                        pstmt.setLong(2, iCdelete += getDeleterowsinterval());
                                        int rows = pstmt.executeUpdate();
                                        if (rows > 0)
                                            deleted += rows;

                                        if (deleted >= maxToDelete) {
                                            totalLineDeleted += deleted;
                                            break;
                                        }
                                        stmt.execute("COMMIT");
                                    }

                                }
                                stmt.execute("COMMIT");
                            }
                        }

                        long timeEnds = System.currentTimeMillis();
                        execTime = (timeEnds - timeStart);

                    } catch (SQLException sqle) {
                        conn.rollback();
                        //                                  System.out.println("Query Delete1 = " + deleteCheck1);
                        /** 
                         Silently skip any deadlock
                        **/
                        if (StressTool.getErrorLogHandler() != null) {
                            StressTool.getErrorLogHandler().appendToFile(sqle.toString());
                        }

                        //                                  sqle.printStackTrace();
                    } finally {

                    }

                    if (doLog) {
                        System.out.println("Query Delete TH = " + this.getID() + " Id = " + pkStart
                                + " IdEnd = " + pkEnds + " " + "Deleted lines " + (totalLineDeleted)
                                + " Exec Time(ms) =" + execTime);
                    }

                    thInfo.setExecutedLoops(repeat);
                    Thread.sleep(sleepFor);
                }

                stmt.close();
                //                      stmt2.close();
                conn.close();

                long threadTimeEnd = System.currentTimeMillis();
                this.executionTime = (threadTimeEnd - threadTimeStart);
                this.setExecutionTime(executionTime);
                active = false;
                //                      System.out.println("Query Delete TH = " + this.getID() +" Id = " + pkStart + 
                //                            " IdEnd = " + pkEnds + " " + "Deleted lines " +
                //                              deletedRows + " Exec Time(ms) =" + execTime + " Sec =" + (execTime/1000));

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

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

    }
}

From source file:dao.DirectoryDaoDb.java

/**
 *  This method updates blob (caption, zoom) for the directory
 *  @param entryId - the entry id of this blob
 *  @param directoryId - the directory id of this blob
 *  @param userId - the user id /*w w w .j  a  v  a2  s  .  c o m*/
 *  @param userLogin - the user login
 *  @param zoom - the zoom
 *  @param btitle - the btitle
 *  @param def - is this the default
 *  @param caption - caption
 *  @throws BaseDaoException - when error occurs
 */
public void updateStreamBlob(String entryId, String directoryId, String userId, String userLogin, String zoom,
        String btitle, boolean def, String caption, String dirPath, String dirName) {

    /**
    * check only dirname and owner. others can be null.
    */
    if (RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(directoryId)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  isDiaryAdmin or isAuthor
     */
    if ((!diaryAdmin.isDiaryAdmin(userLogin)) && (!isAuthor(directoryId, userId))) {
        throw new BaseDaoException("User is neither a diaryAdmin nor author to update directory = "
                + directoryId + " userId =" + userId);
    }

    /**
     *  Get scalability datasource for dirblob - partitioned on directoryId
     */
    String sourceName = scalabilityManager.getWriteBlobScalability(directoryId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, updateStreamBlob() " + sourceName);
    }

    /**
     * Check if this entry exists in the default directory blob
     */
    boolean exists = false;
    String defId = null;
    try {
        Object[] params = { (Object) directoryId };
        List result = defaultQuery.execute(params);
        if (result != null && result.size() > 0) {
            defId = ((Photo) result.get(0)).getValue(DbConstants.ENTRYID);
            if (!RegexStrUtil.isNull(defId) && defId.equals(entryId)) {
                exists = true;
            }
        }
    } catch (Exception e) {
        throw new BaseDaoException("error while" + defaultQuery.getSql(), e);
    }

    if (WebUtil.isSanEnabled()) {
        Photo photo = getPhoto(entryId, directoryId);
        String srcFileName = null;
        if (photo != null) {
            srcFileName = photo.getValue(DbConstants.BTITLE);
        }
        if ((!RegexStrUtil.isNull(srcFileName)) && !srcFileName.equals(btitle)) {
            try {
                getSanUtils();
                sanUtils.renameSanFile(dirPath, dirName, srcFileName, SanConstants.sanPath, btitle);
            } catch (SanException e) {
                throw new BaseDaoException("directory updateStreamBlob()renameSanFile error", e);
            }
        }
    }

    List result = null;
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        blobUpdateQuery.run(conn, entryId, directoryId, zoom, btitle, caption);
        if (def) {
            /**
             * so delete the default entry that does not match with this entryid, add  the new entryid
             */
            if (!exists) {
                deleteDefaultQuery.run(conn, directoryId);
                addDefaultQuery.run(conn, entryId, directoryId);
            }
        } else {
            /** 
             *  A default record matching entryid exists, 
             *  Delete this entry as the user does not want this to be a default entry
             */
            if (exists) {
                deleteDefaultQuery.run(conn, directoryId);
            }
        }
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "conn.close() exception for rollback(), for updateStreamBlob() directoryId ="
                                + directoryId + " entryId = " + entryId,
                        e2);
            }
            throw new BaseDaoException("rollback() exception, for updateStreamBlob() directoryId ="
                    + directoryId + " entryId = " + entryId, e1);
        }
    }

    /** 
    * connection commit
    *
    */
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException(
                "commit() exception updateStreamBlob, directoryId= " + directoryId + " entryId = " + entryId,
                e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("conn.close() exception for commit(), updateStreamBlob()  directoryId = "
                + directoryId + " entryId = " + entryId, e4);
    }

    updateDirImage(entryId, directoryId, zoom, btitle, caption);

    /**
          * generate a key for the directory stream blob (directoryid + entryid)
     * remove blobstream of directory, from cache
     * use the same key for both the caches (DIR_PHOTO, DIR_STREAM_BLOB with blobdata)
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.DIR_STREAM_BLOB);
    StringBuffer sb = new StringBuffer(directoryId);
    sb.append("-");
    sb.append(entryId);
    String key = sb.toString();
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_PHOTO);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    /** remove the existing default photo from cache */
    fqn = cacheUtil.fqn(DbConstants.DIR_PHOTO);
    sb.delete(0, sb.length());
    sb.append(directoryId);
    sb.append("-");
    sb.append(defId);
    key = sb.toString();
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_CAT);
    sb.delete(0, sb.length());
    sb.append(directoryId);
    sb.append("-");
    sb.append(DbConstants.PHOTO_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

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

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

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static void insertStandByIps(int id, String[] ips) {
    Connection c = null;
    PreparedStatement ps = null;//w  ww . j a  v a  2  s . c om

    try {
        c = DBHelper.getConnection();
        c.setAutoCommit(false);
        DBHelper.executeUpdateNoCommit(c, "delete from standby_to_id where id=" + id);
        ps = c.prepareStatement(DBHelperConstants.INSERT_INTO_STANDBY_IP);

        for (int i = 0; i < ips.length; i++) {
            ps.setString(1, ips[i]);
            ps.setInt(2, id);
            ps.executeUpdate();
        }
        c.commit();
    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            c.rollback();
        } catch (Exception e) {
        }
    } finally {
        try {
            c.setAutoCommit(true);
        } catch (Exception ex) {
        }

        try {
            ps.close();
        } catch (Exception ex) {
        }

        try {
            DBHelper.releaseConnection(c);
        } catch (Exception e) {
        }
    }
}

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

@RetrySemantics.ReadOnly
public ShowLocksResponse showLocks(ShowLocksRequest rqst) throws MetaException {
    try {//from www.  j  av  a 2  s .c  o m
        Connection dbConn = null;
        ShowLocksResponse rsp = new ShowLocksResponse();
        List<ShowLocksResponseElement> elems = new ArrayList<ShowLocksResponseElement>();
        List<LockInfoExt> sortedList = new ArrayList<LockInfoExt>();
        Statement stmt = null;
        try {
            dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
            stmt = dbConn.createStatement();

            String s = "select hl_lock_ext_id, hl_txnid, hl_db, hl_table, hl_partition, hl_lock_state, "
                    + "hl_lock_type, hl_last_heartbeat, hl_acquired_at, hl_user, hl_host, hl_lock_int_id,"
                    + "hl_blockedby_ext_id, hl_blockedby_int_id, hl_agent_info from HIVE_LOCKS";

            // Some filters may have been specified in the SHOW LOCKS statement. Add them to the query.
            String dbName = rqst.getDbname();
            String tableName = rqst.getTablename();
            String partName = rqst.getPartname();

            StringBuilder filter = new StringBuilder();
            if (dbName != null && !dbName.isEmpty()) {
                filter.append("hl_db=").append(quoteString(dbName));
            }
            if (tableName != null && !tableName.isEmpty()) {
                if (filter.length() > 0) {
                    filter.append(" and ");
                }
                filter.append("hl_table=").append(quoteString(tableName));
            }
            if (partName != null && !partName.isEmpty()) {
                if (filter.length() > 0) {
                    filter.append(" and ");
                }
                filter.append("hl_partition=").append(quoteString(partName));
            }
            String whereClause = filter.toString();

            if (!whereClause.isEmpty()) {
                s = s + " where " + whereClause;
            }

            LOG.debug("Doing to execute query <" + s + ">");
            ResultSet rs = stmt.executeQuery(s);
            while (rs.next()) {
                ShowLocksResponseElement e = new ShowLocksResponseElement();
                e.setLockid(rs.getLong(1));
                long txnid = rs.getLong(2);
                if (!rs.wasNull())
                    e.setTxnid(txnid);
                e.setDbname(rs.getString(3));
                e.setTablename(rs.getString(4));
                String partition = rs.getString(5);
                if (partition != null)
                    e.setPartname(partition);
                switch (rs.getString(6).charAt(0)) {
                case LOCK_ACQUIRED:
                    e.setState(LockState.ACQUIRED);
                    break;
                case LOCK_WAITING:
                    e.setState(LockState.WAITING);
                    break;
                default:
                    throw new MetaException("Unknown lock state " + rs.getString(6).charAt(0));
                }
                switch (rs.getString(7).charAt(0)) {
                case LOCK_SEMI_SHARED:
                    e.setType(LockType.SHARED_WRITE);
                    break;
                case LOCK_EXCLUSIVE:
                    e.setType(LockType.EXCLUSIVE);
                    break;
                case LOCK_SHARED:
                    e.setType(LockType.SHARED_READ);
                    break;
                default:
                    throw new MetaException("Unknown lock type " + rs.getString(6).charAt(0));
                }
                e.setLastheartbeat(rs.getLong(8));
                long acquiredAt = rs.getLong(9);
                if (!rs.wasNull())
                    e.setAcquiredat(acquiredAt);
                e.setUser(rs.getString(10));
                e.setHostname(rs.getString(11));
                e.setLockIdInternal(rs.getLong(12));
                long id = rs.getLong(13);
                if (!rs.wasNull()) {
                    e.setBlockedByExtId(id);
                }
                id = rs.getLong(14);
                if (!rs.wasNull()) {
                    e.setBlockedByIntId(id);
                }
                e.setAgentInfo(rs.getString(15));
                sortedList.add(new LockInfoExt(e));
            }
            LOG.debug("Going to rollback");
            dbConn.rollback();
        } catch (SQLException e) {
            checkRetryable(dbConn, e, "showLocks(" + rqst + ")");
            throw new MetaException(
                    "Unable to select from transaction database " + StringUtils.stringifyException(e));
        } finally {
            closeStmt(stmt);
            closeDbConn(dbConn);
        }
        //this ensures that "SHOW LOCKS" prints the locks in the same order as they are examined
        //by checkLock() - makes diagnostics easier.
        Collections.sort(sortedList, new LockInfoComparator());
        for (LockInfoExt lockInfoExt : sortedList) {
            elems.add(lockInfoExt.e);
        }
        rsp.setLocks(elems);
        return rsp;
    } catch (RetryException e) {
        return showLocks(rqst);
    }
}

From source file:dao.DirectoryDaoDb.java

/**
 * addRootNode - adds the root node.//w ww.j  a va2s  .  c om
 * @param dirname - directory name
 * @param keywords - keywords for this directory
 * @param desc - description of the directory
 * @param dirlink - the directory link
 * @param dirpath - the directory path
 * @param stateid - the state id
 * @param userId - the user id
 * @param scopeid - the scopeid 
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
*/
public void addRootNode(String dirname, String keywords, String desc, String dirlink, String dirpath,
        String stateid, String userId, String scopeid) {
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        directoryAddQuery.run(conn, dirname, keywords, desc, dirlink, dirpath, stateid, userId);

        /**
              *  default dirscope table
              *     Operations is 2 (allasauthors)
              *     Status is 2 (ready)
         *     Scope is 1 (web)
         *
              *  Creator becomes admin in "diradmin" table
              *  Date defaults to creation date
         *  Root does not have a parent, so don't add this to dirtree.
              */
        //String parentId = "0";
        //addChildQuery.run(conn, LAST_INSERT_ID(), parentId); 
        scopeAddQuery.run(conn, "LAST_INSERT_ID()", dirScope.getAllasauthorsoperation(),
                dirScope.getReadystatus(), scopeid);
        /**
         * this needs to be the last as the order is important, 
         * sql behaviour changes for LAST_INSERT_ID. it will take entryId
              * for this table as the last_insert_id for the tables below it.
         */
        addAdminQuery.run(conn, "LAST_INSERT_ID()", userId);
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "conn.close() exception for rollback(), for add directory/scope tables params (6) "
                                + " dirname = " + dirname + " keywords = " + keywords + " scopeid = " + scopeid
                                + " desc = " + desc + " userId = " + userId,
                        e2);
            }
            throw new BaseDaoException("rollback() exception,  for add directory/scope tables params (6) "
                    + " dirname = " + dirname + " keywords = " + keywords + " scopeid = " + scopeid + " desc = "
                    + desc + " userId = " + userId, e1);
        }
        throw new BaseDaoException(
                "for add directory/scope tables params (6) " + " dirname = " + dirname + " keywords = "
                        + keywords + " scopeid = " + scopeid + " desc = " + desc + " userId = " + userId,
                e);
    }

    /** 
    * connection commit
    */
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit() exception, for add directory/permatcat tables params (6) "
                + " dirname = " + dirname + " keywords = " + keywords + " scopeid = " + scopeid + " desc = "
                + desc + " userId = " + userId, e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("conn.close() exception for commit(), add directory/scope tables "
                + " dirname = " + dirname + " keywords = " + keywords + " scopeid = " + scopeid + " desc = "
                + desc + " userId = " + userId, e4);
    }
}

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

/**
 * Used by both the public saveRecord and globalEdit methods
 *//*from ww w .  jav  a2  s  . c  o  m*/
private void saveRecord(HttpServletRequest request, TableInfo table,
        LinkedHashMap<BaseField, BaseValue> dataToSave, boolean newRecord, Set<Integer> rowIds,
        SessionDataInfo sessionData, List<FileItem> multipartItems)
        throws InputRecordException, ObjectNotFoundException, SQLException, CantDoThatException,
        CodingErrorException, DisallowedException, MissingParametersException {
    if ((dataToSave.size() == 0) && (!newRecord)) {
        // Note: this does actually happen quite a lot, from two particular
        // users, therefore I've commented out the log warning.
        // Haven't tracked down the cause but it doesn't seem to be creating
        // a problem.
        // logger.warn("Call to saveRecord with no data to save. User = "
        // + request.getRemoteUser() + ", table = " + table + ", rowIds = "
        // + rowIds);
        return;
    }
    this.setHiddenFieldValues(request, table, dataToSave, newRecord);
    boolean globalEdit = false;
    int rowId = -1;
    if (rowIds.size() > 1) {
        globalEdit = true;
    } else if (rowIds.size() == 1) {
        rowId = (new LinkedList<Integer>(rowIds)).getFirst();
    } else {
        throw new ObjectNotFoundException("Row ID list " + rowIds + " is invalid");
    }
    StringBuilder SQLCodeBuilder = new StringBuilder();
    // Generate CSV of fields and placeholders to use in update/insert SQL
    // string
    StringBuilder fieldsCsvBuilder = new StringBuilder();
    StringBuilder fieldsAndPlaceholdersCsvBuilder = new StringBuilder();
    StringBuilder valuePlaceholdersCsvBuilder = new StringBuilder();
    for (BaseField field : dataToSave.keySet()) {
        fieldsCsvBuilder.append(field.getInternalFieldName());
        fieldsCsvBuilder.append(", ");
        valuePlaceholdersCsvBuilder.append("?, ");
        fieldsAndPlaceholdersCsvBuilder.append(field.getInternalFieldName());
        fieldsAndPlaceholdersCsvBuilder.append("=?, ");
    }
    // Used if doing an INSERT
    String fieldsCsv = fieldsCsvBuilder.toString();
    String valuePlaceholdersCsv = valuePlaceholdersCsvBuilder.toString();
    // Used if doing an UPDATE
    String fieldsAndPlaceholdersCsv = fieldsAndPlaceholdersCsvBuilder.toString();
    if (!fieldsCsv.equals("")) {
        fieldsCsv = fieldsCsv.substring(0, fieldsCsv.length() - 2);
        valuePlaceholdersCsv = valuePlaceholdersCsv.substring(0, valuePlaceholdersCsv.length() - 2);
        fieldsAndPlaceholdersCsv = fieldsAndPlaceholdersCsv.substring(0, fieldsAndPlaceholdersCsv.length() - 2);
    }
    if (newRecord) {
        SQLCodeBuilder.append("INSERT INTO " + table.getInternalTableName());
        if (fieldsCsv.equals("")) {
            SQLCodeBuilder.append(" VALUES(default)");
        } else {
            SQLCodeBuilder.append("(" + fieldsCsv + ") VALUES (" + valuePlaceholdersCsv + ")");
        }
    } else {
        SQLCodeBuilder.append("UPDATE " + table.getInternalTableName() + " SET " + fieldsAndPlaceholdersCsv);
        if (globalEdit) {
            // add filter for various row ids
            SQLCodeBuilder.append(" WHERE " + table.getPrimaryKey().getInternalFieldName() + " in (?");
            for (int i = 1; i < rowIds.size(); i++) {
                SQLCodeBuilder.append(",?");
            }
            SQLCodeBuilder.append(")");
        } else {
            // add filter for single row id
            SQLCodeBuilder.append(" WHERE " + table.getPrimaryKey().getInternalFieldName() + "=?");
        }
    }
    Connection conn = null;
    int fieldNumber = 0;
    // Will be set if we're inserting a record
    int newRowId = -1;
    TableDataInfo tableData = new TableData(table);
    try {
        conn = this.dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement statement = conn.prepareStatement(SQLCodeBuilder.toString());
        for (BaseField field : dataToSave.keySet()) {
            // If an exception is raised, currentField will be the field
            // which caused it
            // currentField = field;
            fieldNumber++;
            BaseValue fieldValue = dataToSave.get(field);
            if (field instanceof FileField) {
                if (fieldValue.isNull() || fieldValue.toString().equals("")) {
                    throw new InputRecordException("No file specified for the upload", field);
                }
            }
            if (fieldValue.isNull()) {
                statement.setNull(fieldNumber, Types.NULL);
            } else {
                if (fieldValue instanceof TextValue) {
                    String textValue = ((TextValue) fieldValue).toXmlString();
                    statement.setString(fieldNumber, textValue);
                } else if (fieldValue instanceof IntegerValue) {
                    // if no related value, set relation field to null
                    if (field instanceof RelationField && (((IntegerValue) fieldValue).getValueInteger() == -1)
                            || (fieldValue.isNull())) {
                        statement.setNull(fieldNumber, Types.NULL);
                    } else {
                        statement.setInt(fieldNumber, ((IntegerValue) fieldValue).getValueInteger());
                    }
                } else if (fieldValue instanceof DurationValue) {
                    statement.setString(fieldNumber, ((DurationValue) fieldValue).getSqlFormatInterval());
                } else if (fieldValue instanceof DecimalValue) {
                    statement.setDouble(fieldNumber, ((DecimalValue) fieldValue).getValueFloat());
                } else if (fieldValue instanceof DateValue) {
                    if (((DateValue) fieldValue).getValueDate() != null) {
                        java.util.Date javaDateValue = ((DateValue) fieldValue).getValueDate().getTime();
                        java.sql.Timestamp sqlTimestampValue = new java.sql.Timestamp(javaDateValue.getTime());
                        statement.setTimestamp(fieldNumber, sqlTimestampValue);
                    } else {
                        statement.setTimestamp(fieldNumber, null);
                    }
                } else if (fieldValue instanceof CheckboxValue) {
                    statement.setBoolean(fieldNumber, ((CheckboxValue) fieldValue).getValueBoolean());
                } else if (fieldValue instanceof FileValue) {
                    statement.setString(fieldNumber, ((FileValue) fieldValue).toString());
                } else {
                    throw new CodingErrorException("Field value " + fieldValue + " is of unknown type "
                            + fieldValue.getClass().getSimpleName());
                }
            }
        }
        // We've finished setting individual fields, if an SQL error occurs
        // after here we won't know which
        // field caused it without looking for it by other means
        // currentField = null;
        if (!newRecord) {
            if (globalEdit) {
                // Fill in the 'WHERE [row id field] in (?,..,?)' for use in
                // the UPDATE statement
                for (Integer aRowId : rowIds) {
                    if (tableData.isRecordLocked(conn, sessionData, aRowId)) {
                        throw new CantDoThatException(
                                "Record " + aRowId + " from table " + table + " is locked to prevent editing");
                    }
                    statement.setInt(++fieldNumber, aRowId);
                }
            } else {
                // Fill in the 'WHERE [row id field]=?' for use in the
                // UPDATE statement
                if (tableData.isRecordLocked(conn, sessionData, rowId)) {
                    throw new CantDoThatException(
                            "Record " + rowId + " from table " + table + " is locked to prevent editing");
                }
                statement.setInt(fieldNumber + 1, rowId);
            }
        }
        int numRowsAffected = statement.executeUpdate();
        statement.close();
        if ((numRowsAffected != 1) && (!globalEdit)) {
            conn.rollback();
            if (numRowsAffected > 0) {
                throw new ObjectNotFoundException(String.valueOf(numRowsAffected)
                        + " records would be altered during a single record save");
            } else {
                throw new ObjectNotFoundException(
                        "The current record can't be found to edit - perhaps someone else has deleted it");
            }
        }
        if (newRecord) {
            // Find the newly inserted Row ID
            // postgres-specific code, not database independent
            String SQLCode = "SELECT currval('" + table.getInternalTableName() + "_"
                    + table.getPrimaryKey().getInternalFieldName() + "_seq')";
            statement = conn.prepareStatement(SQLCode);
            ResultSet results = statement.executeQuery();
            if (results.next()) {
                newRowId = results.getInt(1);
            } else {
                results.close();
                statement.close();
                throw new SQLException(
                        "Row ID not found for the newly inserted record. '" + SQLCodeBuilder + "' didn't work");
            }
            results.close();
            statement.close();
        }
        conn.commit();
    } catch (SQLException sqlex) {
        // Find out which field caused the error by looking for internal
        // field names in the error message
        String errorMessage = sqlex.getMessage();
        for (BaseField possibleCauseField : dataToSave.keySet()) {
            if (errorMessage.contains(possibleCauseField.getInternalFieldName())) {
                if (errorMessage.contains("check constraint")) {
                    errorMessage = "The value " + dataToSave.get(possibleCauseField)
                            + " falls outside the allowed range";
                } else if (errorMessage.contains("not-null constraint")) {
                    errorMessage = "No value entered";
                } else if (errorMessage.contains("unique constraint")) {
                    errorMessage = "Value " + dataToSave.get(possibleCauseField)
                            + " is already in the database and cannot be entered again";
                } else if (errorMessage.contains("foreign key constraint")
                        && possibleCauseField instanceof RelationField) {
                    errorMessage = "Please select a valid "
                            + ((RelationField) possibleCauseField).getRelatedTable() + " record first";
                } else {
                    errorMessage = "Value " + dataToSave.get(possibleCauseField) + " not allowed ("
                            + Helpers.replaceInternalNames(errorMessage, table.getDefaultReport()) + ")";
                }
                throw new InputRecordException(errorMessage, possibleCauseField, sqlex);
            }
        }
        // Not able to find field
        errorMessage = Helpers.replaceInternalNames(errorMessage, table.getDefaultReport());
        throw new InputRecordException(errorMessage, null, sqlex);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    // If any fields were files to upload, do the actual uploads.
    // Do this after the commit in case the uploads take a long time and
    // time out the SQL connection.
    for (BaseField field : dataToSave.keySet()) {
        if (field instanceof FileField) {
            try {
                if (newRecord) {
                    this.uploadFile(request, (FileField) field, (FileValue) dataToSave.get(field), newRowId,
                            multipartItems);
                } else {
                    this.uploadFile(request, (FileField) field, (FileValue) dataToSave.get(field), rowId,
                            multipartItems);
                }
            } catch (CantDoThatException cdtex) {
                throw new InputRecordException("Error uploading file: " + cdtex.getMessage(), field, cdtex);
            } catch (FileUploadException fuex) {
                throw new InputRecordException("Error uploading file: " + fuex.getMessage(), field, fuex);
            }
        }
    }
    if (newRecord) {
        sessionData.setRowId(table, newRowId);
    }
    this.logLastDataChangeTime(request);
    logLastTableDataChangeTime(table);
    UsageLogger usageLogger = new UsageLogger(this.dataSource);
    AppUserInfo user = null;
    if (request.getRemoteUser() == null) {
        user = ServletUtilMethods.getPublicUserForRequest(request, this.authManager.getAuthenticator());
    } else {
        user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    }
    // Send websocket notification
    // UsageLogger.sendNotification(user, table, sessionData.getReport(),
    // rowId, "edit", "Record saved: " + dataToSave);
    // Log everything apart from hidden (auto set) fields
    Map<BaseField, BaseValue> dataToLog = new LinkedHashMap<BaseField, BaseValue>();
    for (Map.Entry<BaseField, BaseValue> entrySet : dataToSave.entrySet()) {
        BaseField field = entrySet.getKey();
        if (!field.getHidden()) {
            BaseValue value = entrySet.getValue();
            dataToLog.put(field, value);
        }
    }
    if (newRecord) {
        usageLogger.logDataChange(user, table, null, AppAction.SAVE_NEW_RECORD, newRowId, dataToLog.toString());
    } else if (globalEdit) {
        // TODO: need better logging of global edits
        usageLogger.logDataChange(user, table, null, AppAction.GLOBAL_EDIT, rowId, dataToLog.toString());
    } else {
        BaseField fieldUpdated = null;
        Set<BaseField> fieldSet = new TreeSet<BaseField>();
        for (BaseField field : dataToSave.keySet()) {
            if (!field.getHidden()) {
                fieldSet.add(field);
            }
        }
        if (fieldSet.size() == 1) {
            fieldUpdated = new LinkedList<BaseField>(fieldSet).getFirst();
        }
        usageLogger.logDataChange(user, table, fieldUpdated, AppAction.UPDATE_RECORD, rowId,
                dataToLog.toString());
    }
    UsageLogger.startLoggingThread(usageLogger);
}