List of usage examples for java.sql Connection getAutoCommit
boolean getAutoCommit() throws SQLException;
Connection
object. From source file:com.concursive.connect.web.modules.common.social.rating.dao.Rating.java
public static synchronized RatingBean save(Connection db, int userId, int projectId, int objectId, String vote, String table, String uniqueField, int setInappropriateColumn) throws SQLException { boolean commit = false; try {/*from ww w. jav a2s . com*/ commit = db.getAutoCommit(); if (commit) { db.setAutoCommit(false); } // Determine the current value int existingVote = queryUserRating(db, userId, objectId, table, uniqueField); int newVote = Integer.parseInt(vote); PreparedStatement pst = null; ResultSet rs = null; // Determine if an update, insert, or delete is required if (existingVote == -1) { // Perform an insert pst = db.prepareStatement("INSERT INTO " + table + "_rating " + "(project_id, " + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : uniqueField + ", ") + ((setInappropriateColumn != Constants.UNDEFINED) ? "inappropriate, " : "") + "rating, enteredby) " + "VALUES (?, " + (Project.PRIMARY_KEY.equals(uniqueField) ? "" : "?, ") + ((setInappropriateColumn != Constants.UNDEFINED) ? "?, " : "") + "?, ?)"); int i = 0; pst.setInt(++i, projectId); if (!Project.PRIMARY_KEY.equals(uniqueField)) { pst.setInt(++i, objectId); } if (setInappropriateColumn != Constants.UNDEFINED) { pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE)); } pst.setInt(++i, newVote); pst.setInt(++i, userId); pst.execute(); pst.close(); } else if (existingVote != newVote) { // Try an update pst = db.prepareStatement("UPDATE " + table + "_rating " + "SET rating = ?, entered = " + DatabaseUtils.getCurrentTimestamp(db) + " " + ((setInappropriateColumn != Constants.UNDEFINED) ? ", inappropriate = ? " : "") + "WHERE " + uniqueField + " = ? AND enteredby = ? "); int i = 0; pst.setInt(++i, newVote); if (setInappropriateColumn != Constants.UNDEFINED) { pst.setBoolean(++i, (setInappropriateColumn == Constants.TRUE)); } pst.setInt(++i, objectId); pst.setInt(++i, userId); pst.execute(); pst.close(); } if (existingVote != newVote) { // Update the object count and value pst = db.prepareStatement("UPDATE " + table + " " + "SET rating_count = rating_count + ?, rating_value = rating_value + ?, " + "rating_avg = ((rating_value + ?) / (rating_count + ?)) " + "WHERE " + uniqueField + " = ? "); int i = 0; if (existingVote == -1) { if (newVote == INAPPROPRIATE_COMMENT) { //rating count is incremented, but no change in rating value, therefore, rating average decreases pst.setInt(++i, 1); pst.setInt(++i, 0); pst.setInt(++i, 0); pst.setInt(++i, 1); } else { pst.setInt(++i, 1); pst.setInt(++i, newVote); pst.setInt(++i, newVote); pst.setInt(++i, 1); } } else { if (newVote == INAPPROPRIATE_COMMENT || existingVote == INAPPROPRIATE_COMMENT) { if (newVote == INAPPROPRIATE_COMMENT) { //The effects of the previous rating are reversed. pst.setInt(++i, 0); pst.setInt(++i, (-1) * existingVote); pst.setInt(++i, (-1) * existingVote); pst.setInt(++i, 0); } else if (existingVote == INAPPROPRIATE_COMMENT) { //The new rating by the user is recorded, //as an existing inappropriate comment was never considered towards rating value, no additional math is required pst.setInt(++i, 0); pst.setInt(++i, newVote); pst.setInt(++i, newVote); pst.setInt(++i, 0); } } else { pst.setInt(++i, 0); pst.setInt(++i, newVote - existingVote); pst.setInt(++i, newVote - existingVote); pst.setInt(++i, 0); } } pst.setInt(++i, objectId); //System.out.println(pst); pst.execute(); pst.close(); } if (setInappropriateColumn != Constants.UNDEFINED) { int inappropriateCount = 0; pst = db.prepareStatement("SELECT count(*) AS ic " + "FROM " + table + "_rating " + "WHERE " + uniqueField + " = ? AND inappropriate = ?"); int i = 0; pst.setInt(++i, objectId); pst.setBoolean(++i, true); rs = pst.executeQuery(); if (rs.next()) { inappropriateCount = rs.getInt("ic"); } rs.close(); pst.close(); pst = db.prepareStatement("UPDATE " + table + " " + "SET inappropriate_count = ? " + "WHERE " + uniqueField + " = ? "); i = 0; pst.setInt(++i, inappropriateCount); pst.setInt(++i, objectId); pst.execute(); pst.close(); } // Retrieve the values pst = db.prepareStatement( "SELECT rating_count, rating_value " + "FROM " + table + " WHERE " + uniqueField + " = ?"); pst.setInt(1, objectId); rs = pst.executeQuery(); int count = 0; int value = 0; if (rs.next()) { count = rs.getInt("rating_count"); value = rs.getInt("rating_value"); } rs.close(); pst.close(); if (commit) { db.commit(); } // Share the rating bean RatingBean rating = new RatingBean(); rating.setItemId(objectId); rating.setCount(count); rating.setValue(value); return rating; } catch (Exception e) { if (commit) { db.rollback(); } LOG.error("save", e); throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } }
From source file:org.apache.airavata.sharing.registry.db.utils.JPAUtils.java
public static void initializeDB() throws SharingRegistryException { jdbcDriver = readServerProperties(SHARING_REG_JDBC_DRIVER); jdbcURl = readServerProperties(SHARING_REG_JDBC_URL); jdbcUser = readServerProperties(SHARING_REG_JDBC_USER); jdbcPassword = readServerProperties(SHARING_REG_JDBC_PWD); jdbcURl = jdbcURl + "?" + "user=" + jdbcUser + "&" + "password=" + jdbcPassword; if (getDBType(jdbcURl).equals("derby") && isDerbyStartEnabled()) { startDerbyInServerMode();/*from ww w.ja v a 2s . c o m*/ } db = new JdbcStorage(10, 50, jdbcURl, jdbcDriver, true); Connection conn = null; try { conn = db.connect(); if (!DatabaseCreator.isDatabaseStructureCreated(CONFIGURATION, conn)) { DatabaseCreator.createRegistryDatabase("database_scripts/sharing-registry", conn); logger.info("New Database created for Sharing Catalog !!! "); } else { logger.info("Database already created for Sharing Catalog !!!"); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException("Database failure", e); } finally { db.closeConnection(conn); try { if (conn != null) { if (!conn.getAutoCommit()) { conn.commit(); } conn.close(); } } catch (SQLException e) { logger.error("Error while closing database connection...", e.getMessage(), e); } } }
From source file:org.artifactory.storage.db.spring.ArtifactoryPoolableConnectionFactory.java
@Override public void passivateObject(Object obj) throws Exception { if (obj instanceof Connection) { Connection conn = (Connection) obj; if (!conn.getAutoCommit() && !conn.isReadOnly()) { conn.rollback();/*from w ww . j a v a 2s .c om*/ } conn.clearWarnings(); //if(!conn.getAutoCommit()) { // conn.setAutoCommit(true); //} } if (obj instanceof DelegatingConnection) { Method passivateMethod = ReflectionUtils.findMethod(DelegatingConnection.class, "passivate"); passivateMethod.setAccessible(true); ReflectionUtils.invokeMethod(passivateMethod, obj); } }
From source file:dk.netarkivet.common.utils.DBUtils.java
/** * Method to perform a rollback of complex DB updates. If no commit has * been performed, this will undo the entire transaction, otherwise * nothing will happen. If autoCommit is true then no action is taken. * This method should be called in a finally block with * no DB updates after the last commit.//from w w w . j a v a2 s . co m * Thus exceptions while closing are ignored, but logged as warnings. * * NB: the provided connection is not closed. * * @param c the db-connection * @param action The action going on, before calling this method * @param o The Object being acted upon by this action */ public static void rollbackIfNeeded(Connection c, String action, Object o) { ArgumentNotValid.checkNotNull(c, "Connection c"); try { if (!c.getAutoCommit()) { c.rollback(); c.setAutoCommit(true); } } catch (SQLException e) { log.warn("SQL error doing rollback after " + action + " " + o + "\n" + ExceptionUtils.getSQLExceptionCause(e), e); // Can't throw here, we want the real exception } }
From source file:org.alinous.plugin.mysql.MySQLConnectionFactory.java
@Override public void passivateObject(Object arg0) throws Exception { Connection con = (Connection) arg0; if (!con.getAutoCommit()) { con.rollback();/* w w w . j a v a 2 s . c o m*/ con.setAutoCommit(true); } //AlinousDebug.debugOut("*************About passivateObject(arg0);"); super.passivateObject(arg0); }
From source file:org.sakaiproject.genericdao.springutil.SmartDataSourceWrapper.java
/** * Fixes up the auto-commit to be equal to the setting for this connection if possible, * will not cause an exception though if it fails to do it * @param connection the connection/*w w w . jav a 2 s. co m*/ * @return the same connection that was input */ private Connection fixAutoCommit(Connection connection) { try { if (connection.getAutoCommit() != autoCommitConnection) { connection.setAutoCommit(autoCommitConnection); } } catch (SQLException e) { // do nothing } return connection; }
From source file:azkaban.database.AzkabanConnectionPoolTest.java
@Test public void testGetNewConnectionAfterClose() throws Exception { connection.setAutoCommit(false);//from w ww. j av a 2 s . c o m /** * See {@link org.apache.commons.dbcp2.PoolableConnectionFactory#passivateObject}. * If the connection disables auto commit, when we close it, connection will be reset enabling auto commit, * and returned to connection pool. */ DbUtils.closeQuietly(connection); Connection newConnection = h2DataSource.getConnection(); Assert.assertEquals(newConnection.getAutoCommit(), true); DbUtils.closeQuietly(newConnection); }
From source file:kenh.xscript.database.elements.Commit.java
public void process(@Attribute(ATTRIBUTE_REF) java.sql.Connection conn) throws UnsupportedScriptException { try {//from w w w . j av a2s . co m if (!conn.isClosed()) { if (!conn.getAutoCommit()) conn.commit(); } } catch (Exception e) { throw new UnsupportedScriptException(this, e); } }
From source file:com.glaf.core.execution.FileExecutionHelper.java
public void createTable(Connection connection) { boolean autoCommit = false; try {/*from ww w. j ava 2s . c om*/ autoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); TableDefinition tableDefinition = BlobItemDomainFactory.getTableDefinition(); if (!DBUtils.tableExists(connection, BlobItemDomainFactory.TABLENAME)) { DBUtils.createTable(connection, tableDefinition); } else { DBUtils.alterTable(connection, tableDefinition); } connection.commit(); connection.setAutoCommit(autoCommit); } catch (Exception ex) { logger.error(ex); ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:hermes.store.jdbc.JDBCConnectionPool.java
public boolean beforeCheckin(Connection connection) { try {/*from w ww . ja v a 2 s.c om*/ if (connection.isClosed()) { return false; } else { if (!connection.getAutoCommit()) { connection.rollback(); } } } catch (SQLException ex) { log.warn("beforeCheckin failed:" + ex.getMessage(), ex); return false; } return true; }