Example usage for javax.transaction TransactionManager begin

List of usage examples for javax.transaction TransactionManager begin

Introduction

In this page you can find the example usage for javax.transaction TransactionManager begin.

Prototype

public void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file:org.apache.synapse.commons.transaction.TranscationManger.java

public static void beginTransaction() throws Exception {
    long key = Thread.currentThread().getId();
    try {/*www . ja va 2s  .  c o m*/
        if (log.isDebugEnabled()) {
            log.debug("beginTransaction()");
        }

        TransactionManager txMgr = txManagers.get().get(key);
        txMgr.begin();
        Transaction tx = txMgr.getTransaction();
        transactions.get().put(key, tx);
        log.debug(" BEGIN  : " + transactions.get().get(key).getStatus());

    } catch (Exception ex) {
        log.debug(" BEGIN ERROR  : " + txManagers.get().get(key).getStatus());
        throw ex;
    }

}

From source file:org.hibernate.search.test.performance.scenario.TestExecutor.java

private void beginTransaction(SessionImplementor session) {
    if (session.getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta()) {
        TransactionManager transactionManager = lookupTransactionManager(session);
        try {//from   w  w w . ja  va  2  s.c  o m
            transactionManager.begin();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        session.getTransaction().begin();
    }
}

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  w  w  .  j  a  va2s  . 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

/**
 * Suspend the current transaction if active and start a new transaction
 *
 * @return the suspended transaction or null
 * @throws TransactionRuntimeException/*w  w w. j  av a 2s .co m*/
 * @since 5.6
 */
public static Transaction requireNewTransaction() {
    TransactionManager tm = NuxeoContainer.getTransactionManager();
    if (tm == null) {
        return null;
    }
    try {
        Transaction tx = tm.getTransaction();
        if (tx != null) {
            tx = tm.suspend();
        }
        tm.begin();
        return tx;
    } catch (NotSupportedException | SystemException e) {
        throw new TransactionRuntimeException("Cannot suspend 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 {/* ww w  . j a v  a2s .c o  m*/
            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   ww w .  ja v a  2 s.  c  om*/
        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.
 *//*from   w  w w .ja v a  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./*from www . j  ava  2s. c o 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();
    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();// w  ww.ja v  a  2s  .c o  m
    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.seasar.s2click.test.S2ClickServiceTestCase.java

protected void doRunTest() throws Throwable {
    TransactionManager tm = null;
    if (needTransaction()) {
        try {/*from  w w w  .j a v  a 2 s  .  co  m*/
            tm = (TransactionManager) getComponent(TransactionManager.class);
            tm.begin();
        } catch (Throwable t) {
            System.err.println(t);
        }
    }
    try {
        try {
            // ??
            readXlsAllReplaceDb(getClass().getSimpleName() + "_" + getTargetMethod().getName() + "_data.xls");
        } catch (ResourceNotFoundRuntimeException ex) {
            // ??????
        }

        // ???Excel??
        Method method = getTargetMethod();
        GenerateExcel annGenExcel = method.getAnnotation(GenerateExcel.class);
        if (annGenExcel != null) {
            Table[] tables = annGenExcel.tables();
            // Excel??????
            createExcelFile(tables);
        }

        // ?
        runTest();

        // Assert??
        Assert annAssert = method.getAnnotation(Assert.class);
        if (annAssert != null) {
            Table[] tables = annAssert.tables();
            // Excel??????
            createExcelFile(tables);
            // ?
            DataSet ds = getExpectDataSet();
            for (Table table : tables) {
                String tableName = table.name();
                assertEquals(ds.getTable(tableName), readDbByTable(tableName));
            }
        }
    } finally {
        if (tm != null) {
            tm.rollback();
        }
    }
}