Example usage for javax.transaction TransactionManager rollback

List of usage examples for javax.transaction TransactionManager rollback

Introduction

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

Prototype

public void rollback() throws IllegalStateException, SecurityException, SystemException;

Source Link

Document

Roll back the transaction associated with the current thread.

Usage

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

public void testPutTxWithRollback() throws Exception {
    final CacheSPI<Object, Object> c2 = this.cache1;
    Thread t1 = new Thread() {
        public void run() {
            TransactionManager tm;

            try {
                lock.acquire();// w w w .j av a 2 s . c  om
                tm = beginTransaction();
                c2.put("/a/b/c", "age", 38);
                c2.put("/a/b/c", "age", 39);
                lock.release();

                Thread.sleep(100);
                lock.acquire();
                tm.rollback();
                lock.release();
            } catch (Throwable ex) {
                ex.printStackTrace();
                t1_ex = ex;
            } finally {
                lock.release();
            }
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            TransactionManager tm;

            try {
                sleep(200);
                Thread.yield();
                lock.acquire();
                tm = beginTransaction();
                assertNull(cache2.get("/a/b/c", "age"));// must be null as not yet
                                                        // committed
                lock.release();

                Thread.sleep(100);
                lock.acquire();
                assertNull(cache2.get("/a/b/c", "age"));// must be null as rolledback
                tm.commit();
                lock.release();
            } catch (Throwable ex) {
                ex.printStackTrace();
                t2_ex = ex;
            } finally {
                lock.release();
            }
        }
    };

    // Let the game start
    t1.start();
    t2.start();

    // Wait for thread to die but put an insurance of 5 seconds on it.
    t1.join();
    t2.join();
    if (t1_ex != null) {
        fail("Thread1 failed: " + t1_ex);
    }
    if (t2_ex != null) {
        fail("Thread2 failed: " + t2_ex);
    }
}

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

/**
 * Should reproduce JBCACHE-32 problem//from  w  ww. j  a  v  a  2 s  .  co  m
 * (http://jira.jboss.com/jira/browse/JBCACHE-32)
 */
private void _testConcurrentCommits(int num_threads) {
    Object myMutex = new Object();

    Configuration conf1 = new Configuration();
    Configuration conf2 = new Configuration();
    conf1.setClusterName("TempCluster");
    conf2.setClusterName("TempCluster");
    conf1.setCacheMode(Configuration.CacheMode.REPL_SYNC);
    conf2.setCacheMode(Configuration.CacheMode.REPL_SYNC);
    conf1.setSyncCommitPhase(true);
    conf2.setSyncCommitPhase(true);
    conf1.setSyncRollbackPhase(true);
    conf2.setSyncRollbackPhase(true);
    conf1.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
    conf2.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
    conf1.setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
    conf2.setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
    conf1.setLockAcquisitionTimeout(5000);
    conf2.setLockAcquisitionTimeout(5000);

    final CacheSPI<Object, Object> c1 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>()
            .createCache(conf1, false, getClass());
    final CacheSPI<Object, Object> c2 = (CacheSPI<Object, Object>) new UnitTestCacheFactory<Object, Object>()
            .createCache(conf2, false, getClass());

    c1.start();
    c2.start();
    final List<Exception> exceptions = new ArrayList<Exception>();

    class MyThread extends Thread {
        final Object mutex;

        public MyThread(String name, Object mutex) {
            super(name);
            this.mutex = mutex;
        }

        public void run() {
            TransactionManager tm = null;

            try {
                tm = beginTransaction(c1);
                c1.put("/thread/" + getName(), null);
                //OPWAIT synchronized (mutex) {
                //OPWAIT   mutex.wait();
                //OPWAIT }
                tm.commit();
            } catch (Exception e) {
                exceptions.add(e);
            } finally {
                try {
                    if (tm != null)
                        tm.rollback();
                } catch (Exception e) {
                    // do nothing
                }
            }
        }
    }

    MyThread[] threads = new MyThread[num_threads];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new MyThread("t" + (i + 1), myMutex);
    }
    for (int i = 0; i < threads.length; i++) {
        MyThread thread = threads[i];
        thread.start();
    }

    try {
        Thread.sleep(6000);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    //OPWAIT synchronized (myMutex) {
    //OPWAIT   myMutex.notifyAll();
    //OPWAIT }

    for (MyThread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    assertEquals(0, c1.getNumberOfLocksHeld());
    assertEquals(0, c2.getNumberOfLocksHeld());

    c1.stop();
    c2.stop();

    // if(ex != null)
    // {
    // ex.printStackTrace();
    // fail("Thread failed: " + ex);
    // }

    // we can only expect 1 thread to succeed. The others will fail. So,
    // threads.length -1 exceptions.
    // this is a timing issue - 2 threads still may succeed on a multi cpu
    // system
    // assertEquals(threads.length - 1, exceptions.size());

    for (Exception exception : exceptions)
        assertEquals(TimeoutException.class, exception.getClass());
}

From source file:edu.illinois.enforcemop.examples.jbosscache.PessimisticSyncReplTxTest.java

/**
 * Test for JBCACHE-361 -- does marking a tx on the remote side rollback-only
 * cause a rollback on the originating side?
 *///ww  w. ja  va2 s .c  o  m
public void testSyncReplWithRemoteRollback() throws Exception {
    TransactionManager tm;
    final Fqn NODE1 = Fqn.fromString("/one/two/three");

    cache1.getConfiguration().setSyncRollbackPhase(true);
    cache2.getConfiguration().setSyncRollbackPhase(true);

    // Test with a rollback on the remote side

    // listener aborts any active tx
    // TransactionAborterListener tal = new TransactionAborterListener(cache2);

    tm = beginTransaction();
    cache1.put(NODE1, "age", 38);

    // instead of a listener lets just get a WL on ROOT on cache2. And hold on
    // to it.
    Transaction tx = tm.suspend();

    tm.begin();
    cache2.getRoot().put("x", "y");
    Transaction tx2 = cache2.getTransactionManager().suspend();

    tm.resume(tx);

    try {
        tm.commit();
        fail("commit should throw a RollbackException, we should not get here");
    } catch (RollbackException rollback) {
    } finally {
        tm.resume(tx2);
        tm.rollback();
    }

    // Sleep, as the commit call to cache2 is async
    Thread.sleep(1000);

    // assertNull(tal.getCallbackException());

    assertEquals(0, cache1.getNumberOfLocksHeld());
    assertEquals(0, cache2.getNumberOfLocksHeld());

    assertEquals(0, cache1.getNumberOfNodes());
    assertEquals(0, cache2.getNumberOfNodes());

}

From source file:org.apache.ode.scheduler.simple.SimpleScheduler.java

public <T> T execTransaction(Callable<T> transaction, int timeout) throws Exception, ContextException {
    TransactionManager txm = _txm;
    if (txm == null) {
        throw new ContextException("Cannot locate the transaction manager; the server might be shutting down.");
    }/*from   w ww  . j av  a 2  s.  c  o m*/

    // 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 = false;
    try {
        existingTransaction = txm.getTransaction() != null;
    } catch (Exception ex) {
        String errmsg = "Internal Error, could not get current transaction.";
        throw new ContextException(errmsg, ex);
    }

    // already in transaction, execute and return directly
    if (existingTransaction) {
        return transaction.call();
    }

    // run in new transaction
    Exception ex = null;
    int immediateRetryCount = _immediateTransactionRetryLimit;

    _txm.setTransactionTimeout(timeout);
    if (__log.isDebugEnabled() && timeout != 0)
        __log.debug("Custom transaction timeout: " + timeout);
    try {
        do {
            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 ContextException(errmsg, e);
            }

            try {
                ex = null;
                return transaction.call();
            } catch (Exception e) {
                ex = e;
            } finally {
                if (ex == null) {
                    if (__log.isDebugEnabled())
                        __log.debug("Commiting 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 " + _txm + " for error: ", ex);
                    Thread.sleep(_immediateTransactionRetryInterval);
                }
            }
        } while (immediateRetryCount-- > 0);
    } finally {
        // 0 restores the default value
        _txm.setTransactionTimeout(0);
    }

    throw ex;
}

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  ww w. j a v  a  2  s  . com*/
        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.openejb.transaction.TxRequired.java

public InvocationResult invoke(Interceptor interceptor, EjbInvocation ejbInvocation,
        TransactionManager transactionManager) throws Throwable {
    Transaction transaction = transactionManager.getTransaction();
    if (transaction != null) {
        try {//from  w ww  .ja v a 2 s  . 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  .  j a v  a 2  s .com*/
        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.
 *//*  w  w w. j ava2 s.  co 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 ww . j ava 2  s.com
 *
 * 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.seasar.s2click.test.S2ClickServiceTestCase.java

protected void doRunTest() throws Throwable {
    TransactionManager tm = null;
    if (needTransaction()) {
        try {/*from w  w  w.  ja va2 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();
        }
    }
}