Example usage for javax.persistence EntityTransaction isActive

List of usage examples for javax.persistence EntityTransaction isActive

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction isActive.

Prototype

public boolean isActive();

Source Link

Document

Indicate whether a resource transaction is in progress.

Usage

From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName)
        throws AuthenticationException, FatalErrorException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*  w w w  .  j  a  va 2 s.  c  o  m*/
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.debux.webmotion.jpa.Transactional.java

/**
 * Create the transaction and the GenericDAO if the entity name is not 
 * empty or null./*  w w  w.j a va 2s .c  o m*/
 * 
 * @param request set EntityManager, EntityTransaction and GenericDAO into the request
 * @param persistenceUnitName precise the persistence unit
 * @param packageEntityName precise the package of entity
 * @param entityName precise the class name of the entity
 * 
 * @throws Exception catch execption to rollback the transaction
 */
public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties,
        String packageEntityName, String entityName) throws Exception {

    // Create factory
    if (persistenceUnitName == null || persistenceUnitName.isEmpty()) {
        persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME;
    }
    EntityManagerFactory factory = factories.get(persistenceUnitName);
    if (factory == null) {
        Configuration subset = properties.subset(persistenceUnitName);
        java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset);

        factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties);
        factories.put(persistenceUnitName, factory);
    }

    // Create manager
    EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER);
    if (manager == null) {
        manager = factory.createEntityManager();
        request.setAttribute(CURRENT_ENTITY_MANAGER, manager);
    }

    // Create generic DAO each time if callback an action on an other entity
    if (entityName != null) {
        String fullEntityName = null;
        if (packageEntityName != null && !packageEntityName.isEmpty()) {
            fullEntityName = packageEntityName + "." + entityName;
        } else {
            fullEntityName = entityName;
        }

        GenericDAO genericDAO = new GenericDAO(manager, fullEntityName);
        request.setAttribute(CURRENT_GENERIC_DAO, genericDAO);

    } else {
        request.setAttribute(CURRENT_GENERIC_DAO, null);
    }

    // Create transaction
    EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION);
    if (transaction == null) {
        transaction = manager.getTransaction();
        request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction);

        transaction.begin();

        try {
            doProcess();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        if (transaction.isActive()) {
            transaction.commit();
        }
        manager.close();

    } else {
        doProcess();
    }
}

From source file:org.apache.juddi.api.impl.UDDIv2PublishImpl.java

private String getUsername(String authinfo) {
    String user = "N/A";

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from www. j  a va2 s  .co m*/

        tx.begin();
        user = publishService.getEntityPublisher(em, authinfo).getAuthorizedName();
        tx.commit();
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return user;
}

From source file:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?//ww  w. j av a 2  s  .  c om
 */
public void close() {
    if (!nestedEm && em != null) {
        if (em.isOpen()) {
            try {
                List<JpaTransactionCallback> callbacks = getCallbacks();

                if (!isCallbacked()) {
                    for (JpaTransactionCallback callback : callbacks) {
                        if (m_log.isDebugEnabled()) {
                            m_log.debug("executing callback preClose : " + callback.getClass().getName());
                        }
                        try {
                            setCallbacked();

                            callback.preClose();
                        } catch (Throwable t) {
                            m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                        } finally {
                            unsetCallbacked();
                        }
                    }
                }

                // commit or rollback???close?????????(rollback)?
                // ???connection????????
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (m_log.isDebugEnabled()) {
                        StackTraceElement[] eList = Thread.currentThread().getStackTrace();
                        StringBuilder trace = new StringBuilder();
                        for (StackTraceElement e : eList) {
                            if (trace.length() > 0) {
                                trace.append("\n");
                            }
                            trace.append(String.format("%s.%s(%s:%d)", e.getClassName(), e.getMethodName(),
                                    e.getFileName(), e.getLineNumber()));
                        }
                        m_log.debug(
                                "closing uncompleted transaction. this transaction will be rollbacked before closing : "
                                        + trace);
                    }
                    tx.rollback();
                }

                em.close();
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);

                // postClose???innerTransaction????????callback???
                for (JpaTransactionCallback callback : callbacks) {
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("executing callback postClose : " + callback.getClass().getName());
                    }
                    try {
                        callback.postClose();
                    } catch (Throwable t) {
                        m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                    }
                }
            } finally {
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);
            }
        }
        HinemosSessionContext.instance().setProperty(EM, null);
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Deletes the subscription. i.e. when it is expired.
 * @param subscription/*from   w w  w  . j av  a2s.  c  o  m*/
 */
protected void deleteSubscription(Subscription subscription) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.remove(subscription);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public void delete(ODataUri uri, EntityDataModel entityDataModel) throws ODataException {
    Option<Object> entity = extractEntityWithKeys(uri, entityDataModel);

    if (entity.isDefined()) {
        Object jpaEntity = entityMapper.convertODataEntityToDS(entity.get(), entityDataModel);
        if (jpaEntity != null) {
            EntityManager entityManager = getEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();//www .j a va 2 s. c om

                Object attached = entityManager.merge(jpaEntity);
                entityManager.remove(attached);
            } catch (PersistenceException e) {
                LOG.error("Could not remove entity: {}", entity);
                throw new ODataDataSourceException("Could not remove entity", e);
            } finally {
                if (transaction.isActive()) {
                    transaction.commit();
                } else {
                    transaction.rollback();
                }
            }
        } else {
            throw new ODataDataSourceException("Could not remove entity, could not be loaded");
        }
    }
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * A utility class to load the user directory.
 * //  w w  w.j  a  v a 2s  .  c  o m
 * @param user
 *          the user object
 */
public void addUser(JpaUser user) {

    // Create a JPA user with an encoded password.
    String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles());

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(user);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * @see//from   ww w. j  a v a  2  s  .c o m
 * org.apache.james.user.lib.AbstractUsersRepository#doAddUser(java.lang.String, java.lang.String)
 */
protected void doAddUser(String username, String password) throws UsersRepositoryException {
    String lowerCasedUsername = username.toLowerCase();
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername, password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        getLogger().debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username, e);
    } finally {
        entityManager.close();
    }
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}// www.j a v  a  2 s .c om
 */
@Override
public void removeRecord(final String id) throws RecordStorageException {
    if (id == null) {
        throw new RecordStorageException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final RecordDao dao = findRecordDao(em, id);
            if (dao != null) {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    em.remove(dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new RecordStorageException(e, "error removing record id: " + id);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove record id: " + id + ". no record with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    Publisher publisher = null;//from w ww.  j  ava2  s .c  o  m
    try {
        tx.begin();
        publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));

        AuthToken at = em.find(AuthToken.class, authInfo);
        if (at == null)
            throw new AuthTokenRequiredException(new ErrorMessage("E_authTokenRequired", authInfo));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return publisher;
}