Example usage for javax.persistence EntityManager remove

List of usage examples for javax.persistence EntityManager remove

Introduction

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

Prototype

public void remove(Object entity);

Source Link

Document

Remove the entity instance.

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 {//w  w w  .  j  av  a 2  s  . co  m
        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.values.PnlValues.java

private JPanel createContentPanel4Year(final ResValueTypes vtype, final int year) {
    final String keyYears = vtype.getID() + ".xtypes." + Integer.toString(year) + ".year";

    java.util.List<ResValue> myValues;
    synchronized (mapType2Values) {
        if (!mapType2Values.containsKey(keyYears)) {
            mapType2Values.put(keyYears, ResValueTools.getResValues(resident, vtype, year));
        }//from  ww  w . ja  v a2 s  . c  o  m
        if (mapType2Values.get(keyYears).isEmpty()) {
            JLabel lbl = new JLabel(SYSTools.xx("misc.msg.novalue"));
            JPanel pnl = new JPanel();
            pnl.add(lbl);
            return pnl;
        }
        myValues = mapType2Values.get(keyYears);
    }

    JPanel pnlYear = new JPanel(new VerticalLayout());

    pnlYear.setOpaque(false);

    for (final ResValue resValue : myValues) {
        String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"200\" align=\"left\">"
                + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(resValue.getPit())
                + " [" + resValue.getID() + "]</td>" + "<td width=\"340\" align=\"left\">"
                + ResValueTools.getValueAsHTML(resValue) + "</td>" + "<td width=\"200\" align=\"left\">"
                + resValue.getUser().getFullname() + "</td>" + "</tr>" + "</table>" + "</html>";

        final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

        pnlTitle.getMain().setBackground(GUITools.blend(vtype.getColor(), Color.WHITE, 0.1f));
        pnlTitle.getMain().setOpaque(true);

        if (resValue.isObsolete()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22eraser));
        }
        if (resValue.isReplacement()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22edited));
        }
        if (!resValue.getText().trim().isEmpty()) {
            pnlTitle.getAdditionalIconPanel().add(new JLabel(SYSConst.icon22info));
        }
        if (pnlTitle.getAdditionalIconPanel().getComponentCount() > 0) {
            pnlTitle.getButton().addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GUITools.showPopup(
                            GUITools.getHTMLPopup(pnlTitle.getButton(), ResValueTools.getInfoAsHTML(resValue)),
                            SwingConstants.NORTH);
                }
            });
        }

        if (!resValue.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(
                    Integer.toString(resValue.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) {
                    new DlgFiles(resValue, new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final ResValue myValue = em.find(ResValue.class, resValue.getID());
                            em.close();

                            synchronized (mapType2Values) {
                                mapType2Values.get(keyYears).remove(resValue);
                                mapType2Values.get(keyYears).add(myValue);
                                Collections.sort(mapType2Values.get(keyYears));
                            }

                            createCP4Year(vtype, year);
                            buildPanel();
                        }
                    });
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            pnlTitle.getRight().add(btnFiles);
        }

        if (!resValue.getAttachedProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(
                    Integer.toString(resValue.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(resValue, 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);
                                ResValue myValue = em.merge(resValue);
                                em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                        resValue.getAttachedProcessConnections());
                                for (SYSVAL2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getResValue().getAttachedProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.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(myValue)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSVAL2PROCESS myLinkObject = em
                                                .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myValue.getTitle() + " ID: " + myValue.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedResValueConnections().add(myLinkObject);
                                        myValue.getAttachedProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                synchronized (mapType2Values) {
                                    mapType2Values.get(keyYears).remove(resValue);
                                    mapType2Values.get(keyYears).add(myValue);
                                    Collections.sort(mapType2Values.get(keyYears));
                                }
                                createCP4Year(vtype, year);

                                buildPanel();

                            } 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();
                            }
                        }
                    });
                }
            });
            btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            pnlTitle.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(resValue);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

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

        pnlYear.add(pnlTitle.getMain());
        synchronized (linemap) {
            linemap.put(resValue, pnlTitle.getMain());
        }
    }
    return pnlYear;
}

From source file:op.care.nursingprocess.PnlNursingProcess.java

private JPanel createNPPanel(final NursingProcess np) {
    /***/*  w w  w. ja v  a 2  s.c  o  m*/
     *                          _        ____ ____  _  _     _   _ ____
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |   | \ | |  _ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_  |  \| | |_) |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | |\  |  __/
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_|   |_| \_|_|
     *
     */
    if (!contenPanelMap.containsKey(np)) {
        String title = "<html><table border=\"0\">";

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

        title += "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">" + np.getPITAsHTML() + "</td>"
                + "<td width=\"500\" align=\"left\">" + (np.isClosed() ? "<s>" : "") + np.getContentAsHTML()
                + (np.isClosed() ? "</s>" : "") + "</td></tr>";
        title += "</table>" + "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
        cptitle.getButton().setVerticalTextPosition(SwingConstants.TOP);

        if (!np.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(Integer.toString(np.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 = np.isClosed() ? null : new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                            em.close();
                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            createCP4(myNP.getCategory());
                            buildPanel();
                        }
                    };
                    new DlgFiles(np, fileHandleClosure);
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            cptitle.getRight().add(btnFiles);
        }

        if (!np.getAttachedQProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(Integer.toString(np.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(np, 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);
                                final NursingProcess myNP = em.merge(np);
                                em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSNP2PROCESS> attached = new ArrayList<SYSNP2PROCESS>(
                                        myNP.getAttachedQProcessConnections());
                                for (SYSNP2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getNursingProcess().getAttachedQProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.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(myNP)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSNP2PROCESS myLinkObject = em
                                                .merge(new SYSNP2PROCESS(myQProcess, myNP));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedNursingProcessesConnections().add(myLinkObject);
                                        myNP.getAttachedQProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myNP.getCategory()).add(myNP);
                                Collections.sort(valuecache.get(myNP.getCategory()));

                                createCP4(myNP.getCategory());
                                buildPanel();

                            } 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();
                                }
                            } 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));
            cptitle.getRight().add(btnProcess);
        }

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
            /***
             *      _     _         ____       _       _
             *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
             *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
             *     | |_) | |_| | | |  __/| |  | | | | | |_
             *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
             *
             */
            JButton btnPrint = new JButton(SYSConst.icon22print2);
            btnPrint.setContentAreaFilled(false);
            btnPrint.setBorder(null);
            btnPrint.setPressedIcon(SYSConst.icon22print2Pressed);
            btnPrint.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnPrint.setAlignmentY(Component.TOP_ALIGNMENT);
            btnPrint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    SYSFilesTools.print(NursingProcessTools.getAsHTML(np, true, true, true, true), true);
                }
            });

            cptitle.getRight().add(btnPrint);
            //                cptitle.getTitleButton().setVerticalTextPosition(SwingConstants.TOP);
        }

        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        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(np);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });

        btnMenu.setEnabled(!np.isClosed());
        cptitle.getButton().setIcon(getIcon(np));

        cptitle.getRight().add(btnMenu);
        cptitle.getMain().setBackground(getColor(np.getCategory())[SYSConst.light2]);
        cptitle.getMain().setOpaque(true);
        contenPanelMap.put(np, cptitle.getMain());
    }

    return contenPanelMap.get(np);
}

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

private CollapsiblePane createCP4(final Prescription prescription) {
    /***/*from  w ww .  j a  v  a2 s .  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:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java

protected boolean updateQuantityRule(EntityManager em, DataDTOToMVELTranslator translator, String entityKey,
        String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList,
        Class<?> memberType, Object parent, String mappedBy, Property property) {
    boolean dirty = false;
    if (!StringUtils.isEmpty(jsonPropertyValue)) {
        //avoid lazy init exception on the criteria list for criteria created during an add
        criteriaList.size();//from w  w w .j  a  v a 2s . co  m
        DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
        if (dw != null && StringUtils.isEmpty(dw.getError())) {
            List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
            for (DataDTO dto : dw.getData()) {
                if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) {
                    checkId: {
                        //updates are comprehensive, even data that was not changed
                        //is submitted here
                        //Update Existing Criteria
                        for (QuantityBasedRule quantityBasedRule : criteriaList) {
                            //make compatible with enterprise module
                            Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                            boolean isMatch = dto.getId().equals(id)
                                    || dto.getId().equals(quantityBasedRule.getId());
                            if (isMatch) {
                                String mvel;
                                //don't update if the data has not changed
                                if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
                                    dirty = true;
                                }
                                try {
                                    mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator,
                                            entityKey, dto, fieldService);
                                    if (!quantityBasedRule.getMatchRule().equals(mvel)) {
                                        dirty = true;
                                    }
                                } catch (MVELTranslationException e) {
                                    throw new RuntimeException(e);
                                }
                                if (!dirty && extensionManager != null) {
                                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                                    ExtensionResultStatusType result = extensionManager.getProxy()
                                            .establishDirtyState(quantityBasedRule, resultHolder);
                                    if (ExtensionResultStatusType.NOT_HANDLED != result
                                            && resultHolder.getResult() != null) {
                                        dirty = resultHolder.getResult();
                                    }
                                }
                                if (dirty) {
                                    quantityBasedRule.setQuantity(dto.getQuantity());
                                    quantityBasedRule.setMatchRule(mvel);
                                    quantityBasedRule = em.merge(quantityBasedRule);
                                }
                                updatedRules.add(quantityBasedRule);
                                break checkId;
                            }
                        }
                        throw new IllegalArgumentException("Unable to update the rule of type ("
                                + memberType.getName() + ") because an update was requested for id ("
                                + dto.getId() + "), which does not exist.");
                    }
                } else {
                    //Create a new Criteria
                    QuantityBasedRule quantityBasedRule;
                    try {
                        quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
                        quantityBasedRule.setQuantity(dto.getQuantity());
                        quantityBasedRule.setMatchRule(ruleFieldExtractionUtility
                                .convertDTOToMvelString(translator, entityKey, dto, fieldService));
                        if (StringUtils.isEmpty(quantityBasedRule.getMatchRule())
                                && !StringUtils.isEmpty(dw.getRawMvel())) {
                            quantityBasedRule.setMatchRule(dw.getRawMvel());
                        }
                        PropertyUtils.setNestedProperty(quantityBasedRule, mappedBy, parent);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    em.persist(quantityBasedRule);
                    dto.setId(quantityBasedRule.getId());
                    if (extensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        extensionManager.getProxy().postAdd(quantityBasedRule, resultHolder);
                        if (resultHolder.getResult() != null) {
                            quantityBasedRule = (QuantityBasedRule) resultHolder.getResult();
                        }
                    }
                    updatedRules.add(quantityBasedRule);
                    dirty = true;
                }
            }
            //if an item was not included in the comprehensive submit from the client, we can assume that the
            //listing was deleted, so we remove it here.
            Iterator<QuantityBasedRule> itr = criteriaList.iterator();
            while (itr.hasNext()) {
                checkForRemove: {
                    QuantityBasedRule original = itr.next();
                    for (QuantityBasedRule quantityBasedRule : updatedRules) {
                        Long id = sandBoxHelper.getOriginalId(quantityBasedRule);
                        boolean isMatch = original.getId().equals(id)
                                || original.getId().equals(quantityBasedRule.getId());
                        if (isMatch) {
                            break checkForRemove;
                        }
                    }
                    em.remove(original);
                    itr.remove();
                    dirty = true;
                }
            }
            ObjectMapper mapper = new ObjectMapper();
            String json;
            try {
                json = mapper.writeValueAsString(dw);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            property.setValue(json);
        }
    }
    return dirty;
}

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 w w .jav a  2s .com*/
    }
    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:op.allowance.PnlAllowance.java

private JPanel createContentPanel4(final Resident resident, LocalDate month) {
    final String key = getKey(resident, month);

    if (!contentmap.containsKey(key)) {

        JPanel pnlMonth = new JPanel(new VerticalLayout());

        pnlMonth.setBackground(getBG(resident, 11));
        pnlMonth.setOpaque(false);//w w w  . j  ava2s  .  c  om

        //            final String prevKey = resident.getRID() + "-" + SYSCalendar.eom(month.minusMonths(1)).getYear() + "-" + SYSCalendar.eom(month.minusMonths(1)).getMonthOfYear();
        if (!carrySums.containsKey(key)) {
            carrySums.put(key, AllowanceTools.getSUM(resident, SYSCalendar.eom(month.minusMonths(1))));
        }

        BigDecimal rowsum = carrySums.get(key);

        if (!cashmap.containsKey(key)) {
            cashmap.put(key, AllowanceTools.getMonth(resident, month.toDate()));
        }

        JLabel lblEOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMaximumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.endofmonth") + "</td>"
                + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        pnlMonth.add(lblEOM);

        for (final Allowance allowance : cashmap.get(key)) {

            String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                    + DateFormat.getDateInstance().format(allowance.getPit()) + "</td>"
                    + "<td width=\"400\" align=\"left\">" + allowance.getText() + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                    + cf.format(allowance.getAmount())
                    + (allowance.getAmount().compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>"
                    + "<td width=\"100\" align=\"right\">"
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                    + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>"
                    +

                    "</font></html>";

            DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {

                }
            });
            cptitle.getButton().setIcon(
                    allowance.isReplaced() || allowance.isReplacement() ? SYSConst.icon22eraser : null);

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
                /***
                 *      _____    _ _ _
                 *     | ____|__| (_) |_
                 *     |  _| / _` | | __|
                 *     | |__| (_| | | |_
                 *     |_____\__,_|_|\__|
                 *
                 */
                final JButton btnEdit = new JButton(SYSConst.icon22edit3);
                btnEdit.setPressedIcon(SYSConst.icon22edit3Pressed);
                btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnEdit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnEdit.setContentAreaFilled(false);
                btnEdit.setBorder(null);
                btnEdit.setToolTipText(SYSTools.xx("admin.residents.cash.btnedit.tooltip"));
                btnEdit.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        final JidePopup popupTX = new JidePopup();
                        popupTX.setMovable(false);
                        PnlTX pnlTX = getPnlTX(resident, allowance);
                        popupTX.setContentPane(pnlTX);
                        popupTX.removeExcludedComponent(pnlTX);
                        popupTX.setDefaultFocusComponent(pnlTX);

                        popupTX.setOwner(btnEdit);
                        GUITools.showPopup(popupTX, SwingConstants.WEST);

                    }
                });
                cptitle.getRight().add(btnEdit);
                // you can edit your own entries or you are a manager. once they are replaced or a replacement record, its over.
                btnEdit.setEnabled((OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, internalClassID)
                        || allowance.getUser().equals(OPDE.getLogin().getUser())) && !allowance.isReplaced()
                        && !allowance.isReplacement());

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("admin.residents.cash.btnundotx.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>" + "<br/><i>"
                                        + allowance.getText() + "&nbsp;" + cf.format(allowance.getAmount())
                                        + "</i><br/>" + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();

                                                Allowance myOldAllowance = em.merge(allowance);
                                                Allowance myCancelAllowance = em
                                                        .merge(new Allowance(myOldAllowance));
                                                em.lock(em.merge(myOldAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myOldAllowance, LockModeType.OPTIMISTIC);
                                                myOldAllowance.setReplacedBy(myCancelAllowance,
                                                        em.merge(OPDE.getLogin().getUser()));

                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myCancelAllowance.getPit());

                                                final String keyMonth = myCancelAllowance.getResident().getRID()
                                                        + "-" + txDate.getYear() + "-"
                                                        + txDate.getMonthOfYear();
                                                contentmap.remove(keyMonth);
                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(allowance);
                                                cashmap.get(keyMonth).add(myOldAllowance);
                                                cashmap.get(keyMonth).add(myCancelAllowance);
                                                Collections.sort(cashmap.get(keyMonth));

                                                updateCarrySums(myCancelAllowance);

                                                createCP4(myCancelAllowance.getResident());

                                                try {
                                                    cpMap.get(keyMonth).setCollapsed(false);
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();

                                            } 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 (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnUndoTX);
                btnUndoTX.setEnabled(!allowance.isReplaced() && !allowance.isReplacement());
            }

            if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
                /***
                 *      ____       _      _
                 *     |  _ \  ___| | ___| |_ ___
                 *     | | | |/ _ \ |/ _ \ __/ _ \
                 *     | |_| |  __/ |  __/ ||  __/
                 *     |____/ \___|_|\___|\__\___|
                 *
                 */
                final JButton btnDelete = new JButton(SYSConst.icon22delete);
                btnDelete.setPressedIcon(SYSConst.icon22deletePressed);
                btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnDelete.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnDelete.setContentAreaFilled(false);
                btnDelete.setBorder(null);
                btnDelete.setToolTipText(SYSTools.xx("admin.residents.cash.btndelete.tooltip"));
                btnDelete.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.delete1") + "<br/><i>" + allowance.getText()
                                        + "&nbsp;" + cf.format(allowance.getAmount()) + "</i><br/>"
                                        + SYSTools.xx("misc.questions.delete2"),
                                SYSConst.icon48delete, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                Allowance myAllowance = em.merge(allowance);
                                                em.lock(em.merge(myAllowance.getResident()),
                                                        LockModeType.OPTIMISTIC);

                                                Allowance theOtherOne = null;
                                                // Check for special cases
                                                if (myAllowance.isReplacement()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacementFor());
                                                    theOtherOne.setReplacedBy(null);
                                                    theOtherOne.setEditedBy(null);
                                                    myAllowance.setEditPit(null);
                                                }
                                                if (myAllowance.isReplaced()) {
                                                    theOtherOne = em.merge(myAllowance.getReplacedBy());
                                                    theOtherOne.setReplacementFor(null);
                                                }

                                                em.remove(myAllowance);
                                                em.getTransaction().commit();

                                                DateTime txDate = new DateTime(myAllowance.getPit());
                                                final String keyMonth = myAllowance.getResident().getRID() + "-"
                                                        + txDate.getYear() + "-" + txDate.getMonthOfYear();

                                                cpMap.remove(keyMonth);
                                                cashmap.get(keyMonth).remove(myAllowance);
                                                if (theOtherOne != null) {
                                                    cashmap.get(keyMonth).remove(theOtherOne);
                                                    cashmap.get(keyMonth).add(theOtherOne);
                                                    Collections.sort(cashmap.get(keyMonth));
                                                }

                                                // only to update the carrysums. myAllowance will be discarded soon.
                                                myAllowance.setAmount(myAllowance.getAmount().negate());
                                                updateCarrySums(myAllowance);

                                                createCP4(myAllowance.getResident());

                                                try {
                                                    if (cpMap.containsKey(keyMonth)) {
                                                        cpMap.get(keyMonth).setCollapsed(false);
                                                    }
                                                } catch (PropertyVetoException e) {
                                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                                }

                                                buildPanel();
                                            } 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 (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });
                    }
                });
                cptitle.getRight().add(btnDelete);
            }
            pnlMonth.add(cptitle.getMain());
            linemap.put(allowance, cptitle.getMain());

            rowsum = rowsum.subtract(allowance.getAmount());
        }

        JLabel lblBOM = new JLabel("<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                + DateFormat.getDateInstance().format(month.dayOfMonth().withMinimumValue().toDate()) + "</td>"
                + "<td width=\"400\" align=\"left\">" + SYSTools.xx("admin.residents.cash.startofmonth")
                + "</td>" + "<td width=\"100\" align=\"right\"></td>" + "<td width=\"100\" align=\"right\">"
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "") + cf.format(rowsum)
                + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" + "</tr>" + "</table>" +

                "</font></html>");
        lblBOM.setBackground(getBG(resident, 11));
        pnlMonth.add(lblBOM);
        contentmap.put(key, pnlMonth);
    }

    return contentmap.get(key);
}

From source file:op.care.med.inventory.PnlInventory.java

private JPanel createContentPanel4(final MedStock stock) {
    //        final String key = stock.getID() + ".xstock";

    //        if (!contentmap.containsKey(key)) {

    final JPanel pnlTX = new JPanel(new VerticalLayout());
    //            pnlTX.setLayout(new BoxLayout(pnlTX, BoxLayout.PAGE_AXIS));

    pnlTX.setOpaque(true);//  ww  w  . java  2  s.c  o  m
    //        pnlTX.setBackground(Color.white);
    synchronized (lstInventories) {
        pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0));
    }

    /***
     *         _       _     _ _______  __
     *        / \   __| | __| |_   _\ \/ /
     *       / _ \ / _` |/ _` | | |  \  /
     *      / ___ \ (_| | (_| | | |  /  \
     *     /_/   \_\__,_|\__,_| |_| /_/\_\
     *
     */
    JideButton btnAddTX = GUITools.createHyperlinkButton("nursingrecords.inventory.newmedstocktx",
            SYSConst.icon22add, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new DlgTX(new MedStockTransaction(stock, BigDecimal.ONE,
                            MedStockTransactionTools.STATE_EDIT_MANUAL), new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            final MedStockTransaction myTX = (MedStockTransaction) em.merge(o);
                                            MedStock myStock = em.merge(stock);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                            em.lock(em.merge(myTX.getStock().getInventory().getResident()),
                                                    LockModeType.OPTIMISTIC);
                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());

                                            buildPanel();
                                        } 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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
    btnAddTX.setEnabled(!stock.isClosed());
    pnlTX.add(btnAddTX);

    /***
     *      ____  _                           _ _   _______  __
     *     / ___|| |__   _____      __   __ _| | | |_   _\ \/ /___
     *     \___ \| '_ \ / _ \ \ /\ / /  / _` | | |   | |  \  // __|
     *      ___) | | | | (_) \ V  V /  | (_| | | |   | |  /  \\__ \
     *     |____/|_| |_|\___/ \_/\_/    \__,_|_|_|   |_| /_/\_\___/
     *
     */
    OPDE.getMainframe().setBlocked(true);
    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

    SwingWorker worker = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            int progress = 0;

            List<MedStockTransaction> listTX = MedStockTransactionTools.getAll(stock);
            OPDE.getDisplayManager().setProgressBarMessage(
                    new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));

            BigDecimal rowsum = MedStockTools.getSum(stock);
            //                BigDecimal rowsum = MedStockTools.getSum(stock);
            //                Collections.sort(stock.getStockTransaction());
            for (final MedStockTransaction tx : listTX) {
                progress++;
                OPDE.getDisplayManager().setProgressBarMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));
                String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                .format(tx.getPit())
                        + "<br/>[" + tx.getID() + "]" + "</td>" + "<td width=\"200\" align=\"center\">"
                        + SYSTools.catchNull(tx.getText(), "--") + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + NumberFormat.getNumberInstance().format(tx.getAmount()) + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                        + NumberFormat.getNumberInstance().format(rowsum)
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" +

                        (stock.getTradeForm().isWeightControlled() ? "<td width=\"100\" align=\"right\">"
                                + NumberFormat.getNumberInstance().format(tx.getWeight()) + "g" + "</td>" : "")
                        +

                        "<td width=\"100\" align=\"left\">" + SYSTools.anonymizeUser(tx.getUser().getUID())
                        + "</td>" + "</tr>" + "</table>" +

                        "</font></html>";

                rowsum = rowsum.subtract(tx.getAmount());

                final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

                //                pnlTitle.getLeft().addMouseListener();

                if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
                    /***
                     *      ____       _ _______  __
                     *     |  _ \  ___| |_   _\ \/ /
                     *     | | | |/ _ \ | | |  \  /
                     *     | |_| |  __/ | | |  /  \
                     *     |____/ \___|_| |_| /_/\_\
                     *
                     */
                    final JButton btnDelTX = new JButton(SYSConst.icon22delete);
                    btnDelTX.setPressedIcon(SYSConst.icon22deletePressed);
                    btnDelTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnDelTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnDelTX.setContentAreaFilled(false);
                    btnDelTX.setBorder(null);
                    btnDelTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btndelete.tooltip"));
                    btnDelTX.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                                    + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                            .format(tx.getPit())
                                    + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                    + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete,
                                    new Closure() {
                                        @Override
                                        public void execute(Object answer) {
                                            if (answer.equals(JOptionPane.YES_OPTION)) {
                                                EntityManager em = OPDE.createEM();
                                                try {
                                                    em.getTransaction().begin();

                                                    MedStockTransaction myTX = em.merge(tx);
                                                    MedStock myStock = em.merge(stock);
                                                    em.lock(em.merge(
                                                            myTX.getStock().getInventory().getResident()),
                                                            LockModeType.OPTIMISTIC);
                                                    em.lock(myStock, LockModeType.OPTIMISTIC);
                                                    em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                                    em.remove(myTX);
                                                    //                                                myStock.getStockTransaction().remove(myTX);
                                                    em.getTransaction().commit();

                                                    //                                                synchronized (lstInventories) {
                                                    //                                                    int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                    //                                                    int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                    //                                                }

                                                    //                                                synchronized (linemap) {
                                                    //                                                    linemap.remove(myTX);
                                                    //                                                }

                                                    createCP4(myStock.getInventory());

                                                    buildPanel();
                                                } 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 (Exception e) {
                                                    if (em.getTransaction().isActive()) {
                                                        em.getTransaction().rollback();
                                                    }
                                                    OPDE.fatal(e);
                                                } finally {
                                                    em.close();
                                                }
                                            }
                                        }
                                    });

                        }
                    });
                    btnDelTX.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnDelTX);
                }

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>"
                                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                                .format(tx.getPit())
                                        + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                        + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                MedStock myStock = em.merge(stock);
                                                final MedStockTransaction myOldTX = em.merge(tx);

                                                myOldTX.setState(MedStockTransactionTools.STATE_CANCELLED);
                                                final MedStockTransaction myNewTX = em
                                                        .merge(new MedStockTransaction(myStock,
                                                                myOldTX.getAmount().negate(),
                                                                MedStockTransactionTools.STATE_CANCEL_REC));
                                                myOldTX.setText(SYSTools.xx("misc.msg.reversedBy") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myNewTX.getPit()));
                                                myNewTX.setText(SYSTools.xx("misc.msg.reversalFor") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myOldTX.getPit()));

                                                //                                            myStock.getStockTransaction().add(myNewTX);
                                                //                                            myStock.getStockTransaction().remove(tx);
                                                //                                            myStock.getStockTransaction().add(myOldTX);

                                                em.lock(em
                                                        .merge(myNewTX.getStock().getInventory().getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myStock, LockModeType.OPTIMISTIC);
                                                em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                                em.getTransaction().commit();

                                                //                                            synchronized (lstInventories) {
                                                //                                                int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                //                                                int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                //                                            }

                                                //                                            synchronized (linemap) {
                                                //                                                linemap.remove(tx);
                                                //                                            }
                                                createCP4(myStock.getInventory());
                                                buildPanel();
                                                //                                            SwingUtilities.invokeLater(new Runnable() {
                                                //                                                @Override
                                                //                                                public void run() {
                                                //                                                    synchronized (linemap) {
                                                //                                                        GUITools.flashBackground(linemap.get(myOldTX), Color.RED, 2);
                                                //                                                        GUITools.flashBackground(linemap.get(myNewTX), 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 (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });

                    }
                });
                btnUndoTX.setEnabled(!stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                        || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                pnlTitle.getRight().add(btnUndoTX);

                if (stock.getTradeForm().isWeightControlled() && OPDE.getAppInfo()
                        .isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
                    /***
                     *               _ __        __   _       _     _
                     *      ___  ___| |\ \      / /__(_) __ _| |__ | |_
                     *     / __|/ _ \ __\ \ /\ / / _ \ |/ _` | '_ \| __|
                     *     \__ \  __/ |_ \ V  V /  __/ | (_| | | | | |_
                     *     |___/\___|\__| \_/\_/ \___|_|\__, |_| |_|\__|
                     *                                  |___/
                     */
                    final JButton btnSetWeight = new JButton(SYSConst.icon22scales);
                    btnSetWeight.setPressedIcon(SYSConst.icon22Pressed);
                    btnSetWeight.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnSetWeight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnSetWeight.setContentAreaFilled(false);
                    btnSetWeight.setBorder(null);
                    btnSetWeight.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                    btnSetWeight.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {

                            BigDecimal weight;
                            new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (!SYSTools.catchNull(o).isEmpty()) {
                                        BigDecimal weight = (BigDecimal) o;

                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            MedStock myStock = em.merge(stock);
                                            final MedStockTransaction myTX = em.merge(tx);
                                            em.lock(myTX, LockModeType.OPTIMISTIC);
                                            myTX.setWeight(weight);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());
                                            buildPanel();
                                        } 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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            }, "nursingrecords.bhp.weight",
                                    NumberFormat.getNumberInstance().format(tx.getWeight()),
                                    new Validator<BigDecimal>() {
                                        @Override
                                        public boolean isValid(String value) {
                                            BigDecimal bd = parse(value);
                                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                        }

                                        @Override
                                        public BigDecimal parse(String text) {
                                            return SYSTools.parseDecimal(text);
                                        }
                                    });

                        }
                    });
                    btnSetWeight.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_CREDIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnSetWeight);
                }

                pnlTX.add(pnlTitle.getMain());
            }

            return null;
        }

        @Override
        protected void done() {
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

    return pnlTX;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private INakedObject deproxyNakedObject(boolean root, Set<PropertyDescriptor> collections,
        Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers, Set<LinkFileInfo> linkedFiles,
        INakedObject no, Set<PropertyDescriptor> idPds, Map<String, Map<Object, Object>> oldIdByNewId,
        EntityManager em, Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyContext)
        throws IllegalAccessException, InvocationTargetException, InstantiationException,
        IntrospectionException, ClassNotFoundException, PersistenceException {
    String name = getClassName(no);
    if (isProxy(no, name))
        no = clone(no, name);//  ww  w . j a  v  a2s.co m
    Map<com.hiperf.common.ui.shared.util.Id, INakedObject> map = deproxyContext.get(name);
    if (map == null) {
        map = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>();
        deproxyContext.put(name, map);
    }
    com.hiperf.common.ui.shared.util.Id noId = getId(no, idsByClassName.get(name));
    if (map.containsKey(noId))
        return no;
    map.put(noId, no);

    if (root && linkedFiles != null && !linkedFiles.isEmpty()) {
        for (LinkFileInfo a : linkedFiles) {
            Object fileId = a.getLocalFileIdGetter().invoke(no, new Object[0]);
            if (fileId != null)
                a.getLocalFileNameSetter().invoke(no,
                        getFileName(a.getFileClassName(), a.getFileNameField(), fileId, getEntityManager()));
        }
    }

    if (collections != null) {
        for (PropertyDescriptor pd : collections) {
            Method readMethod = pd.getReadMethod();
            Method writeMethod = pd.getWriteMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                if (root) {
                    Collection orig = (Collection) o;
                    boolean processed = false;
                    Type type = readMethod.getGenericReturnType();
                    Class classInCollection = null;
                    if (type instanceof ParameterizedType) {
                        classInCollection = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
                    }
                    if (classInCollection != null) {
                        if (Number.class.isAssignableFrom(classInCollection)
                                || String.class.equals(classInCollection)
                                || Boolean.class.equals(classInCollection)) {
                            Collection targetColl;
                            int size = orig.size();
                            if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                                targetColl = new ArrayList(size);
                            } else {
                                targetColl = new HashSet(size);
                            }
                            if (size > 0)
                                targetColl.addAll(orig);
                            writeMethod.invoke(no, targetColl);
                            processed = true;
                        }
                    }
                    if (!processed) {
                        //deproxyCollection(no, readMethod, writeMethod, orig, oldIdByNewId, em, deproxyContext);
                        com.hiperf.common.ui.shared.util.Id id = getId(no, idPds);
                        CollectionInfo ci = null;
                        if (!id.isLocal()) {
                            String className = getClassName(no);
                            String attName = pd.getName();
                            ci = getCollectionInfo(em, id, className, attName);
                        }
                        if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                            if (ci != null)
                                writeMethod.invoke(no,
                                        new LazyList<INakedObject>(ci.getSize(), ci.getDescription()));
                            else
                                writeMethod.invoke(no, new LazyList<INakedObject>());
                        } else {
                            if (ci != null)
                                writeMethod.invoke(no,
                                        new LazySet<INakedObject>(ci.getSize(), ci.getDescription()));
                            else
                                writeMethod.invoke(no, new LazySet<INakedObject>());
                        }
                    }
                } else {
                    if (List.class.isAssignableFrom(readMethod.getReturnType())) {
                        writeMethod.invoke(no, new LazyList<INakedObject>());
                    } else {
                        writeMethod.invoke(no, new LazySet<INakedObject>());
                    }

                }

            }
        }
    }
    if (lazys != null) {
        for (PropertyDescriptor pd : lazys) {
            Method readMethod = pd.getReadMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                Class<?> targetClass = pd.getPropertyType();
                if (root) {
                    String targetClassName = targetClass.getName();
                    if (isProxy(o, targetClassName)) {
                        o = deproxyObject(targetClass, o);
                    }
                    Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName);
                    o = deproxyNakedObject(root, collectionsByClassName.get(targetClassName),
                            lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName),
                            linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId,
                            em, deproxyContext);
                    pd.getWriteMethod().invoke(no, o);
                } else {
                    Object lazyObj = newLazyObject(targetClass);

                    pd.getWriteMethod().invoke(no, lazyObj);
                }
            }
        }
    }
    if (eagers != null) {
        for (PropertyDescriptor pd : eagers) {
            String targetClassName = pd.getPropertyType().getName();
            Method readMethod = pd.getReadMethod();
            Object o = readMethod.invoke(no, new Object[0]);
            if (o != null) {
                Set<PropertyDescriptor> ids = idsByClassName.get(targetClassName);
                deproxyNakedObject(root, collectionsByClassName.get(targetClassName),
                        lazysByClassName.get(targetClassName), eagerObjectsByClassName.get(targetClassName),
                        linkedFilesByClassName.get(targetClassName), (INakedObject) o, ids, oldIdByNewId, em,
                        deproxyContext);
            }
        }
    }

    if (oldIdByNewId != null && idPds != null) {
        Map<Object, Object> map2 = oldIdByNewId.get(no.getClass().getName());
        if (map2 != null && !map2.isEmpty()) {
            for (PropertyDescriptor pd : idPds) {
                Object id = pd.getReadMethod().invoke(no, StorageService.emptyArg);
                Object oldId = map2.get(id);
                if (oldId != null) {
                    pd.getWriteMethod().invoke(no, new Object[] { oldId });
                }
            }
        }
    }

    try {
        em.remove(no);
    } catch (Exception e) {
    }
    return no;
}

From source file:op.care.med.inventory.PnlInventory.java

private CollapsiblePane createCP4(final MedInventory inventory) {
    /***//from www  .  j  av a2 s.c  o m
     *                          _        ____ ____  _  _    _____                      _                 __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /_ _|_ ____   _____ _ __ | |_ ___  _ __ _   \ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| | | || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | | |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | | || | | \ V /  __/ | | | || (_) | |  | |_| | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, | |
     *                                                     \_\                                       |___/_/
     */
    final String key = inventory.getID() + ".xinventory";
    synchronized (cpMap) {
        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.
            }

        }

        cpMap.get(key).setName("inventory");

        //            final CollapsiblePane cpInventory = cpMap.get(key);

        BigDecimal sumInventory = BigDecimal.ZERO;
        try {
            EntityManager em = OPDE.createEM();
            sumInventory = MedInventoryTools.getSum(em, inventory);
            em.close();
        } catch (Exception e) {
            OPDE.fatal(e);
        }

        String title = "<html><table border=\"0\">" + "<tr>" +

                "<td width=\"520\" align=\"left\"><font size=+1>" + inventory.getText() + "</font></td>"
                + "<td width=\"200\" align=\"right\"><font size=+1>"
                + NumberFormat.getNumberInstance().format(sumInventory) + " "
                + DosageFormTools.getPackageText(MedInventoryTools.getForm(inventory)) + "</font></td>" +

                "</tr>" + "</table>" +

                "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    cpMap.get(key).setCollapsed(!cpMap.get(key).isCollapsed());
                } catch (PropertyVetoException pve) {
                    // BAH!
                }
            }
        });
        cpMap.get(key).setTitleLabelComponent(cptitle.getMain());
        cpMap.get(key).setSlidingDirection(SwingConstants.SOUTH);
        cptitle.getButton().setIcon(inventory.isClosed() ? SYSConst.icon22stopSign : null);

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
            /***
             *       ____ _                ___                      _
             *      / ___| | ___  ___  ___|_ _|_ ____   _____ _ __ | |_ ___  _ __ _   _
             *     | |   | |/ _ \/ __|/ _ \| || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | |
             *     | |___| | (_) \__ \  __/| || | | \ V /  __/ | | | || (_) | |  | |_| |
             *      \____|_|\___/|___/\___|___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, |
             *                                                                    |___/
             */
            final JButton btnCloseInventory = new JButton(SYSConst.icon22playerStop);
            btnCloseInventory.setPressedIcon(SYSConst.icon22playerStopPressed);
            btnCloseInventory.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnCloseInventory.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnCloseInventory.setContentAreaFilled(false);
            btnCloseInventory.setBorder(null);
            btnCloseInventory.setToolTipText(SYSTools.xx("nursingrecords.inventory.btncloseinventory.tooltip"));
            btnCloseInventory.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgYesNo(
                            SYSTools.xx("nursingrecords.inventory.question.close1") + "<br/><b>"
                                    + inventory.getText() + "</b>" + "<br/>"
                                    + SYSTools.xx("nursingrecords.inventory.question.close2"),
                            SYSConst.icon48playerStop, new Closure() {
                                @Override
                                public void execute(Object answer) {
                                    if (answer.equals(JOptionPane.YES_OPTION)) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            MedInventory myInventory = em.merge(inventory);
                                            em.lock(myInventory, LockModeType.OPTIMISTIC);
                                            em.lock(myInventory.getResident(), LockModeType.OPTIMISTIC);

                                            // close all stocks
                                            for (MedStock stock : MedStockTools.getAll(myInventory)) {
                                                if (!stock.isClosed()) {
                                                    MedStock mystock = em.merge(stock);
                                                    em.lock(mystock, LockModeType.OPTIMISTIC);
                                                    mystock.setNextStock(null);
                                                    MedStockTools.close(em, mystock, SYSTools.xx(
                                                            "nursingrecords.inventory.stock.msg.inventory_closed"),
                                                            MedStockTransactionTools.STATE_EDIT_INVENTORY_CLOSED);
                                                }
                                            }
                                            // close inventory
                                            myInventory.setTo(new Date());

                                            em.getTransaction().commit();

                                            createCP4(myInventory);
                                            buildPanel();
                                        } 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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
            btnCloseInventory.setEnabled(!inventory.isClosed());
            cptitle.getRight().add(btnCloseInventory);
        }
        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
            /***
             *      ____       _ ___                      _
             *     |  _ \  ___| |_ _|_ ____   _____ _ __ | |_ ___  _ __ _   _
             *     | | | |/ _ \ || || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | |
             *     | |_| |  __/ || || | | \ V /  __/ | | | || (_) | |  | |_| |
             *     |____/ \___|_|___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, |
             *                                                          |___/
             */
            final JButton btnDelInventory = new JButton(SYSConst.icon22delete);
            btnDelInventory.setPressedIcon(SYSConst.icon22deletePressed);
            btnDelInventory.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnDelInventory.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnDelInventory.setContentAreaFilled(false);
            btnDelInventory.setBorder(null);
            btnDelInventory.setToolTipText(SYSTools.xx("nursingrecords.inventory.btndelinventory.tooltip"));
            btnDelInventory.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgYesNo(
                            SYSTools.xx("nursingrecords.inventory.question.delete1") + "<br/><b>"
                                    + inventory.getText() + "</b>" + "<br/>"
                                    + SYSTools.xx("nursingrecords.inventory.question.delete2"),
                            SYSConst.icon48delete, new Closure() {
                                @Override
                                public void execute(Object answer) {
                                    if (answer.equals(JOptionPane.YES_OPTION)) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            MedInventory myInventory = em.merge(inventory);
                                            em.lock(myInventory, LockModeType.OPTIMISTIC);
                                            em.lock(myInventory.getResident(), LockModeType.OPTIMISTIC);

                                            em.remove(myInventory);

                                            em.getTransaction().commit();

                                            //                                        lstInventories.remove(inventory);
                                            buildPanel();
                                        } 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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
            cptitle.getRight().add(btnDelInventory);
        }

        final JToggleButton tbClosedStock = GUITools.getNiceToggleButton(null);
        tbClosedStock.setToolTipText(SYSTools.xx("nursingrecords.inventory.showclosedstocks"));
        if (!inventory.isClosed()) {
            tbClosedStock.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
                }
            });
        }
        tbClosedStock.setSelected(inventory.isClosed());
        tbClosedStock.setEnabled(!inventory.isClosed());

        mapKey2ClosedToggleButton.put(key, tbClosedStock);

        cptitle.getRight().add(tbClosedStock);

        CollapsiblePaneAdapter adapter = new CollapsiblePaneAdapter() {
            @Override
            public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
                cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
            }
        };
        synchronized (cpListener) {
            if (cpListener.containsKey(key)) {
                cpMap.get(key).removeCollapsiblePaneListener(cpListener.get(key));
            }
            cpListener.put(key, adapter);
            cpMap.get(key).addCollapsiblePaneListener(adapter);
        }

        if (!cpMap.get(key).isCollapsed()) {
            cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
        }

        cpMap.get(key).setHorizontalAlignment(SwingConstants.LEADING);
        cpMap.get(key).setOpaque(false);
        cpMap.get(key).setBackground(getColor(SYSConst.medium2, lstInventories.indexOf(inventory) % 2 != 0));

        return cpMap.get(key);
    }
}