List of usage examples for java.sql Connection setTransactionIsolation
void setTransactionIsolation(int level) throws SQLException;
Connection
object to the one given. From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
@Override public void rollbackTransaction() throws ODataServiceFault { Connection connection = getTransactionalConnection(); try {//from w w w. j a v a2 s.co m connection.rollback(); connection.setTransactionIsolation(defaultTransactionalIsolation); connection.setAutoCommit(defaultAutoCommit); } catch (SQLException e) { throw new ODataServiceFault(e, "Connection Error occurred while rollback. :" + e.getMessage()); } finally { /* close the connection */ try { connection.close(); transactionalConnection.set(null); } catch (Exception ignore) { // ignore } } }
From source file:org.wso2.carbon.user.core.system.SystemUserRoleManager.java
public String[] getSystemUsers() throws UserStoreException { Connection dbConnection = null; String sqlStmt = null;//from w w w . java 2 s . co m PreparedStatement prepStmt = null; ResultSet rs = null; String filter = "*"; int maxItemLimit = 100; String[] systemsUsers = new String[0]; try { if (filter != null && filter.trim().length() != 0) { filter = filter.trim(); filter = filter.replace("*", "%"); filter = filter.replace("?", "_"); } else { filter = "%"; } List<String> lst = new LinkedList<String>(); dbConnection = DatabaseUtil.getDBConnection(dataSource); if (dbConnection == null) { throw new UserStoreException("null connection"); } dbConnection.setAutoCommit(false); dbConnection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); sqlStmt = SystemJDBCConstants.GET_SYSTEM_USER_FILTER_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, filter); if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { prepStmt.setInt(2, tenantId); } rs = prepStmt.executeQuery(); int i = 0; while (rs.next()) { if (i < maxItemLimit) { String name = rs.getString(1); lst.add(name); } else { break; } i++; } rs.close(); if (lst.size() > 0) { systemsUsers = lst.toArray(new String[lst.size()]); } Arrays.sort(systemsUsers); systemsUsers = UserCoreUtil.addDomainToNames(systemsUsers, UserCoreConstants.SYSTEM_DOMAIN_NAME); } catch (SQLException e) { String errorMessage = "Error occurred while getting system users"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt); } return systemsUsers; }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Create a connection to the database; usually used only from within * getConnection(), which enforces a singleton guarantee around the * Connection object./*from w w w. j a v a2 s. c o m*/ */ protected Connection makeConnection() throws SQLException { Connection connection; String driverClass = getDriverClass(); try { Class.forName(driverClass); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not load db driver class: " + driverClass); } String username = options.getUsername(); String password = options.getPassword(); if (null == username) { connection = DriverManager.getConnection(options.getConnectString()); } else { connection = DriverManager.getConnection(options.getConnectString(), username, password); } // We only use this for metadata queries. Loosest semantics are okay. connection.setTransactionIsolation(getMetadataIsolationLevel()); connection.setAutoCommit(false); return connection; }
From source file:org.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java
/** * Updates the specified object in the object set. * <p/>// w ww .j ava 2 s . c om * This implementation requires MVCC and hence enforces that clients state what revision they expect * to be updating * <p/> * If successful, this method updates metadata properties within the passed object, * including: a new {@code _rev} value for the revised object's version * * @param fullId the identifier of the object to be put, or {@code null} to request a generated identifier. * @param rev the version of the object to update; or {@code null} if not provided. * @param obj the contents of the object to put in the object set. * @throws ConflictException if version is required but is {@code null}. * @throws ForbiddenException if access to the object is forbidden. * @throws NotFoundException if the specified object could not be found. * @throws PreconditionFailedException if version did not match the existing object in the set. * @throws BadRequestException if the passed identifier is invalid */ public void update(String fullId, String rev, Map<String, Object> obj) throws ObjectSetException { String localId = getLocalId(fullId); String type = getObjectType(fullId); if (rev == null) { throw new ConflictException("Object passed into update does not have revision it expects set."); } Connection connection = null; Integer previousIsolationLevel = null; boolean retry = false; int tryCount = 0; do { TableHandler handler = getTableHandler(type); if (handler == null) { throw new ObjectSetException("No handler configured for resource type " + type); } retry = false; ++tryCount; try { connection = getConnection(); previousIsolationLevel = new Integer(connection.getTransactionIsolation()); connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); connection.setAutoCommit(false); handler.update(fullId, type, localId, rev, obj, connection); connection.commit(); logger.debug("Commited updated object for id: {}", fullId); } catch (SQLException ex) { if (logger.isDebugEnabled()) { logger.debug("SQL Exception in update of {} with error code {}, sql state {}", new Object[] { fullId, ex.getErrorCode(), ex.getSQLState(), ex }); } rollback(connection); if (handler.isRetryable(ex, connection)) { if (tryCount <= maxTxRetry) { retry = true; logger.debug("Retryable exception encountered, retry {}", ex.getMessage()); } } if (!retry) { throw new InternalServerErrorException("Updating object failed " + ex.getMessage(), ex); } } catch (ObjectSetException ex) { logger.debug("ObjectSetException in update of {}", fullId, ex); rollback(connection); throw ex; } catch (java.io.IOException ex) { logger.debug("IO Exception in update of {}", fullId, ex); rollback(connection); throw new InternalServerErrorException("Conversion of object to update failed", ex); } catch (RuntimeException ex) { logger.debug("Runtime Exception in update of {}", fullId, ex); rollback(connection); throw new InternalServerErrorException( "Updating object failed with unexpected failure: " + ex.getMessage(), ex); } finally { if (connection != null) { try { if (previousIsolationLevel != null) { connection.setTransactionIsolation(previousIsolationLevel.intValue()); } } catch (SQLException ex) { logger.warn("Failure in resetting connection isolation level ", ex); } CleanupHelper.loggedClose(connection); } } } while (retry); }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
@Override public void openTransaction() throws ODataServiceFault { try {/*from w w w. jav a2s . com*/ if (getTransactionalConnection() == null) { Connection connection = this.dataSource.getConnection(); this.defaultAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); this.defaultTransactionalIsolation = connection.getTransactionIsolation(); connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); transactionalConnection.set(connection); } } catch (SQLException e) { throw new ODataServiceFault(e, "Connection Error occurred. :" + e.getMessage()); } }
From source file:massbank.DatabaseManager.java
private HashMap<String, String> getDatabaseOfAccessions() { GetConfig config = new GetConfig(MassBankEnv.get(MassBankEnv.KEY_BASE_URL)); String[] dbNames = config.getDbName(); HashMap<String, String> dbMapping = new HashMap<String, String>(); Connection con = null; try {/*ww w.java2 s. c o m*/ Class.forName(driver); con = DriverManager.getConnection(connectUrl, user, password); con.setAutoCommit(false); con.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); for (String db : dbNames) { String sql = "SELECT ACCESSION FROM " + db + ".RECORD"; PreparedStatement stmnt = con.prepareStatement(sql); ResultSet resultSet = stmnt.executeQuery(); while (resultSet.next()) { dbMapping.put(resultSet.getString("ACCESSION"), db); } resultSet.close(); } } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } return dbMapping; }
From source file:massbank.DatabaseManager.java
private void openConnection() { Connection con = null; try {/* w ww . j a v a 2s .c o m*/ Class.forName(DatabaseManager.driver); con = DriverManager.getConnection(this.connectUrl, DatabaseManager.user, DatabaseManager.password); con.setAutoCommit(false); con.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED); } catch (Exception e) { e.printStackTrace(); } this.con = con; }
From source file:com.cloudera.sqoop.manager.OracleManager.java
/** * Create a connection to the database; usually used only from within * getConnection(), which enforces a singleton guarantee around the * Connection object.// ww w. j av a 2s. c om * * Oracle-specific driver uses READ_COMMITTED which is the weakest * semantics Oracle supports. */ protected Connection makeConnection() throws SQLException { Connection connection; String driverClass = getDriverClass(); try { Class.forName(driverClass); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not load db driver class: " + driverClass); } String username = options.getUsername(); String password = options.getPassword(); String connectStr = options.getConnectString(); connection = CACHE.getConnection(connectStr, username); if (null == connection) { // Couldn't pull one from the cache. Get a new one. LOG.debug("Creating a new connection for " + connectStr + "/" + username); if (null == username) { connection = DriverManager.getConnection(connectStr); } else { connection = DriverManager.getConnection(connectStr, username, password); } } // We only use this for metadata queries. Loosest semantics are okay. connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); // Setting session time zone setSessionTimeZone(connection); return connection; }
From source file:com.commander4j.sys.JHost.java
public synchronized boolean connect(String sessionID, String host, String sqlPath, String viewPath) { Connection tempConn; boolean result = false; if (getSqlstatements().IsInitialised() == false) { getSqlstatements().setXMLFilename(sqlPath); getSqlstatements().setjdbcDriver(getDatabaseParameters().getjdbcDriver()); getSqlstatements().loadSQLStatements(host); getViewstatements().setXMLFilename(viewPath); getViewstatements().setjdbcDriver(getDatabaseParameters().getjdbcDriver()); getViewstatements().loadSQLStatements(host); getSqlstatements().setSubstitutions(getViewstatements().getSQLStatements()); getSqlstatements().setInitialised(); }/*w ww. j av a 2s . c om*/ if (connections.containsKey(sessionID) == false) { try { Class.forName(getDatabaseParameters().getjdbcDriver()).newInstance(); try { logger.debug(getDatabaseParameters().getjdbcConnectString()); DriverManager.setLoginTimeout(5); tempConn = DriverManager.getConnection(getDatabaseParameters().getjdbcConnectString(), getDatabaseParameters().getjdbcUsername(), getDatabaseParameters().getjdbcPassword()); tempConn.setAutoCommit(false); tempConn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); ++instanceCount; addConnection(sessionID, tempConn); result = true; setConnected(sessionID, true); logger.debug("Opened connection for session ID : " + sessionID); } catch (Exception ex) { String err = ""; try { err = ex.getMessage().substring(0, ex.getMessage().indexOf("\n")); } catch (Exception ex2) { err = ex.getMessage(); } logger.fatal(ex); if (Common.sd.getData(sessionID, "silentExceptions").equals("Yes") == false) { JUtility.errorBeep(); JSplashScreenUtils.hide(); JOptionPane.showMessageDialog(null, WordUtils.wrap(err, 100), "Database Connection Error (" + getSiteDescription() + ")", JOptionPane.ERROR_MESSAGE); } result = false; } } catch (Exception ex) { logger.fatal(ex); if (Common.sd.getData(sessionID, "silentExceptions").equals("Yes") == false) { JUtility.errorBeep(); JOptionPane.showMessageDialog(null, "Invalid jdbc driver [" + ex.getMessage() + "]", "Login Error (" + getSiteDescription() + ")", JOptionPane.ERROR_MESSAGE); } result = false; } } return result; }
From source file:edu.umd.cs.submitServer.servlets.UploadTestSetup.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO sanity checks on the format of the test setup MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); Connection conn = null; FileItem fileItem = null;/*from w w w. j av a 2 s . co m*/ boolean transactionSuccess = false; try { conn = getConnection(); fileItem = multipartRequest.getFileItem(); if (fileItem == null) throw new ServletException("fileItem is null; this is not good"); Project project = (Project) request.getAttribute(PROJECT); // could be null String comment = multipartRequest.getOptionalCheckedParameter("comment"); // get size in bytes long sizeInBytes = fileItem.getSize(); if (sizeInBytes == 0) { throw new ServletException("Trying upload file of size 0"); } // copy the fileItem into a byte array InputStream is = fileItem.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes); IO.copyStream(is, bytes); byte[] byteArray = bytes.toByteArray(); FormatDescription desc = FormatIdentification.identify(byteArray); if (desc == null || !desc.getMimeType().equals("application/zip")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "You MUST submit test-setups that are either zipped or jarred"); return; } Submission canonicalSubmission = Submission .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn); // start transaction here conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); TestSetup.submit(byteArray, project, comment, conn); conn.commit(); transactionSuccess = true; if (canonicalSubmission != null && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) { WaitingBuildServer.offerSubmission(project, canonicalSubmission); } String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK=" + project.getProjectPK(); response.sendRedirect(redirectUrl); } catch (SQLException e) { throw new ServletException(e); } finally { rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn); releaseConnection(conn); if (fileItem != null) fileItem.delete(); } }