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.UDDISubscriptionImpl.java

@SuppressWarnings("unchecked")
public List<Subscription> getSubscriptions(String authInfo) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*  ww  w .j  a  va  2  s.  c o m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<Subscription> result = new ArrayList<Subscription>(0);

        List<org.apache.juddi.model.Subscription> modelSubscriptionList = (List<org.apache.juddi.model.Subscription>) FindSubscriptionByPublisherQuery
                .select(em, publisher.getAuthorizedName());
        if (modelSubscriptionList != null && modelSubscriptionList.size() > 0) {
            for (org.apache.juddi.model.Subscription modelSubscription : modelSubscriptionList) {

                Subscription apiSubscription = new Subscription();

                MappingModelToApi.mapSubscription(modelSubscription, apiSubscription);

                result.add(apiSubscription);
            }
        }

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

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, 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 getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID,
        Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag);

        int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS;
        try {
            transferExpirationDays = AppConfig.getConfiguration()
                    .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS);
            // For output
            nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
        } catch (ConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
        }

        String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID();
        org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken();
        transferToken.setTransferToken(transferKey);
        // For output
        opaqueToken.value = transferKey.getBytes();

        GregorianCalendar gc = new GregorianCalendar();
        gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays);

        transferToken.setExpirationDate(gc.getTime());

        try {
            DatatypeFactory df = DatatypeFactory.newInstance();
            // For output
            expirationTime.value = df.newXMLGregorianCalendar(gc);
        } catch (DatatypeConfigurationException ce) {
            throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
        }

        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key);
            transferToken.getTransferKeys().add(tokenKey);
        }

        em.persist(transferToken);

        tx.commit();

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

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

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

public List<PublisherAssertion> getPublisherAssertions(String authInfo) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<org.uddi.api_v3.PublisherAssertion> result = new ArrayList<org.uddi.api_v3.PublisherAssertion>(0);

        List<?> businessKeysFound = null;
        businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);

        List<org.apache.juddi.model.PublisherAssertion> pubAssertionList = FindPublisherAssertionByBusinessQuery
                .select(em, businessKeysFound, null);
        if (pubAssertionList != null)
            for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) {
                org.uddi.api_v3.PublisherAssertion apiPubAssertion = new org.uddi.api_v3.PublisherAssertion();

                MappingModelToApi.mapPublisherAssertion(modelPubAssertion, apiPubAssertion);

                result.add(apiPubAssertion);
            }

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

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

public BusinessDetail saveBusiness(SaveBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business request for key " + body.getBusinessEntity().get(0).getBusinessKey());
    }//from   w  ww . j  a  v  a  2  s.co  m
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

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

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

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

private void deleteNodeInstancesInTransaction(Representation entity) throws Exception {
    EntityManager em = PersistenceUtil.createEntityManager();
    EntityTransaction transaction = em.getTransaction();

    Run run = Run.loadFromUuid(getUuid(), em);
    try {//from www.  j a  v  a  2 s. co m
        Form form = new Form(entity);
        boolean deleteOnly = "true".equals(form.getFirstValue(DELETE_INSTANCE_IDS_ONLY_FORM_PARAM, "").trim())
                ? true
                : false;
        if (!deleteOnly) {
            validateRun(run);
        }
        transaction.begin();

        String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, "");
        if (ids.isEmpty()) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                    "Provide list of node instance IDs to be removed from the Run.");
        } else {
            String cloudServiceName = "";
            try {
                cloudServiceName = run.getCloudServiceNameForNode(nodename);
            } catch (NullPointerException ex) {
                throwClientBadRequest("Invalid nodename: " + nodename);
            }
            List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*"));
            for (String _id : instanceIds) {
                String instanceName = "";
                try {
                    instanceName = getNodeInstanceName(Integer.parseInt(_id));
                } catch (NumberFormatException ex) {
                    throwClientBadRequest("Invalid instance name: " + _id);
                }
                setRemovingNodeInstance(run, instanceName);
                run.removeNodeInstanceName(instanceName, cloudServiceName);
            }
            run.postEventScaleDown(nodename, instanceIds);
            // update instance ids
            removeNodeInstanceIndices(run, instanceIds);
            decrementNodeMultiplicityOnRun(instanceIds.size(), run);
        }

        if (!deleteOnly) {
            StateMachine.createStateMachine(run).tryAdvanceToProvisionning();
        }

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

    getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
}

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

/**
 * Computes the number of annotations for associated to a specified Resource through its url
 * @param _url/*from  w  w  w  . jav a  2s . c o m*/
 * @return
 */
public long computeNbAnnotations(String _url) {
    long nb = 0;
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.computeNbAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return nb;
        }
        Object nb_annotations = em.createQuery(
                " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?")
                .setParameter(1, _uri).getSingleResult();
        //System.out.println("[RetrieveAnnotation.computeNbAnnotations] nb_annotations : " + nb_annotations + " classe : " + nb_annotations.getClass().getSimpleName());
        tx.commit();
        if (nb_annotations instanceof Long) {
            nb = ((Long) nb_annotations).longValue();
        }
        return nb;
    } catch (Exception e) {
        tx.rollback();
        return nb;
    }
}

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

@SuppressWarnings("unchecked")
public void discardTransferToken(DiscardTransferToken body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//w ww  .  ja  va2s.c  o  m
        tx.begin();

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

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

        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        if (apiTransferToken != null) {
            String transferTokenId = new String(apiTransferToken.getOpaqueToken());
            org.apache.juddi.model.TransferToken modelTransferToken = em
                    .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
            if (modelTransferToken != null)
                em.remove(modelTransferToken);
        }

        KeyBag keyBag = body.getKeyBag();
        if (keyBag != null) {
            List<String> keyList = keyBag.getKey();
            Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0);
            for (String key : keyList) {
                // Creating parameters for key-checking query
                DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)",
                        key.toUpperCase(), DynamicQuery.PREDICATE_EQUALS);

                params.add(param);
            }

            // Find the associated transfer tokens and remove them.
            DynamicQuery getTokensQry = new DynamicQuery();
            getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad();
            getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0]));

            Query qry = getTokensQry.buildJPAQuery(em);
            List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList();
            if (tokensToDelete != null && tokensToDelete.size() > 0) {
                for (org.apache.juddi.model.TransferToken tt : tokensToDelete)
                    em.remove(tt);
            }
        }

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

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

From source file:com.eucalyptus.blockstorage.BlockStorageController.java

/**
 * Perform a volume export validated by the token presented in the request.
 * Upon completion of the Export operation, the identified host (by ip and iqn) will
 * have access to connect to the requested volume. No connection is made, just the authorization.
 *
 * If a valid export record exists for the given token and host information, then the connectionString
 * for that record is returned rather than creating a new record.
 * @param request//from   ww w.j a  va  2 s .c om
 * @return
 * @throws EucalyptusCloudException
 */
public ExportVolumeResponseType ExportVolume(ExportVolumeType request) throws EucalyptusCloudException {
    final ExportVolumeResponseType reply = (ExportVolumeResponseType) request.getReply();
    final String volumeId = request.getVolumeId();
    final String token = request.getToken();
    final String ip = request.getIp();
    final String iqn = request.getIqn();
    reply.setVolumeId(volumeId);

    LOG.info("Processing ExportVolume request for volume " + volumeId);

    final Function<VolumeInfo, String> exportAndAttach = new Function<VolumeInfo, String>() {
        @Override
        public String apply(VolumeInfo volume) {
            int tokenRetry = 3;
            VolumeToken tokenInfo = null;
            VolumeInfo volEntity = Entities.merge(volume);
            for (int i = 0; i < tokenRetry; i++) {
                try {
                    tokenInfo = volEntity.getAttachmentTokenIfValid(token);
                    if (tokenInfo != null) {
                        break;
                    }
                } catch (Exception e) {
                    LOG.warn("Could not check for valid token. Will retry. ", e);
                    tokenInfo = null;
                }
                try {
                    Thread.sleep(100); //sleep 100ms to make retry useful.
                } catch (InterruptedException e) {
                    throw new RuntimeException("Token check backoff sleep interrupted", e);
                }
            }

            if (tokenInfo == null) {
                throw new RuntimeException("Cannot export, due to invalid token");
            }

            VolumeExportRecord export = null;
            try {
                export = tokenInfo.getValidExport(ip, iqn);
            } catch (EucalyptusCloudException e2) {
                LOG.error("Failed when checking/getting valid export for " + ip + " - " + iqn);
                return null;
            }

            if (export == null) {
                String connectionString = null;
                try {
                    //attachVolume must be idempotent.
                    connectionString = blockManager.exportVolume(volumeId, iqn);
                } catch (Exception e) {
                    LOG.error("Could not attach volume: " + e.getMessage());
                    LOG.trace("Failed volume attach", e);
                    return null;
                }

                try {
                    //addExport must be idempotent, if one exists a new is not added with same data
                    tokenInfo.addExport(ip, iqn, connectionString);
                    return connectionString;
                } catch (Exception e) {
                    LOG.error("Could not export volume " + volumeId + " failed to add export record");
                    try {
                        LOG.info("Unexporting volume " + volumeId + " to " + iqn
                                + " for export failure cleanup");
                        blockManager.unexportVolume(volumeId, iqn);
                    } catch (EucalyptusCloudException e1) {
                        LOG.error("Failed to detach volume during invalidation failure", e);
                    }
                    return null;
                }
            } else {
                LOG.debug("Found extant valid export for " + ip + " and " + iqn
                        + " returning connection information for that export");
                return export.getConnectionString();
            }
        }
    };

    VolumeInfo searchVol = new VolumeInfo(volumeId);
    EntityTransaction db = Entities.get(VolumeInfo.class);
    VolumeInfo vol = null;
    try {
        vol = Entities.uniqueResult(searchVol);
        db.commit();
    } catch (NoSuchElementException e) {
        LOG.error("No volume db record found for " + volumeId, e);
        throw new EucalyptusCloudException("Volume not found " + volumeId);
    } catch (TransactionException e) {
        LOG.error("Failed to Export due to db error", e);
        throw new EucalyptusCloudException("Could not export volume", e);
    } finally {
        if (db.isActive()) {
            db.rollback();
        }
    }

    //Do the export
    try {
        String connectionString = Entities.asTransaction(VolumeInfo.class, exportAndAttach).apply(vol);
        if (connectionString != null) {
            reply.setConnectionString(connectionString);
        } else {
            throw new Exception("Got null record result. Cannot set connection string");
        }
    } catch (Exception e) {
        LOG.error("Failed ExportVolume transaction due to: " + e.getMessage(), e);
        throw new EucalyptusCloudException("Failed to add export", e);
    }

    return reply;
}

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

/**
 * saves or updates a newscategory.//from ww w . ja  v a 2s .c o  m
 *
 * @param category the category
 * @return the category with the new id
 * @throws Exception the exception
 */
private NewsCategory saveNewsCategory(NewsCategory category) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // try loading the category for the firstspirit id
        NewsCategory cat = getNewsCategory(category.getFs_id(), category.getLanguage(), em);

        if (cat != null) {

            List<NewsMetaCategory> metaCats = category.getMetaCategories();

            // the already persistent categories
            List<NewsMetaCategory> original_metaCats = cat.getMetaCategories();

            // update existing category
            cat.setMetaCategories(new ArrayList<NewsMetaCategory>());

            for (NewsMetaCategory metaCat : metaCats) {
                metaCat = saveNewsMetaCategory(metaCat, em);
                cat.getMetaCategories().add(metaCat);

                original_metaCats.remove(metaCat);
            }
            for (NewsMetaCategory mc : original_metaCats) {
                mc.setLastmodified(category.getLastmodified());
            }
            cat.getMetaCategories().addAll(original_metaCats);

            cat.setFs_id(category.getFs_id());
            cat.setLanguage(category.getLanguage());
            cat.setName(category.getName());
            cat.setVersion(category.getVersion());
            cat.setLastmodified(category.getLastmodified());

            // update
            category = em.merge(cat);
        } else {
            updateMetaCategories(category, em);
            // save to db
            em.persist(category);
        }

        tx.commit();

        return category;

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

From source file:de.iai.ilcd.model.dao.DataSetDao.java

/**
 * Set the {@link DataSet#setMostRecentVersion(boolean) most recent version flags} for all data sets with the
 * specified uuid. Please note that this method
 * <strong>does not open a separate transaction</strong>.
 * /*  w ww  .ja v a2s .co  m*/
 * @param uuid
 *            uuid of the data sets
 */
@SuppressWarnings("unchecked")
protected boolean setMostRecentVersionFlags(String uuid) {
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();
    try {
        Query q = em.createQuery("SELECT a FROM " + this.getJpaName()
                + " a WHERE a.uuid.uuid=:uuid ORDER BY a.version.majorVersion desc, a.version.minorVersion desc, a.version.subMinorVersion desc");
        q.setParameter("uuid", uuid);
        List<T> res = q.getResultList();
        if (!res.isEmpty()) {
            t.begin();
            // get first element and mark it as most recent version (correct order is taken care of in query!)
            T tmp = res.get(0);
            tmp.setMostRecentVersion(true);
            tmp = em.merge(tmp);

            // set "false" for all other elements if required
            final int size = res.size();
            if (size > 1) {
                for (int i = 1; i < size; i++) {
                    tmp = res.get(i);
                    if (tmp.isMostRecentVersion()) {
                        tmp.setMostRecentVersion(false);
                        tmp = em.merge(tmp);
                    }
                }
            }
            t.commit();
            return true;
        } else {
            DataSetDao.LOGGER.warn("Most recent version flag was called for non-existent UUID: " + uuid);
            return false;
        }
    } catch (Exception e) {
        DataSetDao.LOGGER.error("Could not set most recent version flag for UUID: " + uuid);
        if (t.isActive()) {
            t.rollback();
        }
        return false;
    }
}