List of usage examples for javax.transaction TransactionManager commit
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException;
From source file:org.jboss.ejb3.entity.JTATableIdGenerator.java
public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException { // get TransactionManager from JNDI // no JNDI properties provided -> we are in the container TransactionManager tm = transactionManagerLookup.getTransactionManager(new Properties()); Transaction surroundingTransaction = null; // for resuming in finally block Connection conn = null; // for ressource cleanup String sql = null; // for exception try {//from w ww .j a va 2s . c o m long result; // holds the resulting sequence value // prepare a new transaction context for the generator surroundingTransaction = tm.suspend(); if (log.isDebugEnabled()) { log.debug("surrounding tx suspended"); } tm.begin(); // get connection from managed environment conn = session.getBatcher().openConnection(); // execute fetching of current sequence value sql = query; PreparedStatement qps = conn.prepareStatement(query); try { ResultSet rs = qps.executeQuery(); if (!rs.next()) { String err = "could not read sequence value - you need to populate the table: " + tableName; log.error(err); throw new IdentifierGenerationException(err); } result = rs.getLong(1); rs.close(); } catch (SQLException sqle) { log.error("could not read a sequence value", sqle); throw sqle; } finally { qps.close(); } // increment sequence value sql = update; long sequence = result + 1; PreparedStatement ups = conn.prepareStatement(update); try { ups.setLong(1, sequence); ups.setLong(2, result); ups.executeUpdate(); } catch (SQLException sqle) { log.error("could not update sequence value in: " + tableName, sqle); throw sqle; } finally { ups.close(); } // commit transaction to ensure updated sequence is not rolled back tm.commit(); // transform sequence to the desired type and return the value Number typedSequence = IdentifierGeneratorFactory.createNumber(sequence, returnClass); if (log.isDebugEnabled()) { log.debug("generate() returned: " + typedSequence); } return typedSequence; } catch (SQLException sqle) { throw JDBCExceptionHelper.convert(session.getFactory().getSQLExceptionConverter(), sqle, "could not get or update next value", sql); } catch (Exception e) { try { tm.rollback(); throw new HibernateException(e); } catch (SystemException e1) { throw new HibernateException(e1); } } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { // ignore exception } // switch back to surrounding transaction context if (surroundingTransaction != null) { try { tm.resume(surroundingTransaction); if (log.isDebugEnabled()) { log.debug("surrounding tx resumed"); } } catch (Exception e) { throw new HibernateException(e); } } } }
From source file:org.nuxeo.runtime.transaction.TransactionHelper.java
/** * Commit the current transaction if active and resume the principal transaction * * @param tx//from w w w. ja va 2 s. c o m */ public static void resumeTransaction(Transaction tx) { TransactionManager tm = NuxeoContainer.getTransactionManager(); if (tm == null) { return; } try { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.commit(); } if (tx != null) { tm.resume(tx); } } catch (SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException | InvalidTransactionException | IllegalStateException | SecurityException e) { throw new TransactionRuntimeException("Cannot resume tx", e); } }
From source file:org.openejb.transaction.TxRequired.java
public InvocationResult invoke(Interceptor interceptor, EjbInvocation ejbInvocation, TransactionManager transactionManager) throws Throwable { Transaction transaction = transactionManager.getTransaction(); if (transaction != null) { try {/*from www .ja va 2 s .c om*/ return interceptor.invoke(ejbInvocation); } catch (Throwable t) { transactionManager.setRollbackOnly(); if (ejbInvocation.getType().isLocal()) { throw new TransactionRolledbackLocalException().initCause(t); } else { // can't set an initCause on a TransactionRolledbackException throw new TransactionRolledbackException(t.getMessage()); } } } transactionManager.begin(); try { InvocationResult result = interceptor.invoke(ejbInvocation); return result; } catch (RollbackException re) { throw re; } catch (Throwable t) { try { transactionManager.setRollbackOnly(); } catch (Exception e) { log.warn("Unable to roll back", e); } throw t; } finally { if (transactionManager.getStatus() == Status.STATUS_ACTIVE) { transactionManager.commit(); } else { transactionManager.rollback(); } } }
From source file:org.openejb.transaction.TxRequiresNew.java
public InvocationResult invoke(Interceptor interceptor, EjbInvocation ejbInvocation, TransactionManager transactionManager) throws Throwable { Transaction callerTransaction = transactionManager.suspend(); try {/*from w w w. ja v a2 s . co m*/ transactionManager.begin(); try { InvocationResult result = interceptor.invoke(ejbInvocation); return result; } catch (RollbackException re) { throw re; } catch (Throwable t) { try { transactionManager.setRollbackOnly(); } catch (Exception e) { log.warn("Unable to roll back", e); } throw t; } finally { if (transactionManager.getStatus() == Status.STATUS_ACTIVE) { transactionManager.commit(); } else { transactionManager.rollback(); } } } finally { if (callerTransaction != null) { transactionManager.resume(callerTransaction); } } }
From source file:org.rhq.enterprise.server.core.plugin.AgentPluginScanner.java
/** * This method will stream up plugin content if the server has a plugin file * but there is null content in the database (only occurs when upgrading an old server to the new * schema that supports database-storage for plugins). This method will be a no-op for * recent versions of the server because the database will no longer have null content from now on. *///ww w . java 2 s .c o m void fixMissingAgentPluginContent() throws Exception { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; // This map contains the names/paths of plugins that are missing their content in the database. // This map will only have entries if this server was recently upgraded from an older version // that did not support database-stored plugin content. Map<String, String> pluginsMissingContentInDb = new HashMap<String, String>(); // This map contains the names/MD5s of plugins that are missing their content in the database. // This map will only have entries if this server was recently upgraded from an older version // that did not support database-stored plugin content. Map<String, String> pluginsMissingContentInDbMD5 = new HashMap<String, String>(); try { DataSource ds = LookupUtil.getDataSource(); conn = ds.getConnection(); ps = conn.prepareStatement( "SELECT NAME, PATH, MD5 FROM " + Plugin.TABLE_NAME + " WHERE CONTENT IS NULL AND ENABLED = ?"); setEnabledFlag(conn, ps, 1, true); rs = ps.executeQuery(); while (rs.next()) { String name = rs.getString(1); String path = rs.getString(2); String md5 = rs.getString(3); pluginsMissingContentInDb.put(name, path); pluginsMissingContentInDbMD5.put(name, md5); } } finally { JDBCUtil.safeClose(conn, ps, rs); } if (!pluginsMissingContentInDb.isEmpty()) { // if a plugin used to exist but now doesn't, it should be deleted - we should not fail when this occurs List<String> pluginsToDelete = new ArrayList<String>(); // in all likelihood, the new plugins have different filenames; but since the descriptors // will have the same plugin names, we'll be able to key off of plugin name PluginDescriptor descriptor; Map<String, File> existingPluginFiles = new HashMap<String, File>(); // keyed on plugin name for (File file : this.agentPluginDeployer.getPluginDir().listFiles()) { if (file.getName().endsWith(".jar")) { try { descriptor = AgentPluginDescriptorUtil.loadPluginDescriptorFromUrl(file.toURI().toURL()); existingPluginFiles.put(descriptor.getName(), file); } catch (Exception e) { log.warn("File [" + file + "] is not a valid plugin and will be ignored: " + e); } } } // now let's take the new content and stream it into the DB for (Map.Entry<String, String> entry : pluginsMissingContentInDb.entrySet()) { String name = entry.getKey(); String path = entry.getValue(); String expectedMD5 = pluginsMissingContentInDbMD5.get(name); File pluginFile = existingPluginFiles.get(name); if (pluginFile != null) { String newMD5 = MessageDigestGenerator.getDigestString(pluginFile); boolean different = !expectedMD5.equals(newMD5); streamPluginFileContentToDatabase(name, pluginFile, different); log.info("Missing content for plugin [" + name + "] will be uploaded from [" + pluginFile + "]. different=" + different); } else { pluginsToDelete.add(name); log.warn("The database knows of a plugin named [" + name + "] with path [" + path + "] but the content is missing. This server does not have this plugin in [" + this.agentPluginDeployer.getPluginDir() + "] so the database cannot be updated with the content." + " This plugin must be installed to manage existing inventory for its resource types."); } } if (!pluginsToDelete.isEmpty()) { TransactionManager tm = LookupUtil.getTransactionManager(); for (String pluginName : pluginsToDelete) { try { tm.begin(); DataSource ds = LookupUtil.getDataSource(); conn = ds.getConnection(); ps = conn.prepareStatement( "UPDATE " + Plugin.TABLE_NAME + " SET ENABLED = ? WHERE NAME = ?"); setEnabledFlag(conn, ps, 1, false); ps.setString(2, pluginName); int updateResults = ps.executeUpdate(); if (updateResults == 1) { log.warn("Disabled unavailable plugin [" + pluginName + "] - This plugin must be provided to manage committed resources for its types." + " Uninventory obsolete resources to avoid getting warnings in the server and agent."); } else { // TODO: should we throw an exception or is continuing the right thing to do? log.error("Failed to disable unavailable plugin [" + pluginName + "]."); } } catch (Exception e) { tm.rollback(); tm = null; throw e; } finally { JDBCUtil.safeClose(conn, ps, null); if (tm != null) { tm.commit(); } } } } } return; }
From source file:org.rhq.enterprise.server.core.plugin.AgentPluginScanner.java
/** * This will write the contents of the given plugin file to the database. * This will store both the contents and the MD5 in an atomic transaction * so they remain insync.// w w w . ja va 2s .co m * * When <code>different</code> is <code>false</code>, it means the original * plugin and the one currently found on the file system are the same. * * When <code>different</code> is <code>true</code>, it means the plugin * is most likely a different one than the one that originally existed. * When this happens, it is assumed that the {@link ProductPluginDeployer} needs * to see the plugin on the file system as new and needing to be processed, therefore * the MD5, CONTENT and MTIME columns will be updated to ensure the deployer * will process this plugin and thus update all the metadata for this plugin. * * @param name the name of the plugin whose content is being updated * @param file the plugin file whose content will be streamed to the database * @param different this will be <code>true</code> if the given file has a different filename * that the plugin's "path" as found in the database. * * * @throws Exception */ private void streamPluginFileContentToDatabase(String name, File file, boolean different) throws Exception { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; TransactionManager tm = null; String sql = "UPDATE " + Plugin.TABLE_NAME + " SET CONTENT = ?, MD5 = ?, MTIME = ?, PATH = ? WHERE DEPLOYMENT = 'AGENT' AND NAME = ?"; // if 'different' is true, give bogus data so the plugin deployer will think the plugin on the file system is new String md5 = (!different) ? MessageDigestGenerator.getDigestString(file) : "TO BE UPDATED"; long mtime = (!different) ? file.lastModified() : 0L; InputStream fis = (!different) ? new FileInputStream(file) : new ByteArrayInputStream(new byte[0]); int contentSize = (int) ((!different) ? file.length() : 0); try { tm = LookupUtil.getTransactionManager(); tm.begin(); DataSource ds = LookupUtil.getDataSource(); conn = ds.getConnection(); ps = conn.prepareStatement(sql); ps.setBinaryStream(1, new BufferedInputStream(fis), contentSize); ps.setString(2, md5); ps.setLong(3, mtime); ps.setString(4, file.getName()); ps.setString(5, name); int updateResults = ps.executeUpdate(); if (updateResults == 1) { log.info("Stored content for plugin [" + name + "] in the db. file=" + file); } else { throw new Exception("Failed to update content for plugin [" + name + "] from [" + file + "]"); } } catch (Exception e) { tm.rollback(); tm = null; throw e; } finally { JDBCUtil.safeClose(conn, ps, rs); try { fis.close(); } catch (Throwable t) { } if (tm != null) { tm.commit(); } } return; }
From source file:org.sakaiproject.kernel.test.RepositoryKernelUnitT.java
@Test public void testJCRNodeFactory() throws JCRNodeFactoryServiceException, LoginException, RepositoryException, IOException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { KernelManager km = new KernelManager(); Kernel kernel = km.getKernel(); JCRNodeFactoryService jcrNodeFactoryService = kernel.getService(JCRNodeFactoryService.class); TransactionManager transactionManager = kernel.getService(TransactionManager.class); JCRService jcrService = kernel.getService(JCRService.class); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); long start = System.currentTimeMillis(); transactionManager.begin();/* w w w.j ava 2 s.c o m*/ Session session = jcrService.loginSystem(); LOG.info("===============================SESSION STARTED================================="); LOG.info("===============================SESSION STARTED================================="); LOG.info("===============================SESSION STARTED================================="); LOG.info("===============================SESSION STARTED================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); LOG.info("===============================STARTING TEST================================="); jcrNodeFactoryService.createFile("/test/test.txt", RestProvider.CONTENT_TYPE); LOG.info("===============================SESSION SAVE OPERAION================================="); LOG.info("===============================SESSION SAVE OPERAION================================="); LOG.info("===============================SESSION SAVE OPERAION================================="); LOG.info("===============================SESSION SAVE OPERAION================================="); session.save(); LOG.info("===============================SAVE COMPLETE================================="); LOG.info("===============================SAVE COMPLETE================================="); LOG.info("===============================SAVE COMPLETE================================="); LOG.info("===============================SAVE COMPLETE================================="); LOG.info("===============================STARTING TEST2================================="); LOG.info("===============================STARTING TEST2================================="); LOG.info("===============================STARTING TEST2================================="); LOG.info("===============================STARTING TEST2================================="); LOG.info("===============================STARTING TEST2================================="); jcrNodeFactoryService.createFile("/test/test2.txt", RestProvider.CONTENT_TYPE); LOG.info("===============================SESSION SAVE OPERAION2================================="); LOG.info("===============================SESSION SAVE OPERAION2================================="); LOG.info("===============================SESSION SAVE OPERAION2================================="); LOG.info("===============================SESSION SAVE OPERAION2================================="); session.save(); LOG.info("===============================SAVE COMPLETE2================================="); LOG.info("===============================SAVE COMPLETE2================================="); LOG.info("===============================SAVE COMPLETE2================================="); LOG.info("===============================SAVE COMPLETE2================================="); transactionManager.commit(); LOG.info("===============================COMMIT COMPLETE================================="); LOG.info("===============================COMMIT COMPLETE================================="); LOG.info("===============================COMMIT COMPLETE================================="); LOG.info("===============================COMMIT COMPLETE================================="); LOG.info("===============================COMMIT COMPLETE================================="); long end = System.currentTimeMillis() - start; LOG.info("== " + end + " (ms)=============================DONE TEST================================="); LOG.info("== " + end + " (ms)=============================DONE TEST================================="); LOG.info("== " + end + " (ms)=============================DONE TEST================================="); LOG.info("== " + end + " (ms)=============================DONE TEST================================="); LOG.info("== " + end + " (ms)=============================DONE TEST================================="); jcrNodeFactoryService.createFolder("/test/newfolder"); session.save(); ByteArrayInputStream bais = new ByteArrayInputStream("testvalue".getBytes("UTF-8")); jcrNodeFactoryService.setInputStream("/test/test.txt", bais, RestProvider.CONTENT_TYPE); session.save(); String result = IOUtils.readFully(jcrNodeFactoryService.getInputStream("/test/test.txt"), "UTF-8"); assertEquals("testvalue", result); Node n = jcrNodeFactoryService.getNode("/test/test.txt"); assertNotNull(n); jcrService.logout(); }
From source file:org.wso2.carbon.dataservices.core.description.xa.DSSXATransactionManager.java
public void commit() throws DataServiceFault { TransactionManager txManager = getTransactionManager(); if (txManager == null) { return;/* w ww. j a v a 2 s .c o m*/ } try { if (log.isDebugEnabled()) { log.debug("transactionManager.commit()"); } txManager.commit(); } catch (Exception e) { throw new DataServiceFault(e, "Error from transaction manager when committing: " + e.getMessage()); } finally { this.beginTx.set(false); } }
From source file:org.wso2.carbon.humantask.core.scheduler.SimpleScheduler.java
public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception { TransactionManager txm = transactionManager; if (txm == null) { throw new HumanTaskException( "Cannot locate the transaction manager; " + "the server might be shutting down."); }//from ww w. j a v a 2 s . c om // The value of the timeout is in seconds. If the value is zero, // the transaction service restores the default value. if (timeout < 0) { throw new IllegalArgumentException("Timeout must be positive, received: " + timeout); } boolean existingTransaction; try { existingTransaction = txm.getTransaction() != null; } catch (Exception ex) { String errMsg = "Internal Error, could not get current transaction."; throw new HumanTaskException(errMsg, ex); } // already in transaction, execute and return directly if (existingTransaction) { return transaction.call(); } // run in new transaction Exception ex = null; // int immediateRetryCount = _immediateTransactionRetryLimit; transactionManager.setTransactionTimeout(timeout); if (log.isDebugEnabled() && timeout != 0) { log.debug("Custom transaction timeout: " + timeout); } try { try { if (log.isDebugEnabled()) { log.debug("Beginning a new transaction"); } txm.begin(); } catch (Exception e) { String errMsg = "Internal Error, could not begin transaction."; throw new HumanTaskException(errMsg, e); } try { ex = null; return transaction.call(); } catch (Exception e) { ex = e; } finally { if (ex == null) { if (log.isDebugEnabled()) { log.debug("Committing on " + txm + "..."); } try { txm.commit(); } catch (Exception e2) { ex = e2; } } else { if (log.isDebugEnabled()) { log.debug("Rollbacking on " + txm + "..."); } txm.rollback(); } // if (ex != null && immediateRetryCount > 0) { // if (log.isDebugEnabled()) { // log.debug("Will retry the transaction in " + // _immediateTransactionRetryInterval + " msecs on " + // transactionManager + " for error: ", ex); // } // Thread.sleep(_immediateTransactionRetryInterval); // } } } finally { // 0 restores the default value transactionManager.setTransactionTimeout(0); } throw ex; }
From source file:org.wso2.carbon.rssmanager.core.RSSTransactionManager.java
public void commit() throws RSSManagerException { /* if we didn't begin this transaction, don't commit it */ if (!this.beginTx.get()) { return;//from w w w .ja v a2 s . c o m } TransactionManager txManager = getTransactionManager(); try { if (log.isDebugEnabled()) { log.debug("transactionManager.commit()"); } txManager.commit(); } catch (Exception e) { throw new RSSManagerException("Error from transaction manager when committing", e); } finally { this.beginTx.set(false); } }