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.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization)
 *///from   w ww  .  ja  va2s  .  c o  m
@Override
public void storeOrganization(Organization org) throws OrganizationDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organizationEntity = getOrganizationEntity(org.getId());
        if (organizationEntity == null) {
            JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(),
                    org.getAdminRole(), org.getAnonymousRole(), org.getProperties());
            em.persist(organization);
        } else {
            organizationEntity.setName(org.getName());
            organizationEntity.setAdminRole(org.getAdminRole());
            organizationEntity.setAnonymousRole(org.getAnonymousRole());
            organizationEntity.setServers(org.getServers());
            organizationEntity.setProperties(org.getProperties());
            em.merge(organizationEntity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

/**
 * Deletes a news article from the db/*from  w w  w  .j a  v  a  2 s  . c  om*/
 *
 * @param entity The article to delete
 */
public void delete(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.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString());
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            Article art = (Article) query.getSingleResult();
            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.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

/**
  *//from   ww  w  .j a  va2 s. c  om
  */
public String authenticate(final String userID, final String credential) throws AuthenticationException {
    if (userID == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidUserId", userID));
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        // Create a principal for the userID
        Principal principal = new Principal() {
            public String getName() {
                return userID;
            }
        };

        if (!authManager.isValid(principal, credential)) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.InvalidCredentials"));
        } else {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, userID);
            if (publisher == null) {
                publisher = new Publisher();
                publisher.setAuthorizedName(userID);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(199);
                publisher.setMaxBusinesses(100);
                publisher.setMaxServicesPerBusiness(100);
                publisher.setMaxTmodels(100);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        }
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return userID;
}

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

public TModelList findTModel(FindTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {/*ww w.  j a va  2s  . co  m*/
        new ValidateInquiry(null).validateFindTModel(body, false);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findTModel(body, findQualifiers, em);

        TModelList result = InquiryHelper.getTModelListFromKeys(body, findQualifiers, em, keysFound);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.SUCCESS, procTime);

        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.sixsq.slipstream.run.RunNodeResource.java

private Representation addNodeInstancesInTransaction(Representation entity) throws Exception {

    EntityManager em = PersistenceUtil.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    Run run = Run.loadFromUuid(getUuid(), em);
    List<String> instanceNames = new ArrayList<String>();
    try {/* www. j  av  a  2  s. c om*/
        validateRun(run);

        transaction.begin();

        int noOfInst = getNumberOfInstancesToAdd(entity);

        Node node = getNode(run, nodename);
        for (int i = 0; i < noOfInst; i++) {
            instanceNames.add(createNodeInstanceOnRun(run, node));
        }

        run.postEventScaleUp(nodename, instanceNames, noOfInst);

        incrementNodeMultiplicityOnRun(noOfInst, run);
        StateMachine.createStateMachine(run).tryAdvanceToProvisionning();

        if (Configuration.isQuotaEnabled()) {
            User user = User.loadByName(run.getUser());
            Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName()));
        }

        transaction.commit();
    } catch (Exception ex) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw ex;
    } finally {
        em.close();
    }

    getResponse().setStatus(Status.SUCCESS_CREATED);
    return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN);
}

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

public BusinessList findBusiness(FindBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {// ww w  .j  a  v a  2s  . c o m
        new ValidateInquiry(null).validateFindBusiness(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    }

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        if (isAuthenticated())
            this.getEntityPublisher(em, body.getAuthInfo());

        org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
        findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());

        List<?> keysFound = InquiryHelper.findBusiness(body, findQualifiers, em);

        BusinessList result = InquiryHelper.getBusinessListFromKeys(body, findQualifiers, em, keysFound);

        tx.rollback();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.SUCCESS, procTime);

        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}//  www. ja va2 s  .c  o m
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#unlockDatasources()
 */
@Override
public void unlockDatasources() throws DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final Query query = em.createNamedQuery(DataSourceDao.NAMED_QUERY_KILL_ALL_SESSIONS);
            query.executeUpdate();
            transaction.commit();
            if (_log.isInfoEnabled()) {
                _log.info("removed all delta indexing sessions and unlocked all data sources");
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException("error unlocking delta indexing data sources", e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.opencastproject.userdirectory.JpaGroupRoleProvider.java

/**
 * Adds or updates a group to the persistence.
 *
 * @param group//w ww  .jav  a 2s .  c  o  m
 *          the group to add
 */
public void addGroup(final JpaGroup group) {
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf);

    JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(),
            roles, group.getMembers());

    // Then save the jpaGroup
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(),
                jpaGroup.getOrganization().getId(), emf);
        if (foundGroup == null) {
            em.persist(jpaGroup);
        } else {
            foundGroup.setName(jpaGroup.getName());
            foundGroup.setDescription(jpaGroup.getDescription());
            foundGroup.setMembers(jpaGroup.getMembers());
            foundGroup.setRoles(roles);
            em.merge(foundGroup);
        }
        tx.commit();
        messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue,
                GroupItem.update(JaxbGroup.fromGroup(jpaGroup)));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from  w  w  w  . j av  a 2 s.  c  o  m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#finish(String)
 */
@Override
public void finish(final String sessionId) throws DeltaIndexingSessionException, DeltaIndexingException {
    _lock.readLock().lock();
    try {
        final DataSourceDao dao = assertSession(sessionId);
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao unlockedDao = new DataSourceDao(dao.getDataSourceId(), null);
            em.merge(unlockedDao);
            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("finished session " + sessionId + " with data source: " + dao.getDataSourceId());
            }
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error finishing delta indexing for data source: " + dao.getDataSourceId(), e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:org.opencastproject.messages.MailService.java

public void deleteMessageTemplate(Long id) throws MailServiceException, NotFoundException {
    EntityManager em = null;//from   w  ww  . j  a  v a2s.  c om
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        Option<MessageTemplateDto> templateOption = findMessageTemplateById(id, orgId, em);
        if (templateOption.isNone())
            throw new NotFoundException();
        em.remove(templateOption.get());
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete message template '{}': {}", id, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}