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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves the Resource in the database with the specified id.
 * @param id//from w  ww .j  av  a2s  .co m
 * @return a Resource that may be empty
 */
public Resource retrieveResource(long id) {
    //TODO move this method elsewhere, it's here because extension of Resource Class are not queried if it were in controler-resource package
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Resource resource = (Resource) em.createQuery("from Resource where id = ?").setParameter(1, id)
                .getSingleResult();
        tx.commit();
        ////em.close();
        return resource;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveResource.retrieveResource] unable to retrieve Resource" + " id : " + id
                + " cause : " + e.getMessage());
        return new Resource();
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

@SuppressWarnings("unchecked")
public UserAction addUserFootprint(UserAction a) throws UserTrackingException {
    a.setType("FOOTPRINT");
    EntityManager em = null;//  w w  w  .j a va2  s. co m
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query q = em.createNamedQuery("findLastUserFootprintOfSession");
        q.setMaxResults(1);
        q.setParameter("sessionId", a.getSessionId());
        Collection<UserAction> userActions = q.getResultList();

        if (userActions.size() >= 1) {
            UserAction last = userActions.iterator().next();
            if (last.getMediapackageId().equals(a.getMediapackageId()) && last.getType().equals(a.getType())
                    && last.getOutpoint() == a.getInpoint()) {
                last.setOutpoint(a.getOutpoint());
                a = last;
                a.setId(last.getId());
            } else {
                em.persist(a);
            }
        } else {
            em.persist(a);
        }
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

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

/**
 * Gets all client subscription information. This is used for server to server subscriptions
 * Administrative privilege required./*w  ww .  j  a  v  a  2 s  . c o  m*/
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage 
 */
@SuppressWarnings("unchecked")
public ClientSubscriptionInfoDetail getAllClientSubscriptionInfoDetail(GetAllClientSubscriptionInfoDetail body)
        throws DispositionReportFaultMessage {

    new ValidateClientSubscriptionInfo(null).validateGetAllClientSubscriptionDetail(body);

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

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

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        Query query = em.createQuery("SELECT cs from ClientSubscriptionInfo as cs");
        List<org.apache.juddi.model.ClientSubscriptionInfo> modelClientSubscriptionInfoList = query
                .getResultList();

        for (ClientSubscriptionInfo modelClientSubscriptionInfo : modelClientSubscriptionInfoList) {

            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();

            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

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

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

}

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

public static void deregisterImage(String imageId) throws NoSuchImageException, InstanceNotTerminatedException {
    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//from www  .  j  a  v  a 2s  . c o  m
        ImageInfo img = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        if (ImageMetadata.State.deregistered.equals(img.getState())
                || ImageMetadata.State.failed.equals(img.getState())) {
            Entities.delete(img);
        } else {
            if (img instanceof MachineImageInfo) {
                final String runManifestLocation = ((MachineImageInfo) img).getRunManifestLocation();
                final String manifestLocation = ((MachineImageInfo) img).getManifestLocation();
                // cleanup system generated buckets if exist
                if (!manifestLocation.equals(runManifestLocation))
                    img.setState(ImageMetadata.State.deregistered_cleanup);
                else
                    img.setState(ImageMetadata.State.deregistered);
            } else
                img.setState(ImageMetadata.State.deregistered);
        }
        tx.commit();
        if (img instanceof ImageMetadata.StaticDiskImage) {
            StaticDiskImages.flush((StaticDiskImage) img);
        }
    } catch (ConstraintViolationException cve) {
        tx.rollback();
        throw new InstanceNotTerminatedException(
                "To deregister " + imageId + " all associated instances must be in the terminated state.");
    } catch (TransactionException ex) {
        tx.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, ex);
    } catch (NoSuchElementException ex) {
        tx.rollback();
        throw new NoSuchImageException("Failed to lookup image: " + imageId, ex);
    } finally {
        if (tx.isActive())
            tx.rollback();
    }
}

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

public List<AssertionStatusItem> getAssertionStatusReport(String authInfo, CompletionStatus completionStatus)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

        List<org.uddi.api_v3.AssertionStatusItem> result = PublicationHelper
                .getAssertionStatusItemList(publisher, completionStatus, em);

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

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

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

/**
 * Retrieves an AnnotationStatus in the database according to the specified label
 * @param label/* w  w  w  . jav  a 2 s .c  o  m*/
 * @return an AnnotationStatus that may be a new UriStatus with no value.
 */
public AnnotationStatus retrieveAnnotationStatus(String label) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        AnnotationStatus annotationstatus = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, label).getSingleResult();
        tx.commit();
        return annotationstatus;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " label : " + label + " cause : " + e.getMessage());
        return new AnnotationStatus();
    }
}

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/*  www  .  j a va  2s. co 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:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem/* w w  w. j  ava 2 s  .  co  m*/
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    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 = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to 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.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/* www  .  j a  v  a 2 s .c om*/
 * @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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a list of Annotation according to the specified label
 * @param label//from   www .  j  a v  a2 s  .c o  m
 * @return
 */
public List<Annotation> retrieveAnnotation(String label) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        //List docs = em.createQuery("from Annotation where label = '" + label + "'").getResultList();
        List<Annotation> docs = ((List<Annotation>) em.createQuery("from Annotation where label = ?")
                .setParameter(1, label).getResultList());
        tx.commit();
        return docs;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotation] unable to retrieve Annotation" + " label : "
                + label + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}