Example usage for javax.persistence EntityTransaction rollback

List of usage examples for javax.persistence EntityTransaction rollback

Introduction

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

Prototype

public void rollback();

Source Link

Document

Roll back the current resource transaction.

Usage

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

/**
 * Adds client subscription information. This effectively links a server to
 * serverr subscription to clerk/*  w w w .j  a  va 2s  .  c o  m*/
 * Administrative privilege required.
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body);

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<org.apache.juddi.api_v3.ClientSubscriptionInfo> apiClientSubscriptionInfoList = body
                .getClientSubscriptionInfo();
        for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo();

            MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo);

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

            em.persist(modelClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * handle the update and save process.//from  www . ja  va  2s  .c om
 *
 * @param entity the newsdrilldown entity
 * @throws Exception the exception
 */
private void handle(UXBEntity entity) throws Exception {
    /**
     * Due to a hibernate problem when updating or saving a newsdrilldown with
     * related categories we have to perform these step for saving the newsdrilldown
     *
     * 1. save/update all categories and remove them from the newsdrilldown
     *    1.1 save/update all metaCategories and remove them from the categories
     *    1.2 save the categories
     *    1.3 read all metaCategories to the categories
     *    1.4 save the categories again to create the relations
     * 2. save the newsdrilldown
     * 3. read all categories to the newsdrilldown
     */

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        News news = buildNews(entity);
        List<Long> categories = new ArrayList<Long>();

        /*
        * 1. update or save all categories
        * Steps 1.1 - 1.4
        */
        if (news.getCategories() != null && !news.getCategories().isEmpty()) {
            for (NewsCategory cat : news.getCategories()) {
                cat = saveNewsCategory(cat);
                if (!categories.contains(cat.getFs_id())) {
                    categories.add(cat.getFs_id());
                }
            }
            news.setCategories(new ArrayList<NewsCategory>());
        }

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

        // 2. save the newsdrilldown
        news = saveNews(news, em);

        // 3. read all categories to the newsdrilldown
        if (!categories.isEmpty()) {
            for (Long cat : categories) {
                NewsCategory ncat = getNewsCategory(cat, news.getLanguage(), em);
                news.getCategories().add(ncat);
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

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

public void deletePublisherAssertions(DeletePublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from   w  w  w . ja  v a  2 s . com
        tx.begin();

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

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

        List<org.uddi.api_v3.PublisherAssertion> entityList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion entity : entityList) {
            org.apache.juddi.model.PublisherAssertionId pubAssertionId = new org.apache.juddi.model.PublisherAssertionId(
                    entity.getFromKey(), entity.getToKey());
            Object obj = em.find(org.apache.juddi.model.PublisherAssertion.class, pubAssertionId);
            em.remove(obj);
        }

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

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

/**
 * {@inheritDoc}/*  ww  w. j a v  a 2 s .com*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#init(java.lang.String)
 */
@Override
public String init(final String dataSourceID) throws DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }

    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao dao = findDataSourceDao(em, dataSourceID);
            if (dao != null && dao.getSessionId() != null) {
                throw new DeltaIndexingException(
                        "data source " + dataSourceID + " is already locked by another session");
            }

            final String sessionId = UUID.randomUUID().toString();

            final DataSourceDao lockedDao = new DataSourceDao(dataSourceID, sessionId);
            // lock the data source
            if (dao == null) {
                em.persist(lockedDao);
            } else {
                em.merge(lockedDao);
            }

            // reset visited and modified flags
            resetFlags(em, dataSourceID);

            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("created session " + sessionId + " for data source: " + dataSourceID);
            }
            return sessionId;
        } catch (final DeltaIndexingException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error initializing delta indexing for data source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an AnnotationStatus that specifies another AnnotationStatus
 * @param label/*from   w  ww .jav a2s  .co  m*/
 * @param comment
 * @param father
 * @return
 */
public boolean createAnnotationStatusChild(String label, String comment, String color, AnnotationStatus father,
        JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setFather(father);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (father.getId() != null) {
                AnnotationStatus _synchro_father = em.find(AnnotationStatus.class, father.getId());
                if (_synchro_father != null)
                    _as.setFather(_synchro_father);
            }
            em.persist(_as);
            tx.commit();
            //      em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

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

public TModelDetail saveTModel(SaveTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w w w  .  j  ava  2  s . c o m
        tx.begin();

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

        new ValidatePublish(publisher).validateSaveTModel(em, body, null);

        TModelDetail result = new TModelDetail();

        List<org.uddi.api_v3.TModel> apiTModelList = body.getTModel();
        for (org.uddi.api_v3.TModel apiTModel : apiTModelList) {

            org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();

            MappingApiToModel.mapTModel(apiTModel, modelTModel);

            setOperationalInfo(em, modelTModel, publisher);

            em.persist(modelTModel);

            result.getTModel().add(apiTModel);

        }

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

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

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

public void transferEntities(TransferEntities body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from  w w w  .  j  a  v  a2  s  .c o  m*/
        tx.begin();

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

        new ValidateCustodyTransfer(publisher).validateTransferEntities(em, body);

        // Once validated, the ownership transfer is as simple as switching the publisher
        KeyBag keyBag = body.getKeyBag();
        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            UddiEntity uddiEntity = em.find(UddiEntity.class, key);
            uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

            if (uddiEntity instanceof BusinessEntity) {
                BusinessEntity be = (BusinessEntity) uddiEntity;

                List<BusinessService> bsList = be.getBusinessServices();
                for (BusinessService bs : bsList) {
                    bs.setAuthorizedName(publisher.getAuthorizedName());

                    List<BindingTemplate> btList = bs.getBindingTemplates();
                    for (BindingTemplate bt : btList)
                        bt.setAuthorizedName(publisher.getAuthorizedName());
                }
            }
        }

        // After transfer is finished, the token can be removed
        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        String transferTokenId = new String(apiTransferToken.getOpaqueToken());
        org.apache.juddi.model.TransferToken modelTransferToken = em
                .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
        em.remove(modelTransferToken);

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

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

}

From source file:com.eucalyptus.images.ImageManager.java

public ModifyImageAttributeResponseType modifyImageAttribute(final ModifyImageAttributeType request)
        throws EucalyptusCloudException {
    final ModifyImageAttributeResponseType reply = (ModifyImageAttributeResponseType) request.getReply();

    final EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//from  w w w. ja  v a  2 s .c  o  m
        final ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (!canModifyImage(imgInfo)) {
            throw new EucalyptusCloudException("Not authorized to modify image attribute");
        }

        switch (request.imageAttribute()) {
        case LaunchPermission:
            if (request.add()) {
                imgInfo.addPermissions(verifyUserIds(request.userIds()));
                if (request.groupAll()) {
                    imgInfo.setImagePublic(true);
                }
            } else {
                imgInfo.removePermissions(request.userIds());
                if (request.groupAll()) {
                    imgInfo.setImagePublic(false);
                }
            }
            break;
        case ProductCode:
            for (String productCode : request.getProductCodes()) {
                imgInfo.addProductCode(productCode);
            }
            break;
        case Description:
            imgInfo.setDescription(request.getDescription());
            break;
        }

        tx.commit();
        reply.set_return(true);
    } catch (EucalyptusCloudException e) {
        tx.rollback();
        reply.set_return(false);
        throw e;
    } catch (TransactionException | NoSuchElementException ex) {
        tx.rollback();
        throw new EucalyptusCloudException(ex);
    }

    return reply;
}

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

/**
 * {@inheritDoc}//from   www.  jav a2s . c  o m
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getMediaPackage(String)
 */
@Override
public MediaPackage getMediaPackage(String mediaPackageId)
        throws NotFoundException, SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity episodeEntity = getSearchEntity(mediaPackageId, em);
        if (episodeEntity == null)
            throw new NotFoundException("No episode with id=" + mediaPackageId + " exists");
        // Ensure this user is allowed to read this episode
        String accessControlXml = episodeEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            // There are several reasons a user may need to load a episode: to read content, to edit it, or add content
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())
                    && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, CONTRIBUTE.toString())
                    && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) {
                throw new UnauthorizedException(
                        currentUser + " is not authorized to see episode " + mediaPackageId);
            }
        }
        return MediaPackageParser.getFromXml(episodeEntity.getMediaPackageXML());
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get episode {} from database: {} ", 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.UDDIPublicationImpl.java

public void deleteBinding(DeleteBinding body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w  w w .j av  a 2s .  c o m
        tx.begin();

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

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

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

            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService()
                    .setModifiedIncludingChildren(new Date());
            // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

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