Example usage for java.sql Connection setAutoCommit

List of usage examples for java.sql Connection setAutoCommit

Introduction

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

Prototype

void setAutoCommit(boolean autoCommit) throws SQLException;

Source Link

Document

Sets this connection's auto-commit mode to the given state.

Usage

From source file:com.bloidonia.vertx.mods.JdbcProcessor.java

/****************************************************************************
 **//from   ww w.j  a  v a 2 s  .  co m
 **  Transaction handling
 **
 ****************************************************************************/

private void doTransaction(Message<JsonObject> message) {
    Connection connection = null;
    try {
        connection = poolMap.get(address).getConnection();
        connection.setAutoCommit(false);
        doTransaction(message, connection);
    } catch (SQLException ex) {
        sendError(message, "Caught exception in TRANSACTION.  Rolling back...", ex);
        try {
            connection.rollback();
        } catch (SQLException exx) {
            logger.error("Failed to rollback", exx);
        }
        SilentCloser.close(connection);
    }
}

From source file:de.whs.poodle.repositories.ExerciseRepository.java

public void save(Exercise exercise) {
    if (exercise.getTitle().trim().isEmpty())
        throw new BadRequestException("noTitleSpecified");
    if (exercise.getText().trim().isEmpty())
        throw new BadRequestException("noExerciseTextSpecified");

    jdbc.execute(new ConnectionCallback<Void>() {

        @Override/* w  ww .ja v  a 2s.c  o  m*/
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            try (CallableStatement exercisePs = con
                    .prepareCall("{ ? = CALL create_exercise(?,?,?::exercise_visibility,?,?,?,?,?,?,?,?,?) }");

                    PreparedStatement tagsPs = con
                            .prepareStatement("INSERT INTO exercise_to_tag(exercise_id,tag_id) VALUES(?,?)");) {
                con.setAutoCommit(false);

                // inner try for rollback
                try {
                    // create exercise
                    exercisePs.registerOutParameter(1, Types.INTEGER); // new_id

                    exercisePs.setString(2, exercise.getText());

                    /*
                     * The root id is always the ID of the first revision. If this
                     * is a new exercise, this ID obviously doesn't exist yet. We set
                     * NULL in this case, but a trigger in the DB will automatically
                     * set the root_id to the generated id.
                     */
                    if (exercise.getRootId() == 0)
                        exercisePs.setNull(3, Types.INTEGER);
                    else
                        exercisePs.setInt(3, exercise.getRootId());

                    exercisePs.setString(4, exercise.getVisibility().toString());
                    exercisePs.setString(5, exercise.getTitle());
                    exercisePs.setInt(6, exercise.getChangedBy().getId());
                    exercisePs.setString(7, exercise.getHint1());
                    exercisePs.setString(8, exercise.getHint2());

                    // sample solution
                    SampleSolutionType sampleSolutionType = exercise.getSampleSolutionType();

                    if (sampleSolutionType == SampleSolutionType.NONE) {
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else if (sampleSolutionType == SampleSolutionType.FILE) {
                        exercisePs.setInt(9, exercise.getSampleSolution().getFile().getId());
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else { // must be text
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setString(10, exercise.getSampleSolution().getText());
                    }

                    // attachments
                    List<Integer> attachmentIds = exercise.getAttachments().stream().map(a -> a.getId())
                            .collect(Collectors.toList());

                    Array anhaengeIdsArray = con.createArrayOf("int4", attachmentIds.toArray());
                    exercisePs.setArray(11, anhaengeIdsArray);

                    exercisePs.setInt(12, exercise.getCourseId());

                    exercisePs.setString(13, exercise.getComment());

                    exercisePs.executeUpdate();

                    /* Set the generated ID so the calling function can read it. */
                    exercise.setId(exercisePs.getInt(1));

                    // create relation to tags
                    tagsPs.setInt(1, exercise.getId());

                    for (Tag t : exercise.getTags()) {
                        tagsPs.setInt(2, t.getId());
                        tagsPs.addBatch();
                    }

                    tagsPs.executeBatch();

                    con.commit();
                } catch (SQLException e) {
                    con.rollback();
                    throw e;
                } finally {
                    con.setAutoCommit(true);
                }
            }

            return null;
        }
    });
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;
    Integer serial = 0;/*w  ww.jav a2s . c  o m*/
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

From source file:dao.PendingfriendDaoDb.java

/**
 * adds the guestLogin as a friend//from   w ww .  ja  v  a2s .co m
 * @param guestLogin  - the guestId
 * @param loginId  - the loginid
 * @param login  - the login
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void addFriend(String guestLogin, String loginId, String login) throws BaseDaoException {

    if (RegexStrUtil.isNull(guestLogin) || RegexStrUtil.isNull(loginId)) {
        throw new BaseDaoException("params are null");
    }

    Hdlogin hdlogin = getLoginid(guestLogin);
    if (hdlogin == null) {
        throw new BaseDaoException("hdlogin is null for guestLogin " + guestLogin);
    }
    String guestId = hdlogin.getValue(DbConstants.LOGIN_ID);
    if (RegexStrUtil.isNull(guestId)) {
        throw new BaseDaoException("guestId is null for guestLogin " + guestId);
    }

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

    /**
    *  add friend
    */
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        if (conn != null) {
            friendAddQuery.run(conn, guestId, loginId);
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.rollback();
            }
        } catch (Exception e1) { // (Exception e1)
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) { // (Exception e2)
                throw new BaseDaoException("conn.setAutoCommit() error in friendAddQuery() guestId = " + guestId
                        + ", loginId = " + loginId, e2);
            }
            throw new BaseDaoException(
                    "conn.rollback error in friendAddQuery() guestId = " + guestId + ", loginId = " + loginId,
                    e1);
        }
        throw new BaseDaoException(
                "error occured while executing friendAddQuery() guestId =" + guestId + ", loginId = " + loginId,
                e);
    } // (Exception e)

    /**
     * commit the transaction
     */
    try {
        if (conn != null) {
            conn.commit();
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e) {
        throw new BaseDaoException("con.commit()/conn.setAutoCommit()/conn.close() exception", e);
    }

    /**
     * delete the cache based on the loginId 
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.OUT_PENDING);
    if (treeCache.exists(fqn, guestId)) {
        treeCache.remove(fqn, guestId);
    }

    fqn = cacheUtil.fqn(DbConstants.IN_PENDING);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

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

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

From source file:com.appspot.relaxe.tools.CSVInsertTask.java

public void run(Connection connection, Reader input, Table table) throws IOException, SQLException {

    if (connection == null) {
        throw new NullPointerException("'connection' must not be null");
    }//w w w .j  a va  2 s  .c om

    if (input == null) {
        throw new NullPointerException("'input' must not be null");
    }

    if (table == null) {
        throw new NullPointerException("'table' must not be null");
    }

    boolean committed = false;

    try {
        connection.setAutoCommit(false);
        CSVStrategy cs = new CSVStrategy('\t', '"', CSVStrategy.COMMENTS_DISABLED, false, false, false);
        CSVParser p = new CSVParser(input, cs);

        // get header line
        String[] line = p.getLine();

        // configure by using the column headers:        
        ColumnMap cm = table.getColumnMap();
        List<Identifier> names = new ArrayList<Identifier>();
        List<Column> columnList = new ArrayList<Column>();

        for (String n : line) {
            Column column = cm.get(n);

            if (column == null) {
                throw new IllegalArgumentException("column not found " + n);
            }

            columnList.add(column);
            names.add(column.getColumnName());
        }

        if (names.isEmpty()) {
            throw new IllegalStateException("no column names available");
        }

        ElementList<Identifier> nel = ElementList.newElementList(names);

        final int expectedColumnCount = line.length;
        //            int recno = 0;        

        PreparedStatement ps = null;
        InsertStatement ins = null;

        VarcharParameter[] params = new VarcharParameter[expectedColumnCount];
        ValueAssignerFactory vaf = getImplementation().getValueAssignerFactory();

        AssignmentVisitor pa = null;

        while ((line = p.getLine()) != null) {
            //                recno++;
            final int cols = line.length;
            int lineno = p.getLineNumber();

            if (cols != expectedColumnCount) {
                throw new IllegalStateException("unexpected column count: " + cols + " at line " + lineno);
            }

            if (ps == null) {

                List<RowValueConstructorElement> vl = new ArrayList<RowValueConstructorElement>(params.length);

                for (int i = 0; i < params.length; i++) {
                    Column column = columnList.get(i);
                    VarcharHolder h = parse(column, line[i]);

                    VarcharParameter param = new VarcharParameter(column, h);
                    params[i] = param;
                    vl.add(param);
                }

                RowValueConstructor rvc = AbstractRowValueConstructor.of(vl);
                ins = new InsertStatement(table, nel, rvc);

                String q = ins.generate();
                ps = connection.prepareStatement(q);
                pa = new AssignmentVisitor(vaf, ps);

                //                System.err.println("lineno: " + lineno);
                //                System.err.println("record: " + recno);
                //                System.err.println("query: " + q);
            } else {
                pa.reset();

                for (int i = 0; i < line.length; i++) {
                    Column column = columnList.get(i);
                    VarcharHolder h = parse(column, line[i]);
                    VarcharParameter param = params[i];
                    param.setValue(h);
                }
            }

            ins.traverse(null, pa);
            ps.addBatch();
        }

        int[] updateCounts = ps.executeBatch();
        updated(updateCounts);
        connection.commit();
        committed = true;
    } finally {
        if (!(committed)) {
            QueryHelper.doRollback(connection);
        }
    }
}

From source file:edu.umd.cs.submitServer.servlets.ImportProject.java

/**
 * The doPost method of the servlet. <br>
 * //from w w  w  . j a  va2 s.  c  o m
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        // MultipartRequestFilter is required
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
        Course course = (Course) request.getAttribute(COURSE);
        StudentRegistration canonicalStudentRegistration = StudentRegistration.lookupByStudentRegistrationPK(
                multipartRequest.getIntParameter("canonicalStudentRegistrationPK", 0), conn);

        fileItem = multipartRequest.getFileItem();

        conn.setAutoCommit(false);
        /*
         * 20090608: changed TRANSACTION_READ_COMMITTED to
         * TRANSACTION_REPEATABLE_READ to make transaction compatible with
         * innodb in MySQL 5.1, which defines READ_COMMITTED as unsafe for
         * use with standard binary logging. For more information, see:
         * <http
         * ://dev.mysql.com/doc/refman/5.1/en/set-transaction.html#isolevel_read
         * -committed>
         */
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        Project project = Project.importProject(fileItem.getInputStream(), course, canonicalStudentRegistration,
                conn);

        conn.commit();
        transactionSuccess = true;

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (ClassNotFoundException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}

From source file:com.c9.vertx.mods.JdbcProcessor.java

/****************************************************************************
 ** /*from   ww  w  .  j  a  v  a 2 s. c o  m*/
 ** Transaction handling
 ** 
 ****************************************************************************/

private void doTransaction(Message<JsonObject> message) {
    Connection connection = null;
    try {
        connection = getConnection(address);
        connection.setAutoCommit(false);
        doTransaction(message, connection);
    } catch (SQLException ex) {
        sendError(message, "Caught exception in TRANSACTION.  Rolling back...", ex);
        try {
            connection.rollback();
        } catch (SQLException exx) {
            logger.error("Failed to rollback", exx);
        }
        SilentCloser.close(connection);
    }
}

From source file:eionet.cr.dao.virtuoso.VirtuosoFolderDAO.java

@Override
public void createFolder(String parentFolderUri, String folderName, String folderLabel, String homeUri)
        throws DAOException {

    // Make sure we have valid inputs.
    if (StringUtils.isBlank(parentFolderUri) || StringUtils.isBlank(folderName)) {
        throw new IllegalArgumentException("Parent folder URI and folder name must not be blank!");
    }/*  w  ww .  ja  v a 2 s .c o m*/

    // Remove trailing "/" from parent URI, if such exists
    if (parentFolderUri.endsWith("/")) {
        parentFolderUri = StringUtils.substringBeforeLast(parentFolderUri, "/");
    }

    // If the new folder URI is reserved, exit silently.
    String newFolderUri = parentFolderUri + "/" + URLUtil.escapeIRI(folderName);
    if (FolderUtil.isUserReservedUri(newFolderUri)) {
        LOGGER.debug("Cannot create reserved folder, exiting silently!");
        return;
    }

    Connection sqlConn = null;
    RepositoryConnection repoConn = null;
    try {
        sqlConn = SesameUtil.getSQLConnection();
        sqlConn.setAutoCommit(false);

        repoConn = SesameUtil.getRepositoryConnection();
        repoConn.setAutoCommit(false);
        ValueFactory vf = repoConn.getValueFactory();

        URI homeFolder = vf.createURI(homeUri);
        URI parentFolder = vf.createURI(parentFolderUri);
        URI hasFolder = vf.createURI(Predicates.CR_HAS_FOLDER);
        URI newFolder = vf.createURI(newFolderUri);
        URI rdfType = vf.createURI(Predicates.RDF_TYPE);
        URI rdfsLabel = vf.createURI(Predicates.RDFS_LABEL);
        URI allowSubObjectType = vf.createURI(Predicates.CR_ALLOW_SUBOBJECT_TYPE);
        Literal folderLabelLiteral = vf.createLiteral(folderLabel);
        URI folder = vf.createURI(Subjects.CR_FOLDER);
        URI file = vf.createURI(Subjects.CR_FILE);

        ArrayList<Statement> statements = new ArrayList<Statement>();
        statements.add(new ContextStatementImpl(parentFolder, hasFolder, newFolder, homeFolder));
        statements.add(new ContextStatementImpl(newFolder, rdfType, folder, homeFolder));
        if (StringUtils.isNotEmpty(folderLabel)) {
            statements.add(new ContextStatementImpl(newFolder, rdfsLabel, folderLabelLiteral, homeFolder));
        }
        statements.add(new ContextStatementImpl(newFolder, allowSubObjectType, folder, homeFolder));
        statements.add(new ContextStatementImpl(newFolder, allowSubObjectType, file, homeFolder));

        repoConn.add(statements);

        // if a new project is created add subfolders
        if (FolderUtil.isProjectRootFolder(parentFolderUri)) {
            repoConn.add(getProjectFolderCreationStatements(folderName, vf));
        }

        createNeverHarvestedSources(sqlConn, statements);

        repoConn.commit();
        sqlConn.commit();

    } catch (OpenRDFException e) {
        SesameUtil.rollback(repoConn);
        throw new DAOException(e.getMessage(), e);
    } catch (SQLException e) {
        SQLUtil.rollback(sqlConn);
        throw new DAOException(e.getMessage(), e);
    } finally {
        SQLUtil.close(sqlConn);
        SesameUtil.close(repoConn);
    }
}

From source file:com.viettel.logistic.wms.service.StockGoodsSerialServiceImpl.java

@Override
public List<GoodsSerialInforDTO> getGoodsBySerial(OrdersDTO ordersDTO,
        List<GoodsSerialInforDTO> lstGoodsSerialInforDTO) {
    Session session;//www  . j av a  2  s  . com
    Connection connection;
    session = sessionFactory.openSession();
    List<GoodsSerialInforDTO> lstReturn = null;
    try {
        SessionFactory sessionFactoryBatch = session.getSessionFactory();
        connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry()
                .getService(ConnectionProvider.class).getConnection();
        connection.setAutoCommit(false);
        lstReturn = stockGoodsSerialBusiness.getGoodsBySerial(ordersDTO, lstGoodsSerialInforDTO, connection);
        connection.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return lstReturn;
}

From source file:com.viettel.logistic.wms.service.StockGoodsSerialServiceImpl.java

@Override
public List<GoodsSerialInforDTO> getGoodsBySerialInventory(OrdersDTO ordersDTO,
        List<GoodsSerialInforDTO> lstGoodsSerialInforDTO) {
    Session session;//from   w w  w . j a  va2s  . com
    Connection connection;
    session = sessionFactory.openSession();
    List<GoodsSerialInforDTO> lstReturn = null;
    try {
        SessionFactory sessionFactoryBatch = session.getSessionFactory();
        connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry()
                .getService(ConnectionProvider.class).getConnection();
        connection.setAutoCommit(false);
        lstReturn = stockGoodsSerialBusiness.getGoodsBySerialInventory(ordersDTO, lstGoodsSerialInforDTO,
                connection);
        connection.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return lstReturn;
}