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.api.impl.JUDDIApiImpl.java

/**
 * Saves nodes(s) to the persistence layer. This method is specific to
 * jUDDI. Administrative privilege required. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body//from  w w  w .ja v a  2 s.c o  m
 * @return NodeDetail
 * @throws DispositionReportFaultMessage 
 */
public NodeDetail saveNode(SaveNode body) throws DispositionReportFaultMessage {

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

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateNode(publisher).validateSaveNode(em, body);

        NodeDetail result = new NodeDetail();

        List<org.apache.juddi.api_v3.Node> apiNodeList = body.getNode();
        ;
        for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) {

            org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node();

            MappingApiToModel.mapNode(apiNode, modelNode);

            Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName());
            if (existingUddiEntity != null) {
                em.merge(modelNode);
            } else {
                em.persist(modelNode);
            }

            result.getNode().add(apiNode);
        }

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

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

/**
 * Saves clerk(s) to the persistence layer. This method is specific to
 * jUDDI. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body/*w ww.  j a v  a 2  s .c  o  m*/
 * @return ClerkDetail
 * @throws DispositionReportFaultMessage 
 */
public ClerkDetail saveClerk(SaveClerk body) throws DispositionReportFaultMessage {

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

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClerk(publisher).validateSaveClerk(em, body);

        ClerkDetail result = new ClerkDetail();

        List<org.apache.juddi.api_v3.Clerk> apiClerkList = body.getClerk();
        ;
        for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) {

            org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk();

            MappingApiToModel.mapClerk(apiClerk, modelClerk);

            Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName());
            if (existingUddiEntity != null) {
                em.merge(modelClerk);
            } else {
                em.persist(modelClerk);
            }

            result.getClerk().add(apiClerk);
        }

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

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}//  w  w  w  . j av  a2s . com
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String)
 */
@Override
public String getOrganizationId(String mediaPackageId)
        throws NotFoundException, SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity searchEntity = getSearchEntity(mediaPackageId, em);
        if (searchEntity == null)
            throw new NotFoundException("No media package with id=" + mediaPackageId + " exists");
        // Ensure this user is allowed to read this media package
        String accessControlXml = searchEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getOrganization();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

public TModelDetail getTModelDetail(GetTModelDetail body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    try {//from w ww .  ja va 2s .c o  m
        new ValidateInquiry(null).validateGetTModelDetail(body);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime);
        throw drfm;
    }

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

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

        TModelDetail result = new TModelDetail();

        List<String> tmodelKeyList = body.getTModelKey();
        for (String tmodelKey : tmodelKeyList) {
            org.apache.juddi.model.Tmodel modelTModel = null;
            try {
                modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
            } catch (ClassCastException e) {
            }
            if (modelTModel == null)
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey));

            org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel();

            MappingModelToApi.mapTModel(modelTModel, apiTModel);

            result.getTModel().add(apiTModel);
        }

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

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

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}//from ww  w .jav  a 2  s. c o m
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getModificationDate(String)
 */
@Override
public Date getModificationDate(String mediaPackageId)
        throws NotFoundException, SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity searchEntity = getSearchEntity(mediaPackageId, em);
        if (searchEntity == null)
            throw new NotFoundException("No media package with id=" + mediaPackageId + " exists");
        // Ensure this user is allowed to read this media package
        String accessControlXml = searchEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getModificationDate();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get modification date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body//from w ww .jav  a2 s .c o m
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

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

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateSavePublisher(em, body);

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

From source file:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}/*from w  w  w . j  a v  a2 s. c  o  m*/
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getDeletionDate(String)
 */
@Override
public Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity searchEntity = getSearchEntity(mediaPackageId, em);
        if (searchEntity == null) {
            throw new NotFoundException("No media package with id=" + mediaPackageId + " exists");
        }
        // Ensure this user is allowed to read this media package
        String accessControlXml = searchEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()))
                throw new UnauthorizedException(
                        currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getDeletionDate();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

/** Checks wether an user, given his username and password, is allowed to use the system.
 *
 * @param username String representing the username.
 * @param password String representing the password.
 *
 * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null).
 *//* ww  w . j  a  v a 2s  . c  o  m*/
@Override
public Principal authenticate(String username, String password) {

    String encpw = null;
    try {
        encpw = KBCrypter.encryptText(password);
    } catch (Exception ex) {
        log.error("error encrypting password: ", ex);
    }
    Object identity = null;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em
                    .createQuery("from User u where " + "u.timeout > :nu "
                            + "and lower(u.username) = lower(:username) " + "and u.password = :password")
                    .setParameter("nu", new Date()).setParameter("username", username)
                    .setParameter("password", encpw).getSingleResult();
            // if we get a result, this means successful login
            // set lastloginstatus to null to indicate success
            user.setLastLoginStatus(null);

            return user;
        } catch (NoResultException nre) {
            log.debug("No results using encrypted password");
        }
        // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW
        User wrong_password_user = (User) em
                .createQuery(
                        "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ")
                .setParameter("nu", new Date()).setParameter("username", username).getSingleResult();
        wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED);
        em.flush();
        log.warn("Login failure for username " + username);
    } catch (Exception e) {
        log.error("Exception checking user credentails", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }

    return null;
}

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

/**
 * Retrieves publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required. 
 * @param body/*from ww w  .j a  v a 2s . co m*/
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage 
 */
public PublisherDetail getPublisherDetail(GetPublisherDetail body) throws DispositionReportFaultMessage {

    new ValidatePublisher(null).validateGetPublisherDetail(body);

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

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

        PublisherDetail result = new PublisherDetail();

        List<String> publisherIdList = body.getPublisherId();
        for (String publisherId : publisherIdList) {
            org.apache.juddi.model.Publisher modelPublisher = null;
            try {
                modelPublisher = em.find(org.apache.juddi.model.Publisher.class, publisherId);
            } catch (ClassCastException e) {
            }
            if (modelPublisher == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.PublisherNotFound", publisherId));
            }

            org.apache.juddi.api_v3.Publisher apiPublisher = new org.apache.juddi.api_v3.Publisher();

            MappingModelToApi.mapPublisher(modelPublisher, apiPublisher);

            result.getPublisher().add(apiPublisher);
        }

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

}

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

public void deleteBusiness(DeleteBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  ww. j a  v a2s .  com*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateDeleteBusiness(em, body);

        List<String> entityKeyList = body.getBusinessKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey);
            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}