Search in sources :

Example 66 with Transaction

use of javax.transaction.Transaction in project tomee by apache.

the class EntityManagerFactoryCallable method call.

@Override
public EntityManagerFactory call() throws Exception {
    final ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(appClassLoader);
    try {
        final Class<?> clazz = appClassLoader.loadClass(persistenceProviderClassName);
        final PersistenceProvider persistenceProvider = (PersistenceProvider) clazz.newInstance();
        // Create entity manager factories with the validator factory
        final Map<String, Object> properties = new HashMap<String, Object>();
        if (!ValidationMode.NONE.equals(unitInfo.getValidationMode())) {
            properties.put("javax.persistence.validation.factory", new ValidatorFactoryWrapper(potentialValidators));
        }
        if (cdi && "true".equalsIgnoreCase(unitInfo.getProperties().getProperty("tomee.jpa.cdi", "true")) && "true".equalsIgnoreCase(SystemInstance.get().getProperty("tomee.jpa.cdi", "true"))) {
            properties.put("javax.persistence.bean.manager", Proxy.newProxyInstance(appClassLoader, new Class<?>[] { BeanManager.class }, new BmHandler()));
        }
        customizeProperties(properties);
        // ensure no tx is there cause a managed connection would fail if the provider setAutocCommit(true) and some hib* have this good idea
        final Transaction transaction;
        if (unitInfo.isLazilyInitialized()) {
            transaction = OpenEJB.getTransactionManager().suspend();
        } else {
            transaction = null;
        }
        final EntityManagerFactory emf;
        try {
            emf = persistenceProvider.createContainerEntityManagerFactory(unitInfo, properties);
        } finally {
            if (unitInfo.isLazilyInitialized() && transaction != null) {
                OpenEJB.getTransactionManager().resume(transaction);
            }
        }
        if (unitInfo.getProperties() != null && "true".equalsIgnoreCase(unitInfo.getProperties().getProperty(OPENEJB_JPA_INIT_ENTITYMANAGER)) || SystemInstance.get().getOptions().get(OPENEJB_JPA_INIT_ENTITYMANAGER, false)) {
            emf.createEntityManager().close();
        }
        if (unitInfo.getNonJtaDataSource() != null) {
            final ImportSql importer = new ImportSql(appClassLoader, unitInfo.getPersistenceUnitName(), unitInfo.getNonJtaDataSource());
            if (importer.hasSomethingToImport()) {
                // to let OpenJPA create the database if configured this way
                emf.createEntityManager().close();
                importer.doImport();
            }
        }
        return emf;
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : HashMap(java.util.HashMap) PersistenceProvider(javax.persistence.spi.PersistenceProvider) Transaction(javax.transaction.Transaction) EntityManagerFactory(javax.persistence.EntityManagerFactory) InjectableBeanManager(org.apache.webbeans.container.InjectableBeanManager) BeanManager(javax.enterprise.inject.spi.BeanManager)

Example 67 with Transaction

use of javax.transaction.Transaction in project tomee by apache.

the class StatefulContainer method getTransaction.

private Transaction getTransaction(final ThreadContext callContext) {
    final TransactionPolicy policy = callContext.getTransactionPolicy();
    Transaction currentTransaction = null;
    if (policy instanceof JtaTransactionPolicy) {
        final JtaTransactionPolicy jtaPolicy = (JtaTransactionPolicy) policy;
        currentTransaction = jtaPolicy.getCurrentTransaction();
    }
    return currentTransaction;
}
Also used : Transaction(javax.transaction.Transaction) SuspendedTransaction(org.apache.openejb.core.transaction.BeanTransactionPolicy.SuspendedTransaction) EjbUserTransaction(org.apache.openejb.core.transaction.EjbUserTransaction) JtaTransactionPolicy(org.apache.openejb.core.transaction.JtaTransactionPolicy) JtaTransactionPolicy(org.apache.openejb.core.transaction.JtaTransactionPolicy) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) BeanTransactionPolicy(org.apache.openejb.core.transaction.BeanTransactionPolicy)

Example 68 with Transaction

use of javax.transaction.Transaction in project tomee by apache.

the class StatefulContainer method obtainInstance.

@SuppressWarnings("LockAcquiredButNotSafelyReleased")
private Instance obtainInstance(final Object primaryKey, final ThreadContext callContext, final Method callMethod, final boolean checkOutIfNecessary) throws OpenEJBException {
    if (primaryKey == null) {
        throw new SystemException(new NullPointerException("Cannot obtain an instance of the stateful session bean with a null session id"));
    }
    final Transaction currentTransaction = getTransaction(callContext);
    // Find the instance
    Instance instance;
    synchronized (this) {
        instance = checkedOutInstances.get(primaryKey);
        if (instance == null) {
            // no need to check for extended persistence contexts it shouldn't happen
            try {
                instance = cache.checkOut(primaryKey, checkOutIfNecessary);
            } catch (final OpenEJBException e) {
                throw e;
            } catch (final Exception e) {
                throw new SystemException("Unexpected load exception", e);
            }
            // Did we find the instance?
            if (instance == null) {
                throw new InvalidateReferenceException(new NoSuchObjectException("Not Found"));
            }
            // remember instance until it is returned to the cache
            checkedOutInstances.put(primaryKey, instance);
        }
    }
    final Duration accessTimeout = getAccessTimeout(instance.beanContext, callMethod);
    final LockFactory.StatefulLock currLock = instance.getLock();
    final boolean lockAcquired;
    if (accessTimeout == null || accessTimeout.getTime() < 0) {
        // wait indefinitely for a lock
        currLock.lock();
        lockAcquired = true;
    } else if (accessTimeout.getTime() == 0) {
        // concurrent calls are not allowed, lock only once
        lockAcquired = currLock.tryLock();
    } else {
        // try to get a lock within the specified period.
        try {
            lockAcquired = currLock.tryLock(accessTimeout.getTime(), accessTimeout.getUnit());
        } catch (final InterruptedException e) {
            throw new ApplicationException("Unable to get lock.", e);
        }
    }
    // Did we acquire the lock to the current execution?
    if (!lockAcquired) {
        throw new ApplicationException(new ConcurrentAccessTimeoutException("Unable to get lock."));
    }
    if (instance.getTransaction() != null) {
        if (!instance.getTransaction().equals(currentTransaction) && !instance.getLock().tryLock()) {
            throw new ApplicationException(new RemoteException("Instance is in a transaction and cannot be invoked outside that transaction.  See EJB 3.0 Section 4.4.4"));
        }
    } else {
        instance.setTransaction(currentTransaction);
    }
    // Mark the instance in use so we can detect reentrant calls
    instance.setInUse(true);
    return instance;
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) SystemInstance(org.apache.openejb.loader.SystemInstance) Duration(org.apache.openejb.util.Duration) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) InvalidateReferenceException(org.apache.openejb.InvalidateReferenceException) EJBAccessException(javax.ejb.EJBAccessException) RemoveException(javax.ejb.RemoveException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) OpenEJBException(org.apache.openejb.OpenEJBException) RemoteException(java.rmi.RemoteException) EJBException(javax.ejb.EJBException) SystemException(org.apache.openejb.SystemException) NoSuchObjectException(java.rmi.NoSuchObjectException) EntityManagerAlreadyRegisteredException(org.apache.openejb.persistence.EntityManagerAlreadyRegisteredException) ApplicationException(org.apache.openejb.ApplicationException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) InvalidateReferenceException(org.apache.openejb.InvalidateReferenceException) ApplicationException(org.apache.openejb.ApplicationException) SystemException(org.apache.openejb.SystemException) Transaction(javax.transaction.Transaction) SuspendedTransaction(org.apache.openejb.core.transaction.BeanTransactionPolicy.SuspendedTransaction) EjbUserTransaction(org.apache.openejb.core.transaction.EjbUserTransaction) NoSuchObjectException(java.rmi.NoSuchObjectException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) RemoteException(java.rmi.RemoteException)

Example 69 with Transaction

use of javax.transaction.Transaction in project hibernate-orm by hibernate.

the class DdlInWildFlyUsingBmtAndEmfTest method testCreateThenDrop.

@Test
public void testCreateThenDrop() throws Exception {
    URL persistenceXmlUrl = Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML_RESOURCE_NAME);
    if (persistenceXmlUrl == null) {
        persistenceXmlUrl = Thread.currentThread().getContextClassLoader().getResource('/' + PERSISTENCE_XML_RESOURCE_NAME);
    }
    assertNotNull(persistenceXmlUrl);
    ParsedPersistenceXmlDescriptor persistenceUnit = PersistenceXmlParser.locateIndividualPersistenceUnit(persistenceXmlUrl);
    // creating the EMF causes SchemaCreator to be run...
    EntityManagerFactory emf = Bootstrap.getEntityManagerFactoryBuilder(persistenceUnit, Collections.emptyMap()).build();
    // closing the EMF causes the delayed SchemaDropper to be run...
    //		wrap in a transaction just to see if we can get this to fail in the way the WF report says;
    //		in my experience however this succeeds with or without the transaction
    final TransactionManager tm = emf.unwrap(SessionFactoryImplementor.class).getServiceRegistry().getService(JtaPlatform.class).retrieveTransactionManager();
    tm.begin();
    Transaction txn = tm.getTransaction();
    emf.close();
    txn.commit();
}
Also used : ParsedPersistenceXmlDescriptor(org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor) JBossAppServerJtaPlatform(org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform) JtaPlatform(org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform) Transaction(javax.transaction.Transaction) TransactionManager(javax.transaction.TransactionManager) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityManagerFactory(javax.persistence.EntityManagerFactory) URL(java.net.URL) Test(org.junit.Test)

Example 70 with Transaction

use of javax.transaction.Transaction in project hibernate-orm by hibernate.

the class DualNodeJtaTransactionManagerImpl method commit.

public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
    Transaction tx = getCurrentTransaction();
    if (tx == null) {
        throw new IllegalStateException("no current transaction to commit");
    }
    tx.commit();
}
Also used : Transaction(javax.transaction.Transaction)

Aggregations

Transaction (javax.transaction.Transaction)160 SystemException (javax.transaction.SystemException)55 Test (org.junit.Test)42 RollbackException (javax.transaction.RollbackException)26 TransactionManager (javax.transaction.TransactionManager)24 UserTransaction (javax.transaction.UserTransaction)19 NotInTransactionException (org.neo4j.graphdb.NotInTransactionException)14 NotSupportedException (javax.transaction.NotSupportedException)13 Synchronization (javax.transaction.Synchronization)10 XAResource (javax.transaction.xa.XAResource)10 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)10 HazelcastXAResource (com.hazelcast.transaction.HazelcastXAResource)8 InvalidTransactionException (javax.transaction.InvalidTransactionException)7 TransactionContext (com.hazelcast.transaction.TransactionContext)6 RemoteException (java.rmi.RemoteException)6 ResourceException (javax.resource.ResourceException)6 ManagedConnection (javax.resource.spi.ManagedConnection)6 SQLException (java.sql.SQLException)5 HeuristicMixedException (javax.transaction.HeuristicMixedException)5 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)5