Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

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 {/* ww  w .  j av  a2 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();
    }
}

From source file:op.care.prescription.PnlPrescription.java

private CollapsiblePane createCP4(final Prescription prescription) {
    /***/*from w w  w.  j a v a 2s .  c o m*/
     *                          _        ____ ____  _  _    ______                          _       _   _           __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ _ __ ___  ___  ___ _ __(_)_ __ | |_(_) ___  _ __\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) | '__/ _ \/ __|/ __| '__| | '_ \| __| |/ _ \| '_ \| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  __/| | |  __/\__ \ (__| |  | | |_) | |_| | (_) | | | | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_|   |_|  \___||___/\___|_|  |_| .__/ \__|_|\___/|_| |_| |
     *                                                     \_\                               |_|                    /_/
     */
    final String key = prescription.getID() + ".xprescription";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    final CollapsiblePane cpPres = cpMap.get(key);

    String title = "<html><table border=\"0\">" + "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">"
            + prescription.getPITAsHTML() + "</td>" + "<td width=\"380\" align=\"left\">" + "<font size=+1>"
            + PrescriptionTools.getShortDescription(prescription) + "</font>"
            + PrescriptionTools.getDoseAsHTML(prescription)
            + PrescriptionTools.getInventoryInformationAsHTML(prescription) + "</td>"
            + "<td width=\"200\" align=\"left\">" + PrescriptionTools.getOriginalPrescription(prescription)
            + PrescriptionTools.getRemark(prescription) + "</td>";

    if (!prescription.getCommontags().isEmpty()) {
        title += "<tr>" + "    <td colspan=\"3\">" + CommontagsTools.getAsHTML(prescription.getCommontags(),
                SYSConst.html_16x16_tagPurple_internal) + "</td>" + "  </tr>";
    }

    if (PrescriptionTools.isAnnotationNecessary(prescription)) {
        title += "<tr>" + "    <td colspan=\"3\">" + PrescriptionTools.getAnnontationsAsHTML(prescription)
                + "</td>" + "  </tr>";
    }

    title += "</table>" + "</html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
    cpPres.setCollapsible(false);
    cptitle.getButton().setIcon(getIcon(prescription));

    cpPres.setTitleLabelComponent(cptitle.getMain());
    cpPres.setSlidingDirection(SwingConstants.SOUTH);

    if (!prescription.getAttachedFilesConnections().isEmpty()) {
        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = new JButton(
                Integer.toString(prescription.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
        btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
        btnFiles.setForeground(Color.BLUE);
        btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnFiles.setFont(SYSConst.ARIAL18BOLD);
        btnFiles.setPressedIcon(SYSConst.icon22Pressed);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
        btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnFiles.setContentAreaFilled(false);
        btnFiles.setBorder(null);

        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                // checked for acls
                Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                        internalClassID) ? null : new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                final Prescription myPrescription = em.find(Prescription.class,
                                        prescription.getID());
                                em.close();
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                        };
                new DlgFiles(prescription, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        cptitle.getRight().add(btnFiles);
    }

    if (!prescription.getAttachedProcessConnections().isEmpty()) {
        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = new JButton(
                Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
        btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
        btnProcess.setForeground(Color.YELLOW);
        btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnProcess.setFont(SYSConst.ARIAL18BOLD);
        btnProcess.setPressedIcon(SYSConst.icon22Pressed);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
        btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnProcess.setContentAreaFilled(false);
        btnProcess.setBorder(null);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSPRE2PROCESS> attached = new ArrayList<SYSPRE2PROCESS>(
                                    prescription.getAttachedProcessConnections());
                            for (SYSPRE2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getPrescription().getAttachedProcessConnections()
                                            .remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myPrescription)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSPRE2PROCESS myLinkObject = em
                                            .merge(new SYSPRE2PROCESS(myQProcess, myPrescription));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedPrescriptionConnections().add(myLinkObject);
                                    myPrescription.getAttachedProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }

                    }
                });
            }
        });
        // checked for acls
        btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
        cptitle.getRight().add(btnProcess);
    }

    /***
     *      __  __
     *     |  \/  | ___ _ __  _   _
     *     | |\/| |/ _ \ '_ \| | | |
     *     | |  | |  __/ | | | |_| |
     *     |_|  |_|\___|_| |_|\__,_|
     *
     */
    final JButton btnMenu = new JButton(SYSConst.icon22menu);
    btnMenu.setPressedIcon(SYSConst.icon22Pressed);
    btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
    btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    btnMenu.setContentAreaFilled(false);
    btnMenu.setBorder(null);
    btnMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JidePopup popup = new JidePopup();
            popup.setMovable(false);
            popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
            popup.setOwner(btnMenu);
            popup.removeExcludedComponent(btnMenu);
            JPanel pnl = getMenu(prescription);
            popup.getContentPane().add(pnl);
            popup.setDefaultFocusComponent(pnl);

            GUITools.showPopup(popup, SwingConstants.WEST);
        }
    });
    cptitle.getRight().add(btnMenu);

    cpPres.setHorizontalAlignment(SwingConstants.LEADING);
    cpPres.setOpaque(false);

    return cpPres;
}

From source file:it.drwolf.ridire.session.async.Mapper.java

@SuppressWarnings("unchecked")
private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager)
        throws IOException, InterruptedException {
    String workingDirName = System.getProperty("java.io.tmpdir");
    String userDir = System.getProperty("user.dir");
    byte[] buf = new byte[Mapper.BUFLENGTH];
    int count = 0;
    GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((count = gzis.read(buf)) != -1) {
        baos.write(buf, 0, count);//from  w w w  .ja  v a2  s  . c o  m
    }
    gzis.close();
    baos.close();
    byte[] byteArray = baos.toByteArray();
    String uuid = UUID.randomUUID().toString();
    String pdfFileName = uuid + ".pdf";
    String htmlFileName = uuid + ".html";
    File tmpDir = new File(workingDirName);
    String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName;
    File fileToConvert = new File(tmpDir, pdfFileName);
    FileUtils.writeByteArrayToFile(fileToConvert, byteArray);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY);
    CommandLine commandLine = CommandLine.parse(cp.getCommandValue());
    commandLine.addArgument("-c");
    commandLine.addArgument("-i");
    commandLine.addArgument(fileToConvert.getAbsolutePath());
    commandLine.addArgument(htmlFileNameCompletePath);
    executor.setExitValue(0);
    executor.execute(commandLine);
    try {
        FileUtils.moveFileToDirectory(
                new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false);
    } catch (IOException e) {
    }
    cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY);
    commandLine = CommandLine
            .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue());
    commandLine.addArgument(htmlFileNameCompletePath);
    commandLine.addArgument("39");
    commandLine.addArgument("6");
    commandLine.addArgument("5");
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
    ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null);
    executor.setStreamHandler(executeStreamHandler);
    int exitValue = executor.execute(commandLine);
    String htmlString = null;
    if (exitValue == 0) {
        htmlString = baosStdOut.toString();
    }
    FileUtils.deleteQuietly(new File(htmlFileNameCompletePath));
    PrefixFileFilter pff = new PrefixFileFilter(uuid);
    for (File f : FileUtils.listFiles(tmpDir, pff, null)) {
        FileUtils.deleteQuietly(f);
    }
    if (htmlString != null) {
        htmlString = htmlString.replaceAll("&nbsp;", " ");
        htmlString = htmlString.replaceAll("<br.*?>", " ");
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(htmlString.getBytes());
        String encoding = charsetDetector.detect().getName();
        return new StringWithEncoding(htmlString, encoding);
    }
    return null;
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Retrieves the current model and checks if its lifetime is already exceeded.
 * In this case the model's TaskState will be set to {@code failed} and a {@link FailedException} is thrown,
 * which will stop the the main loop in {@code execute()}.
 *
 * Otherwise, the model's TaskState is set to {@code newState} and {@link #transit(TaskState, AbstractTask)}
 * will be invoked,//  ww w .  j a v a  2 s .c o m
 * which calls a method corresponding to the TaskState {@code newState} and throws a {@code TransitException} after its
 * execution specifying the next TaskSate value for the model.
 *
 * The model is made persistent by the EntityManager and the changed model will be 
 * commited to the database.
 * If something goes wrong while commiting the new model, a stable rollback is assured.
 *
 * @param newState the new TaskState for the model
 */
@SuppressWarnings({ "CaughtExceptionImmediatelyRethrown", "ThrowableInstanceNeverThrown" })
private void transit(final TaskState newState) {

    if (getCancelled()) {
        log.debug("cancelled");
        throw new StopException(TaskState.IN_PROGRESS_UNKNOWN);
    }

    EntityManager em = getEntityManager();
    @NotNull
    AbstractTask model = getModel();

    // this throws a stop exception on timeout
    if (!(TaskState.FINISHED.equals(newState) || TaskState.FAILED.equals(newState)))
        checkTimeout(model, em);

    try {
        em.getTransaction().begin();
        if (newState != null) {
            if (!em.contains(model)) {
                log.debug("model not in EntityManager");
                try {
                    try {
                        em.persist(model);
                    } catch (EntityExistsException e) {
                        log.debug("persisting failed merging", e);
                        rewindTransaction(em.getTransaction());
                        em.merge(model);
                    }
                } catch (RuntimeException e2) {
                    log.debug("probably persisting and merging failed", e2);
                    rewindTransaction(em.getTransaction());
                    final @NotNull AbstractTask newModel = em.find(AbstractTask.class, model.getId());
                    model.mold(newModel);
                    newModel.refresh(em);
                    setModel(newModel);
                    model = getModel();
                    log.debug("completed renewing of model");
                }
            }
        }

        model.transit(newState);

        boolean committed = false;
        try {
            em.getTransaction().commit();
            //                em.flush( );
            committed = true;
        } catch (Exception e) {
            log.debug("commit of transit (" + newState.name() + ") model failed ", e);
            try {
                rewindTransaction(em.getTransaction());
                // if this point is reached s.th. is terribly foobared
                // restore backup and fail
                model = Copier.copy(false, backup);
                em.merge(model);
                // backup should be clean so commit mustn't fail.
                model.fail(e);
                em.getTransaction().commit();
            } catch (Exception e2) {
                log.debug("restoring previous version failed", e2);
                try {
                    // refresh em for final commit
                    EntityManagerAux.rollbackAndClose(em);
                } catch (RuntimeException e3) {
                    log.debug("rollback old em failed", e3);
                }

                EntityManager nem = emf.createEntityManager();
                TxFrame tx = new TxFrame(nem);
                try {
                    log.debug("loading fresh model");
                    model = nem.find(model.getClass(), backup.getId());
                    boolean unkown = (model == null);
                    model = Copier.copy(false, backup);
                    model.fail(e2);
                    if (unkown)
                        nem.persist(model);
                    //     else
                    //         nem.merge( model );
                    tx.commit();
                    setModel(model);
                } catch (RuntimeException e3) {
                    log.debug("exception during refresh: ", e3);
                    throw e3;
                } finally {
                    tx.finish();
                    setOwnEntityManager(nem);
                    em = nem;
                }
            }
        }

        // if model could be commited it has a clean state
        // refresh backup
        if (committed)
            setBackup(Copier.copy(false, model));

        final TaskState modelState = model.getState();
        refreshTaskResource();
        //noinspection HardcodedFileSeparator
        trace("on" + modelState + "()", null);
        transit(modelState, model);
    }
    // for debugging
    catch (RuntimeException e) {
        throw e;
    } finally {
        try {
            // for debuggin'
            boolean ta = em.getTransaction().isActive();
            if (ta) {
                log.debug("final rollback");
                em.getTransaction().rollback();
            }
        } catch (Exception e) {
            log.debug("final rollback failed", e);
        }
    }
}

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

public void setPublisherAssertions(String authInfo, Holder<List<PublisherAssertion>> publisherAssertion)
        throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  w ww.j av a 2 s .  co m
        tx.begin();

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

        new ValidatePublish(publisher).validateSetPublisherAssertions(em, publisherAssertion);

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

        // First, wipe out all previous assertions associated with this publisher
        DeletePublisherAssertionByBusinessQuery.delete(em, businessKeysFound);

        // Slate is clean for all assertions involving this publisher, now we simply need to add the new ones (and they will all be "new").
        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = publisherAssertion.value;
        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.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.SET_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SET_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:de.egore911.opengate.services.PilotService.java

@POST
@Path("/register")
@Produces("application/json")
@Documentation("Register a new pilot. This will at first verify the login and email are "
        + "unique and the email is valid. After this it will register the pilot and send "
        + "and email to him to verify the address. The 'verify' will finalize the registration. "
        + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
        + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
        + "error occured an HTTP 500 will be sent.")
public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
        @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
    JSONObject jsonObject = new JSONObject();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Number n = (Number) em
            .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
            .setParameter("login", login).getSingleResult();
    if (n.intValue() > 0) {
        try {/*  w ww  . j  a va 2  s  . c  om*/
            StatusHelper.failed(jsonObject, "Duplicate login");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
            .setParameter("email", email).getSingleResult();
    if (n.intValue() > 0) {
        try {
            StatusHelper.failed(jsonObject, "Duplicate email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    InternetAddress recipient;
    try {
        recipient = new InternetAddress(email, login);
    } catch (UnsupportedEncodingException e1) {
        try {
            StatusHelper.failed(jsonObject, "Invalid email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Faction faction;
    try {
        faction = em.find(Faction.class, factionId);
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Invalid faction");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Vessel vessel;
    try {
        vessel = (Vessel) em
                .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                        + "order by vessel.techLevel asc")
                .setParameter("faction", faction).setMaxResults(1).getSingleResult();
        // TODO assign initical equipment as well
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Faction has no vessel");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    String passwordHash;
    String password = randomText();
    try {
        passwordHash = hashPassword(password);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    em.getTransaction().begin();
    try {
        Pilot pilot = new Pilot();
        pilot.setLogin(login);
        pilot.setCreated(new Date());
        pilot.setPasswordHash(passwordHash);
        pilot.setEmail(email);
        pilot.setFaction(faction);
        pilot.setVessel(vessel);
        pilot.setVerificationCode(randomText());
        em.persist(pilot);
        em.getTransaction().commit();
        try {
            // send e-mail to registered user containing the new password

            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                    + pilot.getLogin()
                    + " with your e-mail adress. The following credentials can be used for your account:\n"
                    + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                    + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                    + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                msg.addRecipient(Message.RecipientType.TO, recipient);
                msg.setSubject("Your Example.com account has been activated");
                msg.setText(msgBody);
                Transport.send(msg);

            } catch (AddressException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (MessagingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (UnsupportedEncodingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

            StatusHelper.ok(jsonObject);
            jsonObject.put("id", pilot.getKey().getId());
            jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
            // TODO properly wrap the vessel and its equipment/cargo
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (NoResultException e) {
        return Response.status(Status.FORBIDDEN).build();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

From source file:op.care.reports.PnlReport.java

private JPanel createContentPanel4Day(LocalDate day) {
    //        OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage("misc.msg.wait", progress, progressMax));
    //        progress++;

    final String key = DateFormat.getDateInstance().format(day.toDate());
    synchronized (contentmap) {
        if (contentmap.containsKey(key)) {
            return contentmap.get(key);
        }/*from w ww. j  av a 2 s . co m*/
    }
    final JPanel dayPanel = new JPanel(new VerticalLayout());
    dayPanel.setOpaque(false);
    synchronized (valuecache) {
        if (!valuecache.containsKey(key)) {
            valuecache.put(key, NReportTools.getNReports4Day(resident, day));
        }

        int i = 0; // for zebra pattern
        for (final NReport nreport : valuecache.get(key)) {

            if (tbShowReplaced.isSelected() || !nreport.isObsolete()) {

                String title = SYSTools.toHTMLForScreen(SYSConst.html_table(SYSConst
                        .html_table_tr("<td width=\"800\" align=\"left\">" + "<b><p>"
                                + (nreport.isObsolete() ? SYSConst.html_16x16_Eraser_internal : "")
                                + (nreport.isReplacement() ? SYSConst.html_16x16_Edited_internal : "")
                                + DateFormat.getTimeInstance(DateFormat.SHORT).format(nreport.getPit()) + " "
                                + SYSTools.xx("misc.msg.Time.short") + ", " + nreport.getMinutes() + " "
                                + SYSTools.xx("misc.msg.Minute(s)") + ", " + nreport.getUser().getFullname()
                                + (nreport.getCommontags().isEmpty() ? ""
                                        : " " + CommontagsTools.getAsHTML(nreport.getCommontags(),
                                                SYSConst.html_16x16_tagPurple_internal))
                                + "</p></b></td>")
                        + SYSConst.html_table_tr("<td width=\"800\" align=\"left\">"
                                + SYSTools.replace(nreport.getText(), "\n", "<br/>", false) + "</td>"),
                        "0"));

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title), null);
                pnlSingle.getButton().addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        GUITools.showPopup(GUITools.getHTMLPopup(pnlSingle.getButton(),
                                NReportTools.getInfoAsHTML(nreport)), SwingConstants.NORTH);
                    }
                });

                if (!nreport.getAttachedFilesConnections().isEmpty()) {
                    /***
                     *      _     _         _____ _ _
                     *     | |__ | |_ _ __ |  ___(_) | ___  ___
                     *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
                     *     | |_) | |_| | | |  _| | | |  __/\__ \
                     *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
                     *
                     */
                    final JButton btnFiles = new JButton(
                            Integer.toString(nreport.getAttachedFilesConnections().size()),
                            SYSConst.icon22greenStar);
                    btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
                    btnFiles.setForeground(Color.BLUE);
                    btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
                    btnFiles.setFont(SYSConst.ARIAL18BOLD);
                    btnFiles.setPressedIcon(SYSConst.icon22Pressed);
                    btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
                    btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnFiles.setContentAreaFilled(false);
                    btnFiles.setBorder(null);

                    btnFiles.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                                    internalClassID) ? null : new Closure() {
                                        @Override
                                        public void execute(Object o) {
                                            EntityManager em = OPDE.createEM();
                                            final NReport myReport = em.find(NReport.class, nreport.getID());
                                            em.close();

                                            final String keyNewDay = DateFormat.getDateInstance()
                                                    .format(myReport.getPit());

                                            synchronized (contentmap) {
                                                contentmap.remove(keyNewDay);
                                            }
                                            synchronized (linemap) {
                                                linemap.remove(nreport);
                                            }

                                            synchronized (valuecache) {
                                                valuecache.get(keyNewDay).remove(nreport);
                                                valuecache.get(keyNewDay).add(myReport);
                                                Collections.sort(valuecache.get(keyNewDay));
                                            }

                                            createCP4Day(new LocalDate(myReport.getPit()));

                                            buildPanel();
                                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                        }
                                    };
                            new DlgFiles(nreport, fileHandleClosure);
                        }
                    });
                    btnFiles.setEnabled(OPDE.isFTPworking());
                    pnlSingle.getRight().add(btnFiles);
                }

                if (!nreport.getAttachedQProcessConnections().isEmpty()) {
                    /***
                     *      _     _         ____
                     *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
                     *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
                     *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
                     *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
                     *
                     */
                    final JButton btnProcess = new JButton(
                            Integer.toString(nreport.getAttachedQProcessConnections().size()),
                            SYSConst.icon22redStar);
                    btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
                    btnProcess.setForeground(Color.YELLOW);
                    btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
                    btnProcess.setFont(SYSConst.ARIAL18BOLD);
                    btnProcess.setPressedIcon(SYSConst.icon22Pressed);
                    btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
                    btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnProcess.setContentAreaFilled(false);
                    btnProcess.setBorder(null);
                    btnProcess.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgProcessAssign(nreport, new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o == null) {
                                        return;
                                    }
                                    Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                                    ArrayList<QProcess> assigned = result.getFirst();
                                    ArrayList<QProcess> unassigned = result.getSecond();

                                    EntityManager em = OPDE.createEM();

                                    try {
                                        em.getTransaction().begin();

                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        NReport myReport = em.merge(nreport);
                                        em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                        ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>(
                                                myReport.getAttachedQProcessConnections());
                                        for (SYSNR2PROCESS linkObject : attached) {
                                            if (unassigned.contains(linkObject.getQProcess())) {
                                                linkObject.getQProcess().getAttachedNReportConnections()
                                                        .remove(linkObject);
                                                linkObject.getNReport().getAttachedQProcessConnections()
                                                        .remove(linkObject);
                                                em.merge(new PReport(
                                                        SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT)
                                                                + ": " + nreport.getTitle() + " ID: "
                                                                + nreport.getID(),
                                                        PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                                        linkObject.getQProcess()));

                                                em.remove(linkObject);
                                            }
                                        }
                                        attached.clear();

                                        for (QProcess qProcess : assigned) {
                                            java.util.List<QProcessElement> listElements = qProcess
                                                    .getElements();
                                            if (!listElements.contains(myReport)) {
                                                QProcess myQProcess = em.merge(qProcess);
                                                SYSNR2PROCESS myLinkObject = em
                                                        .merge(new SYSNR2PROCESS(myQProcess, myReport));
                                                em.merge(new PReport(
                                                        SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT)
                                                                + ": " + nreport.getTitle() + " ID: "
                                                                + nreport.getID(),
                                                        PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                                qProcess.getAttachedNReportConnections().add(myLinkObject);
                                                myReport.getAttachedQProcessConnections().add(myLinkObject);
                                            }
                                        }

                                        em.getTransaction().commit();

                                        final String keyNewDay = DateFormat.getDateInstance()
                                                .format(myReport.getPit());

                                        synchronized (contentmap) {
                                            contentmap.remove(keyNewDay);
                                        }
                                        synchronized (linemap) {
                                            linemap.remove(nreport);
                                        }

                                        synchronized (valuecache) {
                                            valuecache.get(keyNewDay).remove(nreport);
                                            valuecache.get(keyNewDay).add(myReport);
                                            Collections.sort(valuecache.get(keyNewDay));
                                        }

                                        createCP4Day(new LocalDate(myReport.getPit()));

                                        buildPanel();
                                        GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        } else {
                                            reloadDisplay(true);
                                        }
                                    } catch (RollbackException ole) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }

                                }
                            });
                        }
                    });
                    btnProcess.setEnabled(
                            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
                    pnlSingle.getRight().add(btnProcess);
                }

                /***
                 *      __  __
                 *     |  \/  | ___ _ __  _   _
                 *     | |\/| |/ _ \ '_ \| | | |
                 *     | |  | |  __/ | | | |_| |
                 *     |_|  |_|\___|_| |_|\__,_|
                 *
                 */
                final JButton btnMenu = new JButton(SYSConst.icon22menu);
                btnMenu.setPressedIcon(SYSConst.icon22Pressed);
                btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
                btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnMenu.setContentAreaFilled(false);
                btnMenu.setBorder(null);
                btnMenu.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JidePopup popup = new JidePopup();
                        popup.setMovable(false);
                        popup.getContentPane()
                                .setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                        popup.setOwner(btnMenu);
                        popup.removeExcludedComponent(btnMenu);
                        JPanel pnl = getMenu(nreport);
                        popup.getContentPane().add(pnl);
                        popup.setDefaultFocusComponent(pnl);

                        GUITools.showPopup(popup, SwingConstants.WEST);
                    }
                });
                btnMenu.setEnabled(!nreport.isObsolete());
                pnlSingle.getRight().add(btnMenu);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;

                dayPanel.add(zebra);
                linemap.put(nreport, pnlSingle.getMain());
            }
        }
    }
    synchronized (contentmap) {
        contentmap.put(key, dayPanel);
    }
    return dayPanel;
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public com.enioka.jqm.api.JobInstance getJob(int idJob) {
    EntityManager em = null;
    try {/*from w w w  .j  a va 2  s .c  o  m*/
        // Three steps: first, query History as:
        // * this is supposed to be the most frequent query.
        // * we try to avoid hitting the queues if possible
        // Second, query live queues
        // Third, query history again (because a JI may have ended between the first two queries, so we may miss a JI)
        // Outside this case, this third query will be very rare, as the method is always called with an ID that cannot be
        // guessed as its only parameter, so the existence of the JI is nearly always a given.
        em = getEm();
        History h = em.find(History.class, idJob);
        com.enioka.jqm.api.JobInstance res = null;
        if (h != null) {
            res = getJob(h, em);
        } else {
            JobInstance ji = em.find(JobInstance.class, idJob);
            if (ji != null) {
                res = getJob(ji, em);
            } else {
                h = em.find(History.class, idJob);
                if (h != null) {
                    res = getJob(h, em);
                } else {
                    throw new JqmInvalidRequestException("No job instance of ID " + idJob);
                }
            }
        }
        return res;
    } catch (JqmInvalidRequestException e) {
        throw e;
    } catch (Exception e) {
        throw new JqmClientException("an error occured during query execution", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:com.gigglinggnus.controllers.StudentMakeAppointmentController.java

/**
 *
 * @param request servlet request/*from  w ww .  j a  va2s .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String msg = request.getParameter("msg");
    User user = (User) (request.getSession().getAttribute("user"));
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));

    if (msg.equals("lookup_student")) {
        String studId = request.getParameter("studentId");
        List<Exam> exams = user.getRegistrableExams();
        JSONObject json = new JSONObject();
        json.put("students_idNumber", studId);
        json.put("firstName", user.getFirstName());
        json.put("lastName", user.getLastName());
        JSONArray jExams = new JSONArray();
        for (Exam exam : exams) {
            JSONObject elem = new JSONObject();

            String examId = exam.getExamId();
            String termId = exam.getTerm().getTermId();
            String start = exam.getInterval().getStart().atZone(ZoneId.systemDefault()).toLocalDate()
                    .toString();
            String end = exam.getInterval().getEnd().atZone(ZoneId.systemDefault()).toLocalDate().toString();
            elem.put("examId", examId);
            elem.put("termId", termId);
            if (exam instanceof CourseExam) {
                String courseId = ((CourseExam) exam).getCourse().getCourseId();
                elem.put("courseId", courseId);
                elem.put("examType", "Course");
            } else {
                elem.put("courseId", "N/A");
                elem.put("examType", "AdHoc");
            }
            elem.put("start", start);
            elem.put("end", end);
            jExams.put(elem);
        }
        json.put("exams", jExams);
        response.getWriter().write(json.toString());
    } else if (msg.equals("exam_available_timeslots")) {
        String examId = request.getParameter("examId");
        String dateStr = request.getParameter("date");
        Exam exam = em.find(Exam.class, examId);
        LocalDate apptDate = LocalDate.parse(dateStr);
        List<LocalTime> timeslots = exam.getTimeslotsForDay(apptDate);

        JSONObject json = new JSONObject();
        json.put("examId", examId);
        JSONArray jTimeSlots = new JSONArray();
        for (LocalTime timeslot : timeslots) {
            String start = timeslot.toString();
            String end = timeslot.plus(exam.getDuration()).toString();
            JSONObject elem = new JSONObject();
            elem.put("start", start);
            elem.put("end", end);
            jTimeSlots.put(elem);
        }
        json.put("timeSlots", jTimeSlots);
        response.getWriter().write(json.toString());
    } else if (msg.equals("submit-appointment")) {
        String studId = request.getParameter("studentId");
        String examId = request.getParameter("examId");
        String stDate = request.getParameter("examDate");
        String stTime = request.getParameter("startTime") + ":00";
        String stSeat = request.getParameter("seatType");

        Exam exam = em.find(Exam.class, examId);
        LocalDate lDate = LocalDate.parse(stDate);
        LocalTime lTime = LocalTime.parse(stTime);
        Instant inst = ZonedDateTime.of(lDate, lTime, ZoneId.systemDefault()).toInstant();
        JSONObject json = new JSONObject();
        try {
            em.getTransaction().begin();
            user.makeAppointment(exam, inst, clk);
            em.getTransaction().commit();
            json.put("success", "Appointment Made!");
            response.getWriter().write(json.toString());
        } catch (Exception e) {
            em.getTransaction().rollback();
            json.put("error", e.toString());
            response.getWriter().write(json.toString());
        }
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

From source file:net.nan21.dnet.core.presenter.converter.ReflookupResolver.java

/**
 * Do the actual work, update the reference field in the entity based on the
 * ref-lookup rule./* ww w  . jav  a2 s.com*/
 * 
 * @param m
 * @param e
 * @param refLookup
 * @param isInsert
 * @throws Exception
 */
private void doRefLookup1(M ds, E e, RefLookup refLookup, boolean isInsert, EntityManager em) throws Exception {

    String refIdDsFieldName = refLookup.refId();
    Object refIdDsFieldValue = this._getDsFieldValue(refIdDsFieldName, ds);
    String refEntityFieldName = null;
    Field refIdDsField = this._getDsField(refIdDsFieldName);

    if (!refIdDsField.isAnnotationPresent(DsField.class)) {
        throw new Exception("Field " + refIdDsFieldName
                + " cannot be used as value for refId in @RefLookup annotation as it is not marked as @DsField ");
    } else {
        DsField dsFieldAnnotation = refIdDsField.getAnnotation(DsField.class);

        /* Obey the noInsert and noUpdate rules. */

        if ((isInsert && dsFieldAnnotation.noInsert()) || (!isInsert && dsFieldAnnotation.noUpdate())) {
            return;
        }

        String path = dsFieldAnnotation.path();
        if (path.indexOf('.') > 0) {
            // TODO: handle the deep references also ( a.b.c.id )
            refEntityFieldName = path.substring(0, path.indexOf('.'));
        } else {
            throw new Exception("Field " + refIdDsFieldName
                    + " cannot be used as value for refId in @RefLookup annotation as its path(`" + path
                    + "`) in @DsField is not a reference path.");
        }
    }

    Class<?> refClass = this._getEntityField(refEntityFieldName).getType();
    Object ref = this._getEntityFieldValue(refEntityFieldName, e);
    Method setter = this._getEntitySetter(refEntityFieldName);

    if (refIdDsFieldValue != null && !"".equals(refIdDsFieldValue)) {
        /*
         * if there is an ID now in DS which points to a different reference
         * as the one in the original entity then update it to the new one
         */
        if (ref == null || !((IModelWithId) ref).getId().equals(refIdDsFieldValue)) {
            setter.invoke(e, em.find(refClass, refIdDsFieldValue));
        }
    } else {

        /*
         * If there is no ID given in DS for the reference, try to lookup an
         * entity based on the given named query which must be a query based
         * on an unique-key. The given fields as parameters for the
         * named-query must uniquely identify an entity.
         */

        boolean shouldTryToFindReference = true;
        String namedQueryName = refLookup.namedQuery();

        Map<String, Object> values = new HashMap<String, Object>();
        Map<String, Object> namedQueryParams = new HashMap<String, Object>();

        if (namedQueryName == null || namedQueryName.equals("")) {
            shouldTryToFindReference = false;
        } else {
            for (Param p : refLookup.params()) {
                String paramName = p.name();
                String fieldName = p.field();
                String staticValue = p.value();

                Object fieldValue = null;
                if (staticValue != null && !"".equals(staticValue)) {
                    fieldValue = staticValue;
                } else {
                    fieldValue = this._getDsFieldValue(fieldName, ds);
                }

                if (fieldValue == null || (fieldValue instanceof String && ((String) fieldValue).equals(""))) {
                    shouldTryToFindReference = false;
                    break;
                } else {
                    values.put(fieldName, fieldValue);
                    namedQueryParams.put(paramName, fieldValue);
                }
            }
        }

        if (shouldTryToFindReference) {

            Object theReference = null;
            try {
                theReference = (findEntityService(refClass)).findByUk(namedQueryName, namedQueryParams);
            } catch (javax.persistence.NoResultException exception) {

                StringBuffer sb = new StringBuffer();

                for (Map.Entry<String, Object> entry : values.entrySet()) {
                    sb.append(" `" + entry.getKey() + "` = `" + entry.getValue() + "`");
                }

                throw new BusinessException("Cannot find  `" + refClass.getSimpleName() + "` reference using "
                        + sb.toString() + " for data-source `" + ds.getClass().getSimpleName() + "`");
            }
            setter.invoke(e, theReference);
            Method refIdFieldInDsSetter = this._getDsSetter(refIdDsFieldName);
            refIdFieldInDsSetter.invoke(ds, ((IModelWithId) theReference).getId());
        } else {
            setter.invoke(e, (Object) null);
        }
    }
}