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:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * Deletes every item older than the creationTime of the UXBEntity.
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *///from  w  ww  . ja v  a  2  s. c  o  m
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

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

        // Remove old newsdrilldown
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM news x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                News art = (News) obj;
                em.remove(art);
            }
        }

        // Remove old newsCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM category x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsCategory art = (NewsCategory) obj;
                em.remove(art);
            }
        }

        // Remove old newsMetaCategories
        query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM metaCategory x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                NewsMetaCategory art = (NewsMetaCategory) obj;
                em.remove(art);
            }
        }

        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.setRollbackOnly();
        }
        logger.error("Failure while deleting from the database", e);
        throw e;
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

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

/**
 * Deletes a newsdrilldown from the db./*  w w  w . j  a  va2 s . c om*/
 *
 * @param entity The newsdrilldown 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("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            News art = (News) query.getSingleResult();
            // delete file from filesystem
            URL url = new URL(art.getUrl());
            File file = new File(webpath + url.getPath());
            if (file.exists()) {
                // Try acquiring the lock without blocking. This method returns
                // null or throws an exception if the file is already locked.
                try {
                    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
                    // Try to lock the file
                    FileLock lock = channel.tryLock();
                    // Delete the file
                    file.delete();
                    // Release the lock
                    lock.release();
                    lock.channel().close();
                } catch (OverlappingFileLockException e) {
                    logger.info("File is already locked in this thread or virtual machine");
                } catch (MalformedURLException e) {
                    logger.info("wrong url", e);
                }
            }
            // remove article from content repository

            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            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.validation.ValidatePublish.java

/**
 * throws if it doesn't exist, returns it if it does
 *
 * @param tmodelKey//from   w w w .j  a  va 2 s  .co m
 * @return null, or a TModel object
 * @throws ValueNotAllowedException
 * @since 3.3
 */
private TModel verifyTModelKeyExists(String tmodelKey)
        throws ValueNotAllowedException, DispositionReportFaultMessage {
    TModel api = null;
    EntityManager em = PersistenceManager.getEntityManager();
    boolean found = false;
    if (em == null) {
        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
    } else {
        Tmodel modelTModel = null;
        {
            EntityTransaction tx = em.getTransaction();
            try {

                tx.begin();
                modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);

                if (modelTModel != null) {
                    found = true;
                    api = new TModel();
                    MappingModelToApi.mapTModel(modelTModel, api);
                }
                tx.commit();

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

        }
    }
    if (!found) {
        throw new ValueNotAllowedException(
                new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey));
    }
    return api;
}

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

/**
 * {@inheritDoc}// ww w  .  j  a  v a 2  s.c o  m
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage,
 *      AccessControlList, Date)
 */
@Override
public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now)
        throws SearchServiceDatabaseException, UnauthorizedException {
    String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage);
    String mediaPackageId = mediaPackage.getIdentifier().toString();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity entity = getSearchEntity(mediaPackageId, em);
        if (entity == null) {
            // Create new search entity
            SearchEntity searchEntity = new SearchEntity();
            searchEntity.setOrganization(securityService.getOrganization().getId());
            searchEntity.setMediaPackageId(mediaPackageId);
            searchEntity.setMediaPackageXML(mediaPackageXML);
            searchEntity.setAccessControl(AccessControlParser.toXml(acl));
            searchEntity.setModificationDate(now);
            searchEntity.setSeriesId(mediaPackage.getSeries());
            em.persist(searchEntity);
        } else {
            // Ensure this user is allowed to update this media package
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update media package " + mediaPackageId);
                }
            }
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setMediaPackageId(mediaPackageId);
            entity.setMediaPackageXML(mediaPackageXML);
            entity.setAccessControl(AccessControlParser.toXml(acl));
            entity.setModificationDate(now);
            entity.setSeriesId(mediaPackage.getSeries());
            em.merge(entity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", 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 ServiceDetail saveService(SaveService body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

        ServiceDetail result = new ServiceDetail();

        List<org.uddi.api_v3.BusinessService> apiBusinessServiceList = body.getBusinessService();
        for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) {

            org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService();
            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();
            modelBusinessEntity.setEntityKey(apiBusinessService.getBusinessKey());

            MappingApiToModel.mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity);

            setOperationalInfo(em, modelBusinessService, publisher, false);

            em.persist(modelBusinessService);

            result.getBusinessService().add(apiBusinessService);

            validator.validateSaveServiceMax(em, modelBusinessService.getBusinessEntity().getEntityKey());
        }

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

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

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

/**
 * Retrieves all the annotations about a specified Resource, by ascendant or descendant chronological order
 * @param _url// w ww . j  av  a2s.  c  om
 * @param asc
 * @return
 */
public List<Annotation> retrieveAnnotations(String _url, boolean asc) {
    //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();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " order by annotation.id desc";
        if (asc)
            order_by_clause = " order by annotation.id asc";
        List<Annotation> annotations = ((List<Annotation>) em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?"
                        + order_by_clause)
                .setParameter(1, _uri).getResultList());
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

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

/**
 * Tests if an agent has expressed a Spaming on a resource
 * @param _creator//ww  w  .j  a  v  a2 s.  c  om
 * @param _url_to_test
 * @return
 */
public boolean spamExpressed(Agent _creator, String _url_to_test) {
    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_to_test)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.spamExpressed] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url_to_test);
            return false;
        }
        AnnotationStatus status_spam = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Spam").getSingleResult();
        if (status_spam != null) {
            Object nb_annotations_troll = em.createQuery(
                    " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? and annotation.creator=? and annotation.status=?")
                    .setParameter(1, _uri).setParameter(2, _creator).setParameter(3, status_spam)
                    .getSingleResult();
            if (nb_annotations_troll instanceof Long) {
                nb = ((Long) nb_annotations_troll).longValue();
            }
        }
        tx.commit();
        if (nb > 0)
            return true;
        else
            return false;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.spamExpressed] unable to retrieve Annotations" + " on url : "
                + _url_to_test + " cause : " + e.getMessage());
        return false; //to prevent to express its opinion if the system fails
    }
}

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

public CreateStorageSnapshotResponseType CreateStorageSnapshot(CreateStorageSnapshotType request)
        throws EucalyptusCloudException {
    CreateStorageSnapshotResponseType reply = (CreateStorageSnapshotResponseType) request.getReply();

    StorageProperties.updateWalrusUrl();
    if (!StorageProperties.enableSnapshots) {
        LOG.error("Snapshots have been disabled. Please check connection to ObjectStorage.");
        return reply;
    }/*from w w w  . j  a v a 2s.  c  om*/

    String volumeId = request.getVolumeId();
    LOG.info("Processing CreateStorageSnapshot request for volume " + volumeId);

    String snapshotId = request.getSnapshotId();
    EntityTransaction dbTrans = Entities.get(VolumeInfo.class);
    VolumeInfo sourceVolumeInfo = null;
    try {
        VolumeInfo volumeInfo = new VolumeInfo(volumeId);
        sourceVolumeInfo = Entities.uniqueResult(volumeInfo);
        dbTrans.commit();
    } catch (NoSuchElementException e) {
        LOG.debug("Volume " + volumeId + " not found in db");
        throw new NoSuchVolumeException(volumeId);
    } catch (final Throwable e) {
        LOG.warn("Volume " + volumeId + " error getting info from db. May not exist. " + e.getMessage());
        throw new EucalyptusCloudException("Could not get volume information for volume " + volumeId, e);
    } finally {
        if (dbTrans.isActive()) {
            dbTrans.rollback();
        }
        dbTrans = null;
    }

    if (sourceVolumeInfo == null) {
        //Another check to be sure that we have the source volume
        throw new NoSuchVolumeException(volumeId);
    } else {
        //check status
        if (!sourceVolumeInfo.getStatus().equals(StorageProperties.Status.available.toString())) {
            throw new VolumeNotReadyException(volumeId);
        } else {
            //create snapshot
            if (StorageProperties.shouldEnforceUsageLimits) {
                int maxSize = -1;
                try {
                    maxSize = BlockStorageGlobalConfiguration.getInstance()
                            .getGlobal_total_snapshot_size_limit_gb();
                } catch (Exception e) {
                    LOG.error("Could not determine max global snapshot limit. Aborting snapshot creation", e);
                    throw new EucalyptusCloudException("Total size limit not found.", e);
                }
                if (maxSize <= 0) {
                    LOG.warn("Total snapshot size limit is less than or equal to 0");
                    throw new EucalyptusCloudException("Total snapshot size limit is less than or equal to 0");
                }
                if (totalSnapshotSizeLimitExceeded(snapshotId, sourceVolumeInfo.getSize(), maxSize)) {
                    LOG.info("Snapshot " + snapshotId + " exceeds total snapshot size limit of " + maxSize
                            + "GB");
                    throw new SnapshotTooLargeException(snapshotId, maxSize);
                }
            }

            Snapshotter snapshotter = null;
            SnapshotInfo snapshotInfo = new SnapshotInfo(snapshotId);
            EntityTransaction snapTrans = Entities.get(SnapshotInfo.class);
            Date startTime = new Date();
            try {
                snapshotInfo.setUserName(sourceVolumeInfo.getUserName());
                snapshotInfo.setVolumeId(volumeId);
                snapshotInfo.setStartTime(startTime);
                snapshotInfo.setProgress("0");
                snapshotInfo.setSizeGb(sourceVolumeInfo.getSize());
                snapshotInfo.setStatus(StorageProperties.Status.creating.toString());

                /* Change to support sync snap consistency point set on CLC round-trip */
                /*
                 * Always do this operation. On backends that don't support it they will
                 * return null. In that case it is effectively a no-op and we continue normal
                 * async snapshot.
                 * 
                 * If the snap point is set, then we update the DB properly. 
                 */
                String snapPointId = null;
                try {
                    //This will be a no-op if the backend doesn't support it. Will return null.
                    snapPointId = blockManager.createSnapshotPoint(volumeId, snapshotId);
                    if (snapPointId == null) {
                        LOG.debug("Synchronous snap point not supported for this backend. Cleanly skipped.");
                    } else {
                        snapshotInfo.setSnapPointId(snapPointId);
                    }
                    //Do a commit here because the snapshotter expects to find db entry.
                    snapshotInfo.setStatus(StorageProperties.Status.creating.toString());

                    Context ctx = null;
                    try {
                        ctx = Contexts.lookup(request.getCorrelationId());
                        if (!ctx.getChannel().isOpen()) {
                            throw new NoSuchContextException("Channel is closed");
                        }
                    } catch (NoSuchContextException e) {
                        if (snapPointId != null) {
                            //Other end hung up, mark this as failed since this is a sync operation
                            throw new EucalyptusCloudException("Channel closed, aborting snapshot.");
                        }
                    }
                } catch (EucalyptusCloudException e) {
                    //If the snapshot was done but took too long then delete the snap and fail the op.
                    try {
                        blockManager.deleteSnapshotPoint(volumeId, snapshotId, snapPointId);
                    } catch (Exception ex) {
                        LOG.error("Snapshot " + snapshotId + " exception on snap point cleanup after failure: "
                                + e.getMessage());
                    }
                    LOG.error("Snapshot " + snapshotId + " failed to create snap point successfully: "
                            + e.getMessage());
                    throw e;
                } finally {
                    Entities.persist(snapshotInfo);
                }

                /* Resume old code path and finish the snapshot process if already started */
                //snapshot asynchronously
                snapshotter = new Snapshotter(volumeId, snapshotId, snapPointId);

                reply.setSnapshotId(snapshotId);
                reply.setVolumeId(volumeId);
                reply.setStartTime(
                        DateUtils.format(startTime.getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z");
                reply.setProgress(snapshotInfo.getProgress());
            } catch (EucalyptusCloudException cloudEx) {
                snapshotInfo.setStatus(StorageProperties.Status.failed.toString());
                LOG.error("Snapshot " + snapshotId + " creation failed with exception ", cloudEx);
                throw cloudEx;
            } catch (final Throwable e) {
                snapshotInfo.setStatus(StorageProperties.Status.failed.toString());
                LOG.error("Snapshot " + snapshotId + " Error committing state update to failed", e);
                throw new EucalyptusCloudException(
                        "Snapshot " + snapshotId + " unexpected throwable exception caught", e);
            } finally {
                if (snapTrans.isActive()) {
                    snapTrans.commit();
                }
                snapTrans = null;
            }
            reply.setStatus(snapshotInfo.getStatus());
            if (snapshotter != null) { // Kick off the snapshotter task after persisting snapshot to database
                snapshotService.add(snapshotter);
            }
        }
    }
    return reply;
}

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

/**
 * Tests if an agent has expressed a Flame on a resource
 * @param _creator//www  . j a v  a 2  s . c  o m
 * @param _url_to_test
 * @return
 */
public boolean flameExpressed(Agent _creator, String _url_to_test) {
    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_to_test)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.flameExpressed] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url_to_test);
            return false;
        }
        AnnotationStatus status_flame = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Flame")
                .getSingleResult();
        if (status_flame != null) {
            Object nb_annotations_flame = em.createQuery(
                    " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? and annotation.creator=? and annotation.status=?")
                    .setParameter(1, _uri).setParameter(2, _creator).setParameter(3, status_flame)
                    .getSingleResult();
            if (nb_annotations_flame instanceof Long) {
                nb = ((Long) nb_annotations_flame).longValue();
            }
        }
        tx.commit();
        if (nb > 0)
            return true;
        else
            return false;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.flameExpressed] unable to retrieve Annotations" + " on url : "
                + _url_to_test + " cause : " + e.getMessage());
        return false; //to prevent to express its opinion if the system fails
    }
}

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

/**
 * Tests if an agent has expressed a Trolling on a resource
 * @param _creator/* www .  j  av a 2s .c  om*/
 * @param _url_to_test
 * @return
 */
public boolean trollExpressed(Agent _creator, String _url_to_test) {
    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_to_test)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.trollExpressed] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url_to_test);
            return false;
        }
        AnnotationStatus status_troll = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Troll")
                .getSingleResult();
        if (status_troll != null) {
            Object nb_annotations_troll = em.createQuery(
                    " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? and annotation.creator=? and annotation.status=?")
                    .setParameter(1, _uri).setParameter(2, _creator).setParameter(3, status_troll)
                    .getSingleResult();
            if (nb_annotations_troll instanceof Long) {
                nb = ((Long) nb_annotations_troll).longValue();
            }
        }
        tx.commit();
        if (nb > 0)
            return true;
        else
            return false;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.trollExpressed] unable to retrieve Annotations" + " on url : "
                + _url_to_test + " cause : " + e.getMessage());
        return false; //to prevent to express its opinion if the system fails
    }
}