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

public RegisteredInfo getRegisteredInfo(GetRegisteredInfo body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  ww w . j  av  a2s  . c  om
        tx.begin();

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

        new ValidatePublish(publisher).validateRegisteredInfo(body);

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

        List<?> tmodelKeysFound = null;

        if (body.getInfoSelection().equals(InfoSelection.HIDDEN))
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound,
                    new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.TRUE,
                            DynamicQuery.PREDICATE_EQUALS));
        else if (body.getInfoSelection().equals(InfoSelection.VISIBLE))
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound,
                    new DynamicQuery.Parameter(TModelQuery.ENTITY_ALIAS + ".deleted", Boolean.FALSE,
                            DynamicQuery.PREDICATE_EQUALS));
        else
            tmodelKeysFound = FindTModelByPublisherQuery.select(em, null, publisher, tmodelKeysFound);

        RegisteredInfo result = new RegisteredInfo();

        // Sort and retrieve the final results
        List<?> queryResults = FetchBusinessEntitiesQuery.select(em, new FindQualifiers(), businessKeysFound,
                null, null, null);
        if (queryResults.size() > 0) {
            result.setBusinessInfos(new org.uddi.api_v3.BusinessInfos());

            for (Object item : queryResults) {
                org.apache.juddi.model.BusinessEntity modelBusinessEntity = (org.apache.juddi.model.BusinessEntity) item;
                org.uddi.api_v3.BusinessInfo apiBusinessInfo = new org.uddi.api_v3.BusinessInfo();

                MappingModelToApi.mapBusinessInfo(modelBusinessEntity, apiBusinessInfo);

                result.getBusinessInfos().getBusinessInfo().add(apiBusinessInfo);
            }
        }

        // Sort and retrieve the final results
        queryResults = FetchTModelsQuery.select(em, new FindQualifiers(), tmodelKeysFound, null, null, null);
        if (queryResults.size() > 0) {
            result.setTModelInfos(new org.uddi.api_v3.TModelInfos());

            for (Object item : queryResults) {
                org.apache.juddi.model.Tmodel modelTModel = (org.apache.juddi.model.Tmodel) item;
                org.uddi.api_v3.TModelInfo apiTModelInfo = new org.uddi.api_v3.TModelInfo();

                MappingModelToApi.mapTModelInfo(modelTModel, apiTModelInfo);

                result.getTModelInfos().getTModelInfo().add(apiTModelInfo);
            }
        }

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

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

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * //from   w w  w .  j a  va  2  s .  c o  m
 * @param serviceType
 *          the service type
 * @param baseUrl
 *          the base url
 * @throws ServiceRegistryException
 *           if there is a problem communicating with the jobs database
 */
private void cleanRunningJobs(String serviceType, String baseUrl) throws ServiceRegistryException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query query = em.createNamedQuery("Job.processinghost.status");
        query.setParameter("status", Status.RUNNING);
        query.setParameter("host", baseUrl);
        query.setParameter("serviceType", serviceType);
        @SuppressWarnings("unchecked")
        List<JobJpaImpl> unregisteredJobs = query.getResultList();
        for (JobJpaImpl job : unregisteredJobs) {
            if (job.isDispatchable()) {
                em.refresh(job);
                // If this job has already been treated
                if (Status.CANCELED.equals(job.getStatus()) || Status.RESTART.equals(job.getStatus()))
                    continue;
                if (job.getRootJob() != null && Status.PAUSED.equals(job.getRootJob().getStatus())) {
                    JobJpaImpl rootJob = job.getRootJob();
                    cancelAllChildren(rootJob, em);
                    rootJob.setStatus(Status.RESTART);
                    rootJob.setOperation(START_OPERATION);
                    em.merge(rootJob);
                    continue;
                }

                logger.info("Marking child jobs from job {} as canceled", job);
                cancelAllChildren(job, em);
                logger.info("Rescheduling lost job {}", job);
                job.setStatus(Status.RESTART);
                job.setProcessorServiceRegistration(null);
            } else {
                logger.info("Marking lost job {} as failed", job);
                job.setStatus(Status.FAILED);
            }
            em.merge(job);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.eucalyptus.walrus.WalrusFSManager.java

private String getMultipartData(ObjectInfo objectInfo, GetObjectType request, GetObjectResponseType response)
        throws WalrusException {
    //get all parts
    PartInfo searchPart = new PartInfo(request.getBucket(), request.getKey());
    searchPart.setCleanup(false);/* w  w  w  .  ja v  a 2  s . c  om*/
    searchPart.setUploadId(objectInfo.getUploadId());
    List<PartInfo> parts;
    EntityTransaction db = Entities.get(PartInfo.class);
    try {
        Criteria partCriteria = Entities.createCriteria(PartInfo.class);
        partCriteria.setReadOnly(true);
        partCriteria.add(Example.create(searchPart));
        partCriteria.add(Restrictions.isNotNull("partNumber"));
        partCriteria.addOrder(Order.asc("partNumber"));

        parts = partCriteria.list();
        if (parts.size() == 0) {
            throw new InternalErrorException(
                    "No parts found corresponding to uploadId: " + objectInfo.getUploadId());
        }
    } finally {
        db.rollback();
    }

    if (request.getInlineData()) {
        if ((objectInfo.getSize() * 4) > WalrusProperties.MAX_INLINE_DATA_SIZE) {
            throw new InlineDataTooLargeException(request.getBucket() + "/" + request.getKey());
        }
        String base64Data = "";
        for (PartInfo part : parts) {
            byte[] bytes = new byte[102400];
            int bytesRead = 0, offset = 0;
            try {
                FileIO fileIO = storageManager.prepareForRead(part.getBucketName(), part.getObjectName());
                while ((bytesRead = fileIO.read(offset)) > 0) {
                    ByteBuffer buffer = fileIO.getBuffer();
                    if (buffer != null) {
                        buffer.get(bytes, 0, bytesRead);
                        base64Data += new String(bytes, 0, bytesRead);
                        offset += bytesRead;
                    }
                }
                fileIO.finish();
            } catch (Exception e) {
                LOG.error(e, e);
                throw new InternalErrorException(e);
            }
        }
        return Hashes.base64encode(base64Data);
    } else {
        response.setHasStreamingData(true);
        // support for large objects
        storageManager.getMultipartObject(response, parts, request.getIsCompressed());
        return null;
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Sets the online status of a service registration.
 * //from   w  w  w .ja  va2  s.co m
 * @param serviceType
 *          The job type
 * @param baseUrl
 *          the host URL
 * @param online
 *          whether the service is online or off
 * @param jobProducer
 *          whether this service produces jobs for long running operations
 * @return the service registration
 */
protected ServiceRegistration setOnlineStatus(String serviceType, String baseUrl, String path, boolean online,
        Boolean jobProducer) throws ServiceRegistryException {
    if (isBlank(serviceType) || isBlank(baseUrl)) {
        throw new IllegalArgumentException("serviceType and baseUrl must not be blank");
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        HostRegistrationJpaImpl hostRegistration = fetchHostRegistration(em, baseUrl);
        if (hostRegistration == null) {
            throw new IllegalStateException(
                    "A service registration can not be updated when it has no associated host registration");
        }
        ServiceRegistrationJpaImpl registration = getServiceRegistration(em, serviceType, baseUrl);
        if (registration == null) {
            if (isBlank(path)) {
                // we can not create a new registration without a path
                throw new IllegalArgumentException("path must not be blank when registering new services");
            }
            if (jobProducer == null) { // if we are not provided a value, consider it to be false
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, false);

            } else {
                registration = new ServiceRegistrationJpaImpl(hostRegistration, serviceType, path, jobProducer);
            }
            em.persist(registration);
        } else {
            if (StringUtils.isNotBlank(path))
                registration.setPath(path);
            registration.setOnline(online);
            if (jobProducer != null) { // if we are not provided a value, don't update the persistent value
                registration.setJobProducer(jobProducer);
            }
            em.merge(registration);
        }
        tx.commit();
        hostsStatistics.updateHost(hostRegistration);
        servicesStatistics.updateService(registration);
        return registration;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new ServiceRegistryException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.eucalyptus.walrus.WalrusFSManager.java

/**
 * Handles a HEAD request to the bucket. Just returns 200ok if bucket exists and user has access. Otherwise returns 404 if not found or 403 if no accesss.
 *
 * @param request/*w ww .ja  va2  s . c  om*/
 * @return
 * @throws EucalyptusCloudException
 */
@Override
public HeadBucketResponseType headBucket(HeadBucketType request) throws WalrusException {
    HeadBucketResponseType reply = (HeadBucketResponseType) request.getReply();
    Context ctx = Contexts.lookup();
    Account account = ctx.getAccount();
    String bucketName = request.getBucket();
    EntityTransaction db = Entities.get(BucketInfo.class);
    try {
        BucketInfo bucket = Entities.uniqueResult(new BucketInfo(bucketName));
        return reply;
    } catch (NoSuchElementException e) {
        // Bucket not found return 404
        throw new HeadNoSuchBucketException(bucketName);
    } catch (TransactionException e) {
        LOG.error("DB transaction error looking up bucket " + bucketName + ": " + e.getMessage());
        LOG.debug("DB tranction exception looking up bucket " + bucketName, e);
        throw new HeadNoSuchBucketException("Internal error doing db lookup for " + bucketName, e);
    } finally {
        // Nothing to commit, always rollback.
        db.rollback();
    }
}

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

/**
 * Removes connection authorization for the specified iqn/ip pair in the request using
 * the specified token. Only performs the operation if the token is valid for the specified volume.
 *
 * Invalidates the token upon successful de-authorization.
 * @param request//from  w  ww.  j  ava  2  s .co  m
 * @return
 * @throws EucalyptusCloudException
 */
public UnexportVolumeResponseType UnexportVolume(UnexportVolumeType request) throws EucalyptusCloudException {
    UnexportVolumeResponseType reply = request.getReply();
    final String token = request.getToken();
    final String volumeId = request.getVolumeId();
    final String nodeIqn = request.getIqn();
    final String nodeIp = request.getIp();

    LOG.info("Processing UnexportVolume request for volume " + volumeId + " from node " + nodeIp + " with iqn "
            + nodeIqn);

    VolumeInfo volumeEntity = null;
    VolumeToken validToken = null;
    EntityTransaction db = Entities.get(VolumeInfo.class);
    try {
        VolumeInfo foundVolume = Entities.uniqueResult(new VolumeInfo(volumeId));
        volumeEntity = Entities.merge(foundVolume);

        try {
            validToken = volumeEntity.getAttachmentTokenIfValid(token);
            //volumeEntity.invalidateExport(tokenValue, nodeIp, nodeIqn);
            //Entities.flush(volumeEntity); //Sync state -- not needed.... same transaction
        } catch (Exception e) {
            LOG.error("Invalid token in request for volume " + volumeId + ". Encrypted token: " + token);
            throw new EucalyptusCloudException(e);
        }

        if (validToken.hasOnlyExport(nodeIp, nodeIqn)) {
            //There are no active exports, so unexport all.
            blockManager.unexportVolumeFromAll(volumeId);
        } else {
            try {
                blockManager.unexportVolume(volumeEntity.getVolumeId(), nodeIqn);
            } catch (UnsupportedOperationException e) {
                //The backend doesn't support unexport to just one host... this is a noop.
                LOG.info("Volume " + volumeId
                        + ": UnexportVolume for single host not supported by backend. Treating as no-op and continuing normally.");
            } catch (Exception e) {
                LOG.error("Could not detach volume: " + volumeId, e);
                throw e;
            }
        }

        //Do the actual invalidation. Handle retries, but only on the DB part.
        if (!Entities.asTransaction(VolumeInfo.class, new Function<VolumeInfo, Boolean>() {
            @Override
            public Boolean apply(VolumeInfo vol) {
                VolumeInfo entity = Entities.merge(vol);
                try {
                    entity.invalidateExport(token, nodeIp, nodeIqn);
                    return true;
                } catch (Exception e) {
                    LOG.error("Error invalidating export: " + e.getMessage());
                    return false;
                }
            }
        }).apply(volumeEntity)) {
            //Transaction failed after retries...
            LOG.error("Error invalidating the export record in the DB for volume " + volumeId);
        }

        db.commit();
        reply.set_return(true);
    } catch (NoSuchElementException e) {
        LOG.error("Volume " + volumeId + " not found in DB", e);
        throw new EucalyptusCloudException("Volume " + volumeId + " not found");
    } catch (Exception e) {
        LOG.error("Failed UnexportVolume due to: " + e.getMessage(), e);
        throw new EucalyptusCloudException(e);
    } finally {
        db.rollback();
    }
    return reply;
}

From source file:com.eucalyptus.objectstorage.WalrusManager.java

/**
 * Handles a HEAD request to the bucket. Just returns 200ok if bucket exists and user has access. Otherwise returns 404 if not found or 403 if no accesss.
 * /*from ww  w  .j  a  v a 2 s.  c o m*/
 * @param request
 * @return
 * @throws EucalyptusCloudException
 */
public HeadBucketResponseType headBucket(HeadBucketType request) throws EucalyptusCloudException {
    HeadBucketResponseType reply = (HeadBucketResponseType) request.getReply();
    Context ctx = Contexts.lookup();
    Account account = ctx.getAccount();
    String bucketName = request.getBucket();
    EntityTransaction db = Entities.get(BucketInfo.class);
    try {
        BucketInfo bucket = Entities.uniqueResult(new BucketInfo(bucketName));
        if (ctx.hasAdministrativePrivileges() || (bucket.canRead(account.getAccountNumber())
                && (bucket.isGlobalRead() || Lookups.checkPrivilege(PolicySpec.S3_LISTBUCKET,
                        PolicySpec.VENDOR_S3, PolicySpec.S3_RESOURCE_BUCKET, bucketName, null)))) {
            return reply;
        } else {
            // Insufficient access, return 403
            throw new HeadAccessDeniedException(bucketName);
        }
    } catch (NoSuchElementException e) {
        // Bucket not found return 404
        throw new HeadNoSuchBucketException(bucketName);
    } catch (TransactionException e) {
        LOG.error("DB transaction error looking up bucket " + bucketName + ": " + e.getMessage());
        LOG.debug("DB tranction exception looking up bucket " + bucketName, e);
        throw new EucalyptusCloudException("Internal error doing db lookup for " + bucketName, e);
    } finally {
        // Nothing to commit, always rollback.
        db.rollback();
    }
}

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

public void addPublisherAssertions(AddPublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

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

        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.PublisherAssertion existingPubAssertion = em
                    .find(modelPubAssertion.getClass(), modelPubAssertion.getId());
            boolean persistNewAssertion = true;
            if (existingPubAssertion != null) {
                if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey())
                        && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName())
                        && modelPubAssertion.getKeyValue()
                                .equalsIgnoreCase(existingPubAssertion.getKeyValue())) {
                    // This pub assertion is already been "asserted".  Simply need to set the "check" value on the existing (and persistent) assertion
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey()))
                        existingPubAssertion.setFromCheck("true");
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey()))
                        existingPubAssertion.setToCheck("true");

                    persistNewAssertion = false;
                } else {
                    // Otherwise, it is a new relationship between these entities.  Remove the old one so the new one can be added.
                    // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as 
                    // many relationships as desired (the differentiator would be the keyedRef values).
                    em.remove(existingPubAssertion);
                }
            }

            if (persistNewAssertion) {
                org.apache.juddi.model.BusinessEntity beFrom = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey());
                org.apache.juddi.model.BusinessEntity beTo = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey());
                modelPubAssertion.setBusinessEntityByFromKey(beFrom);
                modelPubAssertion.setBusinessEntityByToKey(beTo);

                modelPubAssertion.setFromCheck("false");
                modelPubAssertion.setToCheck("false");

                em.persist(modelPubAssertion);

                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                    modelPubAssertion.setFromCheck("true");
                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                    modelPubAssertion.setToCheck("true");
            }

        }

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

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

/**
 * Creates an Annotation/*  w  w w  . j a va  2  s . com*/
 * @param label
 * @param context_creation
 * @param hTMLContent
 * @param access
 * @param representsResource
 * @param status
 * @param added
 * @param annotated
 * @return
 */
public boolean createAnnotation(String label, String context_creation, URI access, URI representsResource,
        AnnotationStatus status, Collection<Resource> added, Collection<Resource> annotated,
        Collection<URI> annotatedURIs, Agent _creator) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        Annotation _annotation = new Annotation();
        _annotation.setContextCreation(context_creation);
        _annotation.setCreation(new Date());
        _annotation.setLabel(label);
        _annotation.setAccess(access);
        _annotation.setRepresentsResource(representsResource);
        _annotation.setStatus(status);
        _annotation.setCreator(_creator);
        //_annotation.setAdded(added);
        //_annotation.setAnnotated(annotated);
        //_annotation.setAnnotatedURIs(annotatedURIs);
        //EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (representsResource.getId() != null) {
                URI _synchro_represents_resource = em.find(URI.class, representsResource.getId());
                if (_synchro_represents_resource != null)
                    _annotation.setRepresentsResource(_synchro_represents_resource);
            }
            if (access.getId() != null) {
                URI _synchro_access = em.find(URI.class, access.getId());
                if (_synchro_access != null)
                    _annotation.setAccess(_synchro_access);
            }
            if (status.getId() != null) {
                AnnotationStatus _synchro_status = em.find(AnnotationStatus.class, status.getId());
                if (_synchro_status != null)
                    _annotation.setStatus(_synchro_status);
            }
            if (_creator != null && _creator.getId() != null) {
                Agent _synchro_agent = em.find(_creator.getClass(), _creator.getId());
                if (_synchro_agent != null)
                    _annotation.setCreator(_synchro_agent);
            }
            Collection<Resource> _synchro_added = new ArrayList<Resource>();
            for (Resource _to_add : added) {
                if (_to_add.getId() != null) {
                    Resource _synchro_to_add = em.find(_to_add.getClass(), _to_add.getId());
                    if (_synchro_to_add != null)
                        _synchro_added.add(_synchro_to_add);
                } else
                    _synchro_added.add(_to_add);
            }
            _annotation.setAdded(_synchro_added);
            Collection<Resource> _synchro_annotated = new ArrayList<Resource>();
            for (Resource _to_annotate : annotated) {
                if (_to_annotate.getId() != null) {
                    Resource _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null)
                        _synchro_annotated.add(_synchro_to_annotate);
                } else
                    _synchro_annotated.add(_to_annotate);
            }
            _annotation.setAnnotated(_synchro_annotated);
            Collection<URI> synchro_annotatedURIs = new ArrayList<URI>();
            for (URI _to_annotate : annotatedURIs) {
                if (_to_annotate.getId() != null) {
                    URI _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null) {
                        //empcher qu'une mme URI soit ajoute plusieurs fois  une mme annotation
                        if (!synchro_annotatedURIs.contains(_synchro_to_annotate))
                            synchro_annotatedURIs.add(_synchro_to_annotate);
                    }
                } else
                    synchro_annotatedURIs.add(_to_annotate);
            }
            _annotation.setAnnotatedURIs(synchro_annotatedURIs);
            em.persist(_annotation);
            tx.commit();
            em.close();
            return true;
        } catch (Exception e) {
            System.out.println(
                    "[CreateAnnotation.createAnnotation] fails to create annotation" + " context creation : "
                            + context_creation + " label : " + label + " cause : " + e.getMessage());
            tx.rollback();
            //em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotation.createAnnotation] unable to persist annotation"
                + " not a valid label : " + label);
        return false;
    }
}

From source file:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Creates a job on a remote host.//  www .  ja  v  a  2 s.com
 */
public Job createJob(String host, String serviceType, String operation, List<String> arguments, String payload,
        boolean dispatchable, Job parentJob) throws ServiceRegistryException {
    if (StringUtils.isBlank(host)) {
        throw new IllegalArgumentException("Host can't be null");
    }
    if (StringUtils.isBlank(serviceType)) {
        throw new IllegalArgumentException("Service type can't be null");
    }
    if (StringUtils.isBlank(operation)) {
        throw new IllegalArgumentException("Operation can't be null");
    }

    User currentUser = securityService.getUser();
    Organization currentOrganization = securityService.getOrganization();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        ServiceRegistrationJpaImpl creatingService = getServiceRegistration(em, serviceType, host);
        if (creatingService == null) {
            throw new ServiceRegistryException(
                    "No service registration exists for type '" + serviceType + "' on host '" + host + "'");
        }
        if (creatingService.getHostRegistration().isMaintenanceMode()) {
            logger.warn("Creating a job from {}, which is currently in maintenance mode.",
                    creatingService.getHost());
        } else if (!creatingService.getHostRegistration().isActive()) {
            logger.warn("Creating a job from {}, which is currently inactive.", creatingService.getHost());
        }
        JobJpaImpl job = new JobJpaImpl(currentUser, currentOrganization, creatingService, operation, arguments,
                payload, dispatchable);

        // Bind the given parent job to the new job
        if (parentJob != null) {

            // Get the JPA instance of the parent job
            JobJpaImpl jpaParentJob;
            if (parentJob instanceof JobJpaImpl)
                jpaParentJob = (JobJpaImpl) parentJob;
            else {
                try {
                    jpaParentJob = (JobJpaImpl) getJob(parentJob.getId());
                } catch (NotFoundException e) {
                    logger.error("{} not found in the persitence context", parentJob);
                    throw new ServiceRegistryException(e);
                }
            }
            job.setParentJob(jpaParentJob);

            // Get the JPA instance of the root job
            JobJpaImpl jpaRootJob;
            if (parentJob.getRootJobId() == -1L) {
                jpaRootJob = jpaParentJob;
            } else {
                try {
                    jpaRootJob = (JobJpaImpl) getJob(parentJob.getRootJobId());
                } catch (NotFoundException e) {
                    logger.error("job with id {} not found in the persitence context",
                            parentJob.getRootJobId());
                    throw new ServiceRegistryException(e);
                }
            }
            job.setRootJob(jpaRootJob);
        }

        // if this job is not dispatchable, it must be handled by the host that has created it
        if (dispatchable) {
            job.setStatus(Status.QUEUED);
        } else {
            job.setProcessingHost(creatingService.getHost());
        }

        em.persist(job);
        tx.commit();
        setJobUri(job);
        return job;
    } catch (RollbackException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}