Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

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

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

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 {//from  w  w  w .jav  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:org.opencastproject.serviceregistry.impl.ServiceRegistryJpaImpl.java

/**
 * Find all running jobs on this service and set them to RESET or CANCELED.
 * /*w  w w  .ja  v  a 2 s.co  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.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/* w  w  w  .  j  a v a2 s .  c om*/
 * @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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an Annotation//from   ww w.j  a v a2 s. c  o  m
 * @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:com.eucalyptus.walrus.WalrusFSManager.java

private void doPartCleanup(String bucketName, String objectKey, String uploadId) {
    //get all parts
    PartInfo searchPart = new PartInfo(bucketName, objectKey);
    searchPart.setCleanup(true);/*from  w w w  .ja v  a 2  s  . co m*/
    searchPart.setUploadId(uploadId);
    List<PartInfo> parts;
    EntityTransaction db = Entities.get(PartInfo.class);
    try {
        parts = Entities.query(searchPart);
        if (parts.size() > 0) {
            for (PartInfo part : parts) {
                if (part.getObjectName() != null) {
                    try {
                        storageManager.deleteObject(bucketName, part.getObjectName());
                    } catch (IOException e) {
                        LOG.error("Unable to delete part on disk: " + e.getMessage());
                    }
                }
                LOG.trace("Garbage collecting part: " + part.getBucketName() + "/" + part.getObjectName()
                        + " partNumber: " + part.getPartNumber() + " uploadId: " + part.getUploadId());
                if (part.getGrants() != null) {
                    for (GrantInfo grant : part.getGrants()) {
                        Entities.delete(grant);
                    }
                }
                Entities.delete(part);
            }
        }
    } finally {
        db.commit();
    }

}

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

/**
 * Creates a job on a remote host.//from w  w w. j  a v a  2 s.  c o m
 */
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();
    }
}

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

public DescribeImageAttributeResponseType describeImageAttribute(final DescribeImageAttributeType request)
        throws EucalyptusCloudException {
    DescribeImageAttributeResponseType reply = (DescribeImageAttributeResponseType) request.getReply();

    if (request.getAttribute() != null)
        request.applyAttribute();/* ww  w . j a v  a 2 s.  c o m*/

    final EntityTransaction tx = Entities.get(ImageInfo.class);
    try {
        final ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (!canModifyImage(imgInfo)) {
            throw new EucalyptusCloudException("Not authorized to describe image attribute");
        }
        reply.setImageId(imgInfo.getDisplayName());
        if (request.getKernel() != null) {
            if (imgInfo instanceof MachineImageInfo) {
                if (((MachineImageInfo) imgInfo).getKernelId() != null) {
                    reply.getKernel().add(((MachineImageInfo) imgInfo).getKernelId());
                }
            }
        } else if (request.getRamdisk() != null) {
            if (imgInfo instanceof MachineImageInfo) {
                if (((MachineImageInfo) imgInfo).getRamdiskId() != null) {
                    reply.getRamdisk().add(((MachineImageInfo) imgInfo).getRamdiskId());
                }
            }
        } else if (request.getLaunchPermission() != null) {
            if (imgInfo.getImagePublic()) {
                reply.getLaunchPermission().add(LaunchPermissionItemType.newGroupLaunchPermission());
            }
            for (final String permission : imgInfo.getPermissions())
                reply.getLaunchPermission().add(LaunchPermissionItemType.newUserLaunchPermission(permission));
        } else if (request.getProductCodes() != null) {
            reply.getProductCodes().addAll(imgInfo.getProductCodes());
        } else if (request.getBlockDeviceMapping() != null) {
            if (imgInfo instanceof BlockStorageImageInfo) {
                BlockStorageImageInfo bfebsImage = (BlockStorageImageInfo) imgInfo;
                reply.getBlockDeviceMapping().add(new BlockDeviceMappingItemType(
                        VmInstances.EBS_ROOT_DEVICE_NAME, bfebsImage.getRootDeviceName()));
                reply.getBlockDeviceMapping()
                        .add(new BlockDeviceMappingItemType("root", bfebsImage.getRootDeviceName()));
                int i = 0;
                for (DeviceMapping mapping : bfebsImage.getDeviceMappings()) {
                    if (mapping.getDeviceName().equalsIgnoreCase(bfebsImage.getRootDeviceName())) {
                        continue;
                    }
                    switch (mapping.getDeviceMappingType()) {
                    case blockstorage:
                        BlockStorageDeviceMapping bsdm = (BlockStorageDeviceMapping) mapping;
                        BlockDeviceMappingItemType bdmItem = new BlockDeviceMappingItemType("ebs" + (++i),
                                mapping.getDeviceName());
                        EbsDeviceMapping ebsItem = new EbsDeviceMapping();
                        ebsItem.setSnapshotId(bsdm.getSnapshotId());
                        ebsItem.setVolumeSize(bsdm.getSize());
                        ebsItem.setDeleteOnTermination(bsdm.getDelete());
                        bdmItem.setEbs(ebsItem);
                        reply.getBlockDeviceMapping().add(bdmItem);
                        break;
                    case ephemeral:
                        reply.getBlockDeviceMapping().add(new BlockDeviceMappingItemType(
                                mapping.getVirtualName(), mapping.getDeviceName()));
                        break;
                    default:
                        break;
                    }
                }
            } else {
                reply.getBlockDeviceMapping()
                        .add(new BlockDeviceMappingItemType(VmInstances.EBS_ROOT_DEVICE_NAME, "sda1"));
                reply.getBlockDeviceMapping().add(new BlockDeviceMappingItemType("ephemeral0", "sda2"));
                reply.getBlockDeviceMapping().add(new BlockDeviceMappingItemType("swap", "sda3"));
                reply.getBlockDeviceMapping().add(new BlockDeviceMappingItemType("root", "/dev/sda1"));
            }
        } else if (request.getDescription() != null) {
            if (imgInfo.getDescription() != null) {
                reply.getDescription().add(imgInfo.getDescription());
            }
        } else {
            throw new EucalyptusCloudException("invalid image attribute request.");
        }
    } catch (TransactionException | NoSuchElementException ex) {
        throw new EucalyptusCloudException("Error handling image attribute request: " + ex.getMessage(), ex);
    } finally {
        tx.commit();
    }
    return reply;
}

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

@SuppressWarnings("unchecked")
public SubscriptionResultsList getSubscriptionResults(GetSubscriptionResults body,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

        if (publisher == null) {
            publisher = this.getEntityPublisher(em, body.getAuthInfo());
            new ValidateSubscription(publisher).validateGetSubscriptionResults(em, body);
        }

        org.apache.juddi.model.Subscription modelSubscription = em
                .find(org.apache.juddi.model.Subscription.class, body.getSubscriptionKey());
        SubscriptionFilter subscriptionFilter = null;
        try {
            subscriptionFilter = (SubscriptionFilter) JAXBMarshaller.unmarshallFromString(
                    modelSubscription.getSubscriptionFilter(), JAXBMarshaller.PACKAGE_SUBSCRIPTION);
        } catch (JAXBException e) {
            logger.error("JAXB Exception while unmarshalling subscription filter", e);
            throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
        }
        if (logger.isDebugEnabled())
            logger.debug("filter=" + modelSubscription.getSubscriptionFilter());

        SubscriptionResultsList result = new SubscriptionResultsList();
        result.setChunkToken("0");
        //chunkToken:  Optional element used to retrieve subsequent groups of data when the first invocation of this API indicates more data is available.  This occurs when a chunkToken is returned whose value is not "0" in the validValuesList structure described in the next section.  To retrieve the next chunk of data, the chunkToken returned should be used as an argument to the next invocation of this API.
        result.setCoveragePeriod(body.getCoveragePeriod());

        // The subscription structure is required output for the results
        org.uddi.sub_v3.Subscription apiSubscription = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(modelSubscription, apiSubscription);
        result.setSubscription(apiSubscription);

        Date startPointDate = new Date(
                body.getCoveragePeriod().getStartPoint().toGregorianCalendar().getTimeInMillis());
        Date endPointDate = new Date(
                body.getCoveragePeriod().getEndPoint().toGregorianCalendar().getTimeInMillis());

        Integer chunkData = null;
        if (body.getChunkToken() != null && body.getChunkToken().length() > 0) {
            SubscriptionChunkToken chunkToken = em.find(SubscriptionChunkToken.class, body.getChunkToken());

            if (chunkToken == null)
                throw new InvalidValueException(new ErrorMessage(
                        "errors.getsubscriptionresult.InvalidChunkToken", body.getChunkToken()));
            if (!chunkToken.getSubscriptionKey().equals(chunkToken.getSubscriptionKey()))
                throw new InvalidValueException(new ErrorMessage(
                        "errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken()));
            if (chunkToken.getStartPoint() != null
                    && chunkToken.getStartPoint().getTime() != startPointDate.getTime())
                throw new InvalidValueException(new ErrorMessage(
                        "errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken()));
            if (chunkToken.getEndPoint() != null
                    && chunkToken.getEndPoint().getTime() != endPointDate.getTime())
                throw new InvalidValueException(new ErrorMessage(
                        "errors.getsubscriptionresult.NonMatchingChunkToken", body.getChunkToken()));
            if (chunkToken.getExpiresAfter().before(new Date()))
                throw new InvalidValueException(new ErrorMessage(
                        "errors.getsubscriptionresult.ExpiredChunkToken", body.getChunkToken()));

            chunkData = chunkToken.getData();
            // We've got the data from the chunk token, now it is no longer needed (once it's called, it's used up)
            em.remove(chunkToken);
        }

        if (subscriptionFilter.getFindBinding() != null) {
            //Get the current matching keys
            List<?> currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em);
            // See if there's any missing keys by comparing against the previous matches.  If so, they missing keys are added to the KeyBag and
            // then added to the result
            List<String> missingKeys = getMissingKeys(currentMatchingKeys,
                    modelSubscription.getSubscriptionMatches());
            if (missingKeys != null && missingKeys.size() > 0) {
                KeyBag missingKeyBag = new KeyBag();
                missingKeyBag.setDeleted(true);
                for (String key : missingKeys)
                    missingKeyBag.getBindingKey().add(key);

                result.getKeyBag().add(missingKeyBag);
            }

            // Re-setting the subscription matches to the new matching key collection
            //modelSubscription.getSubscriptionMatches().clear();
            //for (Object key : currentMatchingKeys) {
            //   SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key);
            //   modelSubscription.getSubscriptionMatches().add(subMatch);
            //}

            // Now, finding the necessary entities, within the coverage period limits
            if (modelSubscription.isBrief()) {
                KeyBag resultsKeyBag = new KeyBag();
                for (String key : (List<String>) currentMatchingKeys)
                    resultsKeyBag.getBindingKey().add(key);

                result.getKeyBag().add(resultsKeyBag);
            } else {
                FindBinding fb = subscriptionFilter.getFindBinding();
                org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
                findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers());

                // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default.  User settings for
                // these values don't make sense with the "chunking" feature.
                fb.setListHead(null);
                fb.setMaxRows(null);
                // Setting the start index to the chunkData
                Holder<Integer> subscriptionStartIndex = new Holder<Integer>(chunkData);

                BindingDetail bindingDetail = InquiryHelper.getBindingDetailFromKeys(fb, findQualifiers, em,
                        currentMatchingKeys, startPointDate, endPointDate, subscriptionStartIndex,
                        modelSubscription.getMaxEntities());

                // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null
                // if no more results)
                chunkData = subscriptionStartIndex.value;

                result.setBindingDetail(bindingDetail);
            }
        }
        if (subscriptionFilter.getFindBusiness() != null) {
            //Get the current matching keys
            List<?> currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em);

            List<String> missingKeys = getMissingKeys(currentMatchingKeys,
                    modelSubscription.getSubscriptionMatches());
            if (missingKeys != null && missingKeys.size() > 0) {
                KeyBag missingKeyBag = new KeyBag();
                missingKeyBag.setDeleted(true);
                for (String key : missingKeys)
                    missingKeyBag.getBusinessKey().add(key);

                result.getKeyBag().add(missingKeyBag);
            }

            // Re-setting the subscription matches to the new matching key collection
            //modelSubscription.getSubscriptionMatches().clear();
            //for (Object key : currentMatchingKeys) {
            //   SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key);
            //   modelSubscription.getSubscriptionMatches().add(subMatch);
            //}

            // Now, finding the necessary entities, within the coverage period limits
            if (modelSubscription.isBrief()) {
                KeyBag resultsKeyBag = new KeyBag();
                for (String key : (List<String>) currentMatchingKeys)
                    resultsKeyBag.getBusinessKey().add(key);

                result.getKeyBag().add(resultsKeyBag);
            } else {
                FindBusiness fb = subscriptionFilter.getFindBusiness();
                org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
                findQualifiers.mapApiFindQualifiers(fb.getFindQualifiers());

                // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default.  User settings for
                // these values don't make sense with the "chunking" feature.
                fb.setListHead(null);
                fb.setMaxRows(null);
                // Setting the start index to the chunkData
                Holder<Integer> subscriptionStartIndex = new Holder<Integer>(chunkData);

                BusinessList businessList = InquiryHelper.getBusinessListFromKeys(fb, findQualifiers, em,
                        currentMatchingKeys, startPointDate, endPointDate, subscriptionStartIndex,
                        modelSubscription.getMaxEntities());

                // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null
                // if no more results)
                chunkData = subscriptionStartIndex.value;

                result.setBusinessList(businessList);
            }
        }
        if (subscriptionFilter.getFindService() != null) {
            //Get the current matching keys
            List<?> currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em);
            if (logger.isDebugEnabled())
                logger.debug("current matching keys=" + currentMatchingKeys);
            List<String> missingKeys = getMissingKeys(currentMatchingKeys,
                    modelSubscription.getSubscriptionMatches());
            if (missingKeys != null && missingKeys.size() > 0) {
                KeyBag missingKeyBag = new KeyBag();
                missingKeyBag.setDeleted(true);
                for (String key : missingKeys)
                    missingKeyBag.getServiceKey().add(key);

                result.getKeyBag().add(missingKeyBag);
            }

            // Re-setting the subscription matches to the new matching key collection
            //modelSubscription.getSubscriptionMatches().clear();
            //for (Object key : currentMatchingKeys) {
            //   SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key);
            //   modelSubscription.getSubscriptionMatches().add(subMatch);
            //}

            // Now, finding the necessary entities, within the coverage period limits
            if (modelSubscription.isBrief()) {
                KeyBag resultsKeyBag = new KeyBag();
                for (String key : (List<String>) currentMatchingKeys)
                    resultsKeyBag.getServiceKey().add(key);

                result.getKeyBag().add(resultsKeyBag);
            } else {
                FindService fs = subscriptionFilter.getFindService();
                org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
                findQualifiers.mapApiFindQualifiers(fs.getFindQualifiers());

                // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default.  User settings for
                // these values don't make sense with the "chunking" feature.
                fs.setListHead(null);
                fs.setMaxRows(null);
                // Setting the start index to the chunkData
                Holder<Integer> subscriptionStartIndex = new Holder<Integer>(chunkData);

                ServiceList serviceList = InquiryHelper.getServiceListFromKeys(fs, findQualifiers, em,
                        currentMatchingKeys, startPointDate, endPointDate, subscriptionStartIndex,
                        modelSubscription.getMaxEntities());
                if (serviceList.getServiceInfos() == null
                        || serviceList.getServiceInfos().getServiceInfo().size() == 0) {
                    serviceList = null;
                }
                // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null
                // if no more results)
                chunkData = subscriptionStartIndex.value;

                result.setServiceList(serviceList);
            }
        }
        if (subscriptionFilter.getFindTModel() != null) {
            //Get the current matching keys
            List<?> currentMatchingKeys = getSubscriptionMatches(subscriptionFilter, em);

            List<String> missingKeys = getMissingKeys(currentMatchingKeys,
                    modelSubscription.getSubscriptionMatches());
            if (missingKeys != null && missingKeys.size() > 0) {
                KeyBag missingKeyBag = new KeyBag();
                missingKeyBag.setDeleted(true);
                for (String key : missingKeys)
                    missingKeyBag.getTModelKey().add(key);

                result.getKeyBag().add(missingKeyBag);
            }

            // Re-setting the subscription matches to the new matching key collection
            //modelSubscription.getSubscriptionMatches().clear();
            //for (Object key : currentMatchingKeys) {
            //   SubscriptionMatch subMatch = new SubscriptionMatch(modelSubscription, (String)key);
            //   modelSubscription.getSubscriptionMatches().add(subMatch);
            //}

            // Now, finding the necessary entities, within the coverage period limits
            if (modelSubscription.isBrief()) {
                KeyBag resultsKeyBag = new KeyBag();
                for (String key : (List<String>) currentMatchingKeys)
                    resultsKeyBag.getTModelKey().add(key);

                result.getKeyBag().add(resultsKeyBag);
            } else {
                FindTModel ft = subscriptionFilter.getFindTModel();
                org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
                findQualifiers.mapApiFindQualifiers(ft.getFindQualifiers());

                // To do subscription "chunking", the listHead and maxRows are nulled which will set them to system default.  User settings for
                // these values don't make sense with the "chunking" feature.
                ft.setListHead(null);
                ft.setMaxRows(null);
                // Setting the start index to the chunkData
                Holder<Integer> subscriptionStartIndex = new Holder<Integer>(chunkData);

                // If more results are to be had, chunkData will come out with a value and a new token will be generated below.  Otherwise, it will
                // be null and no token will be generated.
                TModelList tmodelList = InquiryHelper.getTModelListFromKeys(ft, findQualifiers, em,
                        currentMatchingKeys, startPointDate, endPointDate, subscriptionStartIndex,
                        modelSubscription.getMaxEntities());

                // Upon exiting above function, if more results are to be had, the subscriptionStartIndex will contain the latest value (or null
                // if no more results)
                chunkData = subscriptionStartIndex.value;

                result.setTModelList(tmodelList);
            }

        }
        if (subscriptionFilter.getFindRelatedBusinesses() != null) {
            FindRelatedBusinesses findRelatedBusiness = subscriptionFilter.getFindRelatedBusinesses();
            RelatedBusinessesList relatedBusinessList = InquiryHelper
                    .getRelatedBusinessesList(findRelatedBusiness, em, startPointDate, endPointDate);
            result.setRelatedBusinessesList(relatedBusinessList);
        }
        if (subscriptionFilter.getGetBindingDetail() != null) {
            GetBindingDetail getDetail = subscriptionFilter.getGetBindingDetail();

            // Running through the key list here to determine the deleted keys and store the existing entities.
            KeyBag missingKeyBag = new KeyBag();
            missingKeyBag.setDeleted(true);
            List<org.apache.juddi.model.BindingTemplate> existingList = new ArrayList<org.apache.juddi.model.BindingTemplate>(
                    0);
            for (String key : getDetail.getBindingKey()) {
                org.apache.juddi.model.BindingTemplate modelBindingTemplate = em
                        .find(org.apache.juddi.model.BindingTemplate.class, key);
                if (modelBindingTemplate != null)
                    existingList.add(modelBindingTemplate);
                else
                    missingKeyBag.getBindingKey().add(key);
            }
            // Store deleted keys in the results
            if (missingKeyBag.getBindingKey() != null && missingKeyBag.getBindingKey().size() > 0)
                result.getKeyBag().add(missingKeyBag);

            KeyBag resultsKeyBag = new KeyBag();
            BindingDetail bindingDetail = new BindingDetail();

            // Set the currentIndex to 0 or the value of the chunkData
            int currentIndex = 0;
            if (chunkData != null)
                currentIndex = chunkData;

            int returnedRowCount = 0;
            while (currentIndex < existingList.size()) {

                org.apache.juddi.model.BindingTemplate modelBindingTemplate = existingList.get(currentIndex);

                if (startPointDate.after(modelBindingTemplate.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (endPointDate.before(modelBindingTemplate.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (modelSubscription.isBrief()) {
                    resultsKeyBag.getBindingKey().add(modelBindingTemplate.getEntityKey());
                } else {
                    org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate();
                    MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate);
                    bindingDetail.getBindingTemplate().add(apiBindingTemplate);

                    returnedRowCount++;
                }

                // If the returned rows equals the max allowed, we can end the loop.
                if (modelSubscription.getMaxEntities() != null) {
                    if (returnedRowCount == modelSubscription.getMaxEntities())
                        break;
                }

                currentIndex++;
            }

            // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with.
            // A non-null value of chunk data will cause a chunk token to be generated. 
            if (currentIndex < (existingList.size() - 1))
                chunkData = currentIndex + 1;
            else
                chunkData = null;

            if (modelSubscription.isBrief())
                result.getKeyBag().add(resultsKeyBag);
            else
                result.setBindingDetail(bindingDetail);

        }
        if (subscriptionFilter.getGetBusinessDetail() != null) {
            GetBusinessDetail getDetail = subscriptionFilter.getGetBusinessDetail();

            // Running through the key list here to determine the deleted keys and store the existing entities.
            KeyBag missingKeyBag = new KeyBag();
            missingKeyBag.setDeleted(true);
            List<org.apache.juddi.model.BusinessEntity> existingList = new ArrayList<org.apache.juddi.model.BusinessEntity>(
                    0);
            for (String key : getDetail.getBusinessKey()) {
                org.apache.juddi.model.BusinessEntity modelBusinessEntity = em
                        .find(org.apache.juddi.model.BusinessEntity.class, key);
                if (modelBusinessEntity != null)
                    existingList.add(modelBusinessEntity);
                else
                    missingKeyBag.getBusinessKey().add(key);
            }
            // Store deleted keys in the results
            if (missingKeyBag.getBusinessKey() != null && missingKeyBag.getBusinessKey().size() > 0)
                result.getKeyBag().add(missingKeyBag);

            KeyBag resultsKeyBag = new KeyBag();
            BusinessDetail businessDetail = new BusinessDetail();

            // Set the currentIndex to 0 or the value of the chunkData
            int currentIndex = 0;
            if (chunkData != null)
                currentIndex = chunkData;

            int returnedRowCount = 0;
            while (currentIndex < existingList.size()) {

                org.apache.juddi.model.BusinessEntity modelBusinessEntity = existingList.get(currentIndex);

                if (startPointDate.after(modelBusinessEntity.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (endPointDate.before(modelBusinessEntity.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (modelSubscription.isBrief()) {
                    resultsKeyBag.getBusinessKey().add(modelBusinessEntity.getEntityKey());
                } else {
                    org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity();
                    MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity);
                    businessDetail.getBusinessEntity().add(apiBusinessEntity);

                    returnedRowCount++;
                }

                // If the returned rows equals the max allowed, we can end the loop.
                if (modelSubscription.getMaxEntities() != null) {
                    if (returnedRowCount == modelSubscription.getMaxEntities())
                        break;
                }

                currentIndex++;
            }

            // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with.
            // A non-null value of chunk data will cause a chunk token to be generated. 
            if (currentIndex < (existingList.size() - 1))
                chunkData = currentIndex + 1;
            else
                chunkData = null;

            if (modelSubscription.isBrief())
                result.getKeyBag().add(resultsKeyBag);
            else
                result.setBusinessDetail(businessDetail);

        }
        if (subscriptionFilter.getGetServiceDetail() != null) {
            GetServiceDetail getDetail = subscriptionFilter.getGetServiceDetail();

            // Running through the key list here to determine the deleted keys and store the existing entities.
            KeyBag missingKeyBag = new KeyBag();
            missingKeyBag.setDeleted(true);
            List<org.apache.juddi.model.BusinessService> existingList = new ArrayList<org.apache.juddi.model.BusinessService>(
                    0);
            for (String key : getDetail.getServiceKey()) {
                org.apache.juddi.model.BusinessService modelBusinessService = em
                        .find(org.apache.juddi.model.BusinessService.class, key);
                if (modelBusinessService != null)
                    existingList.add(modelBusinessService);
                else
                    missingKeyBag.getBusinessKey().add(key);
            }
            // Store deleted keys in the results
            if (missingKeyBag.getServiceKey() != null && missingKeyBag.getServiceKey().size() > 0)
                result.getKeyBag().add(missingKeyBag);

            KeyBag resultsKeyBag = new KeyBag();
            ServiceDetail serviceDetail = new ServiceDetail();

            // Set the currentIndex to 0 or the value of the chunkData
            int currentIndex = 0;
            if (chunkData != null)
                currentIndex = chunkData;

            int returnedRowCount = 0;
            while (currentIndex < existingList.size()) {

                org.apache.juddi.model.BusinessService modelBusinessService = existingList.get(currentIndex);

                if (startPointDate.after(modelBusinessService.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (endPointDate.before(modelBusinessService.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (modelSubscription.isBrief()) {
                    resultsKeyBag.getServiceKey().add(modelBusinessService.getEntityKey());
                } else {
                    org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService();
                    MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService);
                    serviceDetail.getBusinessService().add(apiBusinessService);

                    returnedRowCount++;
                }

                // If the returned rows equals the max allowed, we can end the loop.
                if (modelSubscription.getMaxEntities() != null) {
                    if (returnedRowCount == modelSubscription.getMaxEntities())
                        break;
                }

                currentIndex++;
            }

            // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with.
            // A non-null value of chunk data will cause a chunk token to be generated. 
            if (currentIndex < (existingList.size() - 1))
                chunkData = currentIndex + 1;
            else
                chunkData = null;

            if (modelSubscription.isBrief())
                result.getKeyBag().add(resultsKeyBag);
            else
                result.setServiceDetail(serviceDetail);

        }
        if (subscriptionFilter.getGetTModelDetail() != null) {
            GetTModelDetail getDetail = subscriptionFilter.getGetTModelDetail();

            // Running through the key list here to determine the deleted keys and store the existing entities.
            KeyBag missingKeyBag = new KeyBag();
            missingKeyBag.setDeleted(true);
            List<org.apache.juddi.model.Tmodel> existingList = new ArrayList<org.apache.juddi.model.Tmodel>(0);
            for (String key : getDetail.getTModelKey()) {
                org.apache.juddi.model.Tmodel modelTModel = em.find(org.apache.juddi.model.Tmodel.class, key);
                if (modelTModel != null)
                    existingList.add(modelTModel);
                else
                    missingKeyBag.getTModelKey().add(key);
            }
            // Store deleted keys in the results
            if (missingKeyBag.getTModelKey() != null && missingKeyBag.getTModelKey().size() > 0)
                result.getKeyBag().add(missingKeyBag);

            KeyBag resultsKeyBag = new KeyBag();
            TModelDetail tmodelDetail = new TModelDetail();

            // Set the currentIndex to 0 or the value of the chunkData
            int currentIndex = 0;
            if (chunkData != null)
                currentIndex = chunkData;

            int returnedRowCount = 0;
            while (currentIndex < existingList.size()) {

                org.apache.juddi.model.Tmodel modelTModel = existingList.get(currentIndex);

                if (startPointDate.after(modelTModel.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (endPointDate.before(modelTModel.getModifiedIncludingChildren())) {
                    currentIndex++;
                    continue;
                }

                if (modelSubscription.isBrief()) {
                    resultsKeyBag.getTModelKey().add(modelTModel.getEntityKey());
                } else {
                    org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel();
                    MappingModelToApi.mapTModel(modelTModel, apiTModel);
                    tmodelDetail.getTModel().add(apiTModel);

                    returnedRowCount++;
                }

                // If the returned rows equals the max allowed, we can end the loop.
                if (modelSubscription.getMaxEntities() != null) {
                    if (returnedRowCount == modelSubscription.getMaxEntities())
                        break;
                }

                currentIndex++;
            }

            // If the loop was broken prematurely (max row count hit) we set the chunk data to the next index to start with.
            // A non-null value of chunk data will cause a chunk token to be generated. 
            if (currentIndex < (existingList.size() - 1))
                chunkData = currentIndex + 1;
            else
                chunkData = null;

            if (modelSubscription.isBrief())
                result.getKeyBag().add(resultsKeyBag);
            else
                result.setTModelDetail(tmodelDetail);

        }
        if (subscriptionFilter.getGetAssertionStatusReport() != null) {
            // The coverage period doesn't apply here (basically because publisher assertions don't keep operational info).

            GetAssertionStatusReport getAssertionStatusReport = subscriptionFilter
                    .getGetAssertionStatusReport();

            List<AssertionStatusItem> assertionList = PublicationHelper.getAssertionStatusItemList(publisher,
                    getAssertionStatusReport.getCompletionStatus(), em);

            AssertionStatusReport assertionStatusReport = new AssertionStatusReport();
            for (AssertionStatusItem asi : assertionList)
                assertionStatusReport.getAssertionStatusItem().add(asi);

            result.setAssertionStatusReport(assertionStatusReport);
        }

        // If chunkData contains non-null data, a new token must be created and the token returned in the results
        if (chunkData != null) {
            String chunkToken = CHUNK_TOKEN_PREFIX + UUID.randomUUID();
            SubscriptionChunkToken newChunkToken = new SubscriptionChunkToken(chunkToken);
            newChunkToken.setSubscriptionKey(body.getSubscriptionKey());
            newChunkToken.setStartPoint(startPointDate);
            newChunkToken.setEndPoint(endPointDate);
            newChunkToken.setData(chunkData);

            int chunkExpirationMinutes = DEFAULT_CHUNKEXPIRATION_MINUTES;
            try {
                chunkExpirationMinutes = AppConfig.getConfiguration()
                        .getInt(Property.JUDDI_SUBSCRIPTION_CHUNKEXPIRATION_MINUTES);
            } catch (ConfigurationException ce) {
                throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval"));
            }
            newChunkToken.setExpiresAfter(
                    new Date(System.currentTimeMillis() + ((long) chunkExpirationMinutes * 60L * 1000L)));

            em.persist(newChunkToken);

            result.setChunkToken(chunkToken);
        }

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

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