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:com.eucalyptus.images.Images.java

public static void enableImage(String imageId) throws NoSuchImageException {
    final EntityTransaction db = Entities.get(ImageInfo.class);
    try {//from  ww  w  .ja va2  s  .  c  o m
        final ImageInfo img = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        img.setState(ImageMetadata.State.available);
        db.commit();
    } catch (final NoSuchElementException e) {
        db.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, e);
    } catch (final Exception e) {
        db.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, e);
    } finally {
        if (db.isActive())
            db.rollback();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java

/**
 * Register a new application.//from  w w w  . jav a  2s  .  c o  m
 *
 * @param application The application to register
 * @return The registered application
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Application createApplication(final Application application) {
    if (application.getInfrastructureIds() == null || application.getInfrastructureIds().isEmpty()) {
        throw new BadRequestException();
    }
    Date now = new Date();
    application.setDateCreated(now);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        List<Infrastructure> lstInfra = new LinkedList<>();
        for (String infraId : application.getInfrastructureIds()) {
            Infrastructure infra = em.find(Infrastructure.class, infraId);
            if (infra == null) {
                throw new BadRequestException();
            }
            lstInfra.add(infra);
        }
        application.setInfrastructures(lstInfra);
        em.persist(application);
        et.commit();
        log.debug("New application registered: " + application.getId());
    } catch (BadRequestException re) {
        throw re;
    } catch (RuntimeException re) {
        log.error("Impossible to create the application");
        log.error(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return application;
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void rollback() {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }//from   w  ww. ja  va  2s.c  om

    // commit transaction
    EntityTransaction transaction = entityManager.getTransaction();
    if (transaction.isActive()) {
        transaction.rollback();
    }
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void begin() {
    // validate entity manager transaction
    if (entityManager != null) {
        throw new IllegalStateException("Transaction already initiated");
    }/*from   w w w .  ja v  a2 s.c  o  m*/

    // create entity manager and start transaction
    entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    if (!transaction.isActive()) {
        transaction.begin();
    }
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void close() {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }/*from   w  ww .  jav a 2  s  .co m*/

    // rollback transaction and close entity manager
    EntityTransaction transaction = entityManager.getTransaction();
    if (transaction.isActive()) {
        transaction.rollback();
    }
    entityManager.clear();
    entityManager.close();
    entityManager = null;
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

public void commit() throws PersistenceCommitException {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }//from   ww  w. ja v a 2 s .c o  m

    // commit transaction
    EntityTransaction transaction = entityManager.getTransaction();
    if (transaction.isActive()) {
        try {
            transaction.commit();
        } catch (RollbackException re) {
            throw new PersistenceCommitException("Transaction commit exception: " + re, re);
        } catch (OptimisticLockException ole) {
            throw new PersistenceCommitException("Transaction locking/version commit exception: " + ole, ole);
        }
    }
}

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

/**
* @return the userId that came in on the request providing the user has
 * a publishing account in jUDDI./*  w  w w  . ja va  2  s.  c o m*/
* @param authorizedName
* @param credential
* @return authorizedName
* @throws AuthenticationException 
*/
public String authenticate(String authorizedName, String credential) throws AuthenticationException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!");
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! " + authorizedName, ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null) {
            log.warn("Publisher \"" + authorizedName + "\" was not found, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(authorizedName);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }
        return authorizedName;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 */// w  w  w  .  j a  v  a  2 s  . co  m
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public void deleteTheme(long id) throws ThemesServiceDatabaseException, NotFoundException {
    EntityManager em = null;/* w  ww .java 2 s.c o  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        ThemeDto themeDto = getThemeDto(id, em);
        if (themeDto == null)
            throw new NotFoundException("No theme with id=" + id + " exists");

        tx = em.getTransaction();
        tx.begin();
        em.remove(themeDto);
        tx.commit();
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.delete(id));
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete theme '{}': {}", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

/**
 * Finalize any operation which affected the EntityManager. This method has
 * the following tasks:// ww w.j ava2 s  .c o  m
 *
 * <ul>
 * <li>Commit the provided transaction</li>
 * <li>If the commit fails, rollback the transaction</li>
 * <li>Clear the cache of the EntityManager (make all entities
 * unmanaged)</li>
 * </ul>
 *
 * If no transaction is provided (after an operation which did not affect
 * the data backend, e.g. find()), only the cache is cleared.
 *
 * @param <T> Generic entity type.
 * @param methodName Description of the method which was performed (for
 * debugging).
 * @param transaction The transaction to finalize.
 * @param entity Affected entity or entity class (for debugging).
 */
private <T> void finalizeEntityManagerAccess(String methodName, EntityTransaction transaction, T entity) {
    if (transaction != null) {
        try {
            LOGGER.debug("Flushing entityManager");
            entityManager.flush();
            LOGGER.debug("Committing current transaction");
            transaction.commit();
        } catch (Exception e) {
            LOGGER.warn("Failed to commit transaction for operation '" + methodName + "'", e);
        } finally {
            if (transaction.isActive()) {
                LOGGER.debug("Transaction is still active. Performing rollback.");
                transaction.rollback();
                LOGGER.error("Method '" + methodName + "' fails for entity/class '" + entity + "'");
            }
            LOGGER.debug("Clearing entityManager cache");
            entityManager.clear();
            LOGGER.debug("Cache cleared.");
        }
    } else {
        LOGGER.debug("Clearing entityManager cache");
        entityManager.clear();
        LOGGER.debug("Cache cleared.");
    }
}