Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

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

Prototype

void rollback() throws SQLException;

Source Link

Document

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

Usage

From source file:com.concursive.connect.web.portal.PortletPreferencesServiceImpl.java

public void store(PortletWindow portletWindow, PortletRequest request, InternalPortletPreference[] preferences)
        throws PortletContainerException {
    String key = getFormattedKey(portletWindow);
    if (key.startsWith("T")) {
        LOG.debug("Storing temporary portlet prefs");
        DashboardPortlet portlet = (DashboardPortlet) request.getAttribute("dashboardPortlet");
        LOG.debug("write------------------------------------");
        LOG.debug("portlet page name: " + portlet.getPageName());
        LOG.debug("portlet key: " + portlet.getWindowConfigId());
        LOG.debug("portlet formatted key: " + key);
        LOG.debug("-----------------------------------------");
        // Store them in an array for quick retrieval
        storage.put(key, clonePreferences(preferences));
    } else {/*www. j  a v  a  2  s  .  co  m*/
        // Store them in an array for quick retrieval
        storage.put(key, clonePreferences(preferences));
        // Store the preferences into the database -- container does not specify what changed
        // so delete them all
        int portletId = Integer.parseInt(key);
        Connection db = (Connection) request.getAttribute("connection");
        try {
            db.setAutoCommit(false);
            DashboardPortletPrefsList.delete(db, portletId);
            for (InternalPortletPreference thisPref : preferences) {
                DashboardPortletPrefs portletPrefs = new DashboardPortletPrefs();
                portletPrefs.setPortletId(portletId);
                portletPrefs.setName(thisPref.getName());
                portletPrefs.setValues(thisPref.getValues());
                portletPrefs.insert(db);
            }
            db.commit();
        } catch (Exception e) {
            try {
                db.rollback();
                e.printStackTrace(System.out);
                LOG.error("Preferences", e);
            } catch (Exception e2) {

            }
        } finally {
            try {
                db.setAutoCommit(true);
            } catch (Exception e2) {

            }
        }
    }
}

From source file:dbutils.DbUtilsTemplate.java

/**
 * ?sql?/*from   w  ww  .j a  va 2 s. c  om*/
 *
 * @param sql    sql?
 * @param params ?
 * @return ??
 */
public int[] batchUpdate(String sql, Object[][] params) throws SQLException {
    queryRunner = new QueryRunner();
    int[] affectedRows = new int[0];
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        affectedRows = queryRunner.batch(conn, sql, params);
    } catch (SQLException e) {
        LOG.error("Error occured while attempting to batch update data", e);
        if (conn != null) {
            conn.rollback();
        }
        throw e;
    } finally {
        if (conn != null) {
            DbUtils.commitAndClose(conn);
        }
    }
    return affectedRows;
}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectCopier.java

public static Requirement cloneRequirement(CloneBean bean, Connection db, int groupId, int userId,
        int requirementId) throws SQLException {
    Requirement requirement = null;/*from w ww.ja v  a  2 s  .  c om*/
    try {
        db.setAutoCommit(false);

        // Load permissions and resources for this member
        LOG.debug("ProjectCopier-> RequirementId: " + requirementId);

        Project project = new Project(db, bean.getProjectId());
        TeamMember member = new TeamMember(db, project.getId(), userId);
        User user = UserUtils.loadUser(userId);

        LookupList roleList = new LookupList(db, "lookup_project_role");

        // Load old requirement, change some values, save as new requirement
        requirement = new Requirement(db, requirementId);

        // Outlines, Activities, Activity Folders (no notes yet)
        if (hasPermission(db, project, user, member, "project-plan-view", roleList)) {
            requirement.setEnteredBy(userId);
            requirement.setModifiedBy(userId);
            requirement.setEntered((Timestamp) null);
            requirement.setModified((Timestamp) null);
            requirement.setShortDescription(requirement.getShortDescription() + " (copy)");
            boolean resetStatus = false;
            long offset = 0;
            if (bean.getResetActivityStatus()) {
                resetStatus = true;
            }
            requirement.clone(db, project.getId(), offset, resetStatus);
        }
        db.commit();
    } catch (Exception e) {
        LOG.error("ProjectCopier-> cloneRequirement", e);
        db.rollback();
    } finally {
        db.setAutoCommit(true);
    }
    return requirement;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProjectDeploymentConfigurationSqlAdapter.java

public ProjectDeploymentConfiguration createNewProjectDeploymentConfig(int projectID, String name,
        String description) throws AdaptationException {

    ProjectDeploymentConfiguration config = null;
    Connection connection = null;
    Statement statement = null;/*from   w  ww .  ja  v  a 2  s  . co m*/
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProjectDeploymentConfigurations" + "(projectID, name, description) VALUES ("
                + projectID + ", '" + name + "', '" + description + "')";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM ProjectDeploymentConfigurations WHERE " + " projectID   = " + projectID
                + "  AND " + " name        = '" + name + "' AND " + " description = '" + description + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create " + "ProjectDeploymentConfiguration failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        config = getProjectDeploymentConfiguration(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProjectDeploymentConfig";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return config;
}

From source file:net.bull.javamelody.SpringTestFacadeImpl.java

/**
 * {@inheritDoc}//  w  ww . j  a  v  a2s .  c om
 */
@Override
public Date nowWithSql() throws SQLException {
    //      final javax.sql.DataSource dataSource = (javax.sql.DataSource) new javax.naming.InitialContext()
    //            .lookup("java:comp/env/jdbc/TestDB");
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "net/bull/javamelody/monitoring-spring.xml", "spring-context.xml", });
    final javax.sql.DataSource dataSource = (javax.sql.DataSource) context.getBean("dataSource");
    final java.sql.Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    try {
        // test pour explain plan en oracle
        //         final PreparedStatement statement = connection
        //               .prepareStatement("select * from v$session where user# = ?");
        final Statement statement = connection.createStatement();
        try {
            //            statement.setInt(1, 36);
            //            statement.executeQuery();

            statement.execute(
                    "DROP ALIAS if exists SLEEP; CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\"");
            statement.execute("call sleep(.01)");
            for (int i = 0; i < 5; i++) {
                statement.execute("call sleep(.02)");
            }
        } finally {
            statement.close();
        }
    } finally {
        connection.rollback();
        connection.close();
    }

    return new Date();
}

From source file:br.com.localizae.model.service.FileServiceLocal.java

@Override
public void upload(File file) throws Exception {
    Connection conn = null;

    try {/*from w  w  w  .j av a 2 s .c o  m*/
        conn = ConnectionManager.getInstance().getConnection();
        FileDAO dao = new FileDAO();

        dao.create(conn, file);

        if (!file.getBase64().isEmpty()) {
            byte[] data = Base64.getDecoder().decode(file.getBase64());
            try (OutputStream stream = new FileOutputStream(Constantes.PATH_FILE + file.getUri())) {
                stream.write(data);
            }
        } else if (file.getFile().length != 0) {
            FileOutputStream fos = new FileOutputStream(Constantes.PATH_FILE + file.getUri());
            fos.write(file.getFile());

            fos.close();
        } else {
            throw new IllegalArgumentException(
                    " necessrio o envio do arquivo como array de byte ou como base64.");
        }

        conn.commit();
    } catch (Exception e) {
        conn.rollback();

        throw e;
    } finally {
        conn.close();
    }
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramSymbolSqlAdapter.java

public ProgramSymbol createNewProgramSymbol(int programID, String module, String symbol, int address, int size)
        throws AdaptationException {
    ProgramSymbol programSymbol = null;//w w w.  j  a v a 2s.co m
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProgramSymbols " + "(programID, module, symbol, address, size)"
                + " VALUES (" + programID + ", '" + module + "',  '" + symbol + "', " + address + ", " + size
                + ")";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM ProgramSymbols WHERE  " + "programID =  " + programID + "  AND "
                + "module    = '" + module + "' AND " + "symbol    = '" + symbol + "'";

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        programSymbol = getProgramSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProgramSymbol";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return programSymbol;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramProfilingSymbolSqlAdapter.java

public ProgramProfilingSymbol createNewProfilingSymbol(int configID, int programSymbolID)
        throws AdaptationException {
    ProgramProfilingSymbol profilingSymbol = null;
    Connection connection = null;
    Statement statement = null;/* w w  w .j  av a2 s  .co  m*/
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProgramProfilingSymbols"
                + "(projectDeploymentConfigurationID, programSymbolID)" + " VALUES (" + configID + ", "
                + programSymbolID + ")";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM ProgramProfilingSymbols WHERE " + "projectDeploymentConfigurationID = "
                + configID + " AND programSymbolID             = " + programSymbolID;

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program profiling " + "symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }
        profilingSymbol = getProfilingSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProfilingSymbol";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return profilingSymbol;
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramProfilingMessageSymbolSqlAdapter.java

public ProgramProfilingMessageSymbol createNewProfilingMessageSymbol(int configID, int programMessageSymbolID)
        throws AdaptationException {
    ProgramProfilingMessageSymbol profilingMessageSymbol = null;
    Connection connection = null;
    Statement statement = null;//www  . java  2 s. com
    ResultSet resultSet = null;

    try {
        String query = "INSERT INTO ProgramProfilingMessageSymbols"
                + "(projectDeploymentConfigurationID, programMessageSymbolID)" + " VALUES (" + configID + ", "
                + programMessageSymbolID + ")";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        statement.executeUpdate(query);

        query = "SELECT * FROM ProgramProfilingMessageSymbols WHERE " + "projectDeploymentConfigurationID = "
                + configID + " AND " + "programMessageSymbolID           = " + programMessageSymbolID;

        resultSet = statement.executeQuery(query);

        if (!resultSet.next()) {
            connection.rollback();
            String msg = "Attempt to create program profiling message " + "symbol failed.";
            log.error(msg);
            throw new AdaptationException(msg);
        }

        profilingMessageSymbol = getProfilingMessageSymbol(resultSet);
        connection.commit();
    } catch (SQLException ex) {
        try {
            connection.rollback();
        } catch (Exception e) {
        }

        String msg = "SQLException in createNewProfilingMessageSymbol";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return profilingMessageSymbol;
}

From source file:gridool.db.sql.ParallelSQLExecJob.java

private static String invokeStringOutputReduce(final Connection conn, final String reduceQuery,
        final ReadWriteLock rwlock) throws GridException {
    final ResultSetHandler rsh = new ResultSetHandler() {
        public String handle(ResultSet rs) throws SQLException {
            if (rs.next()) {
                String firstResult = rs.getString(1);
                return firstResult;
            }/*from   w w w . j a va2  s.  c  o  m*/
            return null;
        }
    };

    if (LOG.isInfoEnabled()) {
        LOG.info("Executing a Reduce SQL query: \n" + reduceQuery);
    }
    final String result;
    final Lock rlock = rwlock.readLock();
    try {
        rlock.lock();
        conn.setReadOnly(true);
        result = (String) JDBCUtils.query(conn, reduceQuery, rsh);
    } catch (SQLException e) {
        String errmsg = "failed running a reduce query: " + reduceQuery;
        LOG.error(errmsg, e);
        try {
            conn.rollback();
        } catch (SQLException rbe) {
            LOG.warn("Rollback failed", rbe);
        }
        throw new GridException(errmsg, e);
    } finally {
        rlock.unlock();
    }
    return result;
}