Example usage for org.apache.commons.collections CollectionUtils intersection

List of usage examples for org.apache.commons.collections CollectionUtils intersection

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils intersection.

Prototype

public static Collection intersection(final Collection a, final Collection b) 

Source Link

Document

Returns a Collection containing the intersection of the given Collection s.

Usage

From source file:org.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> createCommissionInvoices(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
    List<Map<String, String>> invoicesCreated = FastList.newInstance();
    Map<String, List<Map<String, Object>>> commissionParties = FastMap.newInstance();
    for (String salesInvoiceId : salesInvoiceIds) {
        List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
        BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
        if (amountTotal.signum() == 0) {
            Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal
                    + "], so no commission invoice will be created", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                    "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
        }//  ww  w  . j ava  2s  . co  m
        BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
        GenericValue invoice = null;
        boolean isReturn = false;
        List<String> billFromVendorInvoiceRoles = new ArrayList<String>();
        List<GenericValue> invoiceItems = new ArrayList<GenericValue>();
        try {
            List<EntityExpr> invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
            EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole")
                    .where(invoiceRoleConds);
            billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId",
                    true);

            invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP"));
            // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice.
            if (UtilValidate.isEmpty(salesRepPartyIds)) {
                salesRepPartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isEmpty(salesRepPartyIds)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                            "No party found with role sales representative for sales invoice " + salesInvoiceId,
                            locale));
                }
            } else {
                List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                    salesRepPartyIds = UtilGenerics.checkList(
                            CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                }
            }
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne();
            String invoiceTypeId = invoice.getString("invoiceTypeId");
            if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) {
                isReturn = true;
            } else if (!"SALES_INVOICE".equals(invoiceTypeId)) {
                Debug.logWarning("This type of invoice has no commission; returning success", module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale));
            }
            invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId)
                    .queryList();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        // Map of commission Lists (of Maps) for each party.
        // Determine commissions for various parties.
        for (GenericValue invoiceItem : invoiceItems) {
            BigDecimal amount = ZERO;
            BigDecimal quantity = ZERO;
            quantity = invoiceItem.getBigDecimal("quantity");
            amount = invoiceItem.getBigDecimal("amount");
            amount = isReturn ? amount.negate() : amount;
            String productId = invoiceItem.getString("productId");
            String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
            String invoiceId = invoiceItem.getString("invoiceId");
            // Determine commission parties for this invoiceItem
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> resultMap = null;
                try {
                    resultMap = dispatcher.runSync("getCommissionForProduct",
                            UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId,
                                    "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId",
                                    invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity",
                                    quantity, "userLogin", userLogin));
                } catch (GenericServiceException e) {
                    return ServiceUtil.returnError(e.getMessage());
                }
                // build a Map of partyIds (both to and from) in a commission and the amounts
                // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
                List<Map<String, Object>> itemCommissions = UtilGenerics
                        .checkList(resultMap.get("commissions"));
                if (UtilValidate.isNotEmpty(itemCommissions)) {
                    for (Map<String, Object> commissionMap : itemCommissions) {
                        commissionMap.put("invoice", invoice);
                        commissionMap.put("appliedFraction", appliedFraction);
                        if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom"))
                                || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
                            continue;
                        }
                        String partyIdFromTo = (String) commissionMap.get("partyIdFrom")
                                + (String) commissionMap.get("partyIdTo");
                        if (!commissionParties.containsKey(partyIdFromTo)) {
                            commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                        } else {
                            (commissionParties.get(partyIdFromTo)).add(commissionMap);
                        }
                    }
                }
            }
        }
    }
    Timestamp now = UtilDateTime.nowTimestamp();
    // Create invoice for each commission receiving party
    for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
        List<GenericValue> toStore = FastList.newInstance();
        List<Map<String, Object>> commList = commissionParty.getValue();
        // get the billing parties
        if (UtilValidate.isEmpty(commList)) {
            continue;
        }
        // From and To are reversed between commission and invoice
        String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom");
        String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo");
        GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice");
        BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction");
        Long days = (Long) (commList.get(0)).get("days");
        // create the invoice record
        // To and From are in commission's sense, opposite for invoice
        Map<String, Object> createInvoiceMap = FastMap.newInstance();
        createInvoiceMap.put("partyId", partyIdBillTo);
        createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
        createInvoiceMap.put("invoiceDate", now);
        // if there were days associated with the commission agreement, then set a dueDate for the invoice.
        if (days != null) {
            createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days));
        }
        createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE");
        // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
        createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS");
        createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
        createInvoiceMap.put("userLogin", userLogin);
        // store the invoice first
        Map<String, Object> createInvoiceResult = null;
        try {
            createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
        } catch (GenericServiceException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null,
                    createInvoiceResult);
        }
        String invoiceId = (String) createInvoiceResult.get("invoiceId");
        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue partyContactMechPurpose = null;
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "BILLING_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "PAYMENT_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        // create the item records
        for (Map<String, Object> commissionMap : commList) {
            BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction);
            BigDecimal quantity = (BigDecimal) commissionMap.get("quantity");
            String invoiceIdFrom = (String) commissionMap.get("invoiceId");
            String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId");
            elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
            Map<String, Object> resMap = null;
            try {
                resMap = dispatcher.runSync("createInvoiceItem",
                        UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"),
                                "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount",
                                elemAmount, "userLogin", userLogin));
                dispatcher.runSync("createInvoiceItemAssoc",
                        UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom",
                                invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo",
                                resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE",
                                "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity",
                                quantity, "amount", elemAmount, "userLogin", userLogin));
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            if (ServiceUtil.isError(resMap)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale),
                        null, null, resMap);
            }
        }
        // store value objects
        try {
            delegator.storeAll(toStore);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem",
                            UtilMisc.toMap("reason", e.toString()), locale));
        }
        invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId,
                "salesRepresentative ", partyIdBillFrom));
    }
    String invCreated = new Integer(invoicesCreated.size()).toString();
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
            "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale));
    Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module);
    result.put("invoicesCreated", invoicesCreated);
    return result;
}

From source file:org.openbel.framework.internal.KAMStoreDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from   w w w  .ja  v  a 2  s.c  o  m
public Integer getKamNodeId(String belTermString) throws SQLException {
    // See if the bel term is already mapped
    if (supportingTermLabelReverseCache.containsKey(belTermString)) {
        return supportingTermLabelReverseCache.get(belTermString);
    }

    // parse the BelTerm
    Term term;
    try {
        term = BELParser.parseTerm(belTermString);
    } catch (Exception e) {
        // invalid BEL
        return null;
    }

    Collection<Integer> possibleTermIds = null;
    int ordinal = 0;
    for (Parameter param : term.getAllParametersLeftToRight()) {
        Integer namespaceId = null;
        if (param.getNamespace() != null && StringUtils.isNotBlank(param.getNamespace().getPrefix())) {
            Namespace ns = getNamespaceByPrefix(param.getNamespace().getPrefix());
            if (ns != null) {
                namespaceId = ns.getId();
            }
        }
        String paramValue = param.getValue();
        if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) {
            paramValue = paramValue.substring(1, paramValue.length() - 1);
        }

        Integer valueOid = getObjectIdByValue(paramValue);
        if (valueOid == null) {
            // could not find label for param
            if (possibleTermIds != null) {
                possibleTermIds.clear();
            }
            break;
        }

        ResultSet rset = null;
        try {
            PreparedStatement ps = getPreparedStatement(SELECT_TERM_ID_BY_PARAMETERS_SQL);
            // set twice to handle is null, see http://stackoverflow.com/questions/4215135/
            if (namespaceId == null) {
                ps.setNull(1, Types.INTEGER);
                ps.setNull(2, Types.INTEGER);
            } else {
                ps.setInt(1, namespaceId);
                ps.setInt(2, namespaceId);
            }

            ps.setInt(3, valueOid);
            ps.setInt(4, ordinal);

            rset = ps.executeQuery();

            Set<Integer> termIdsWithParam = new HashSet<Integer>();
            while (rset.next()) {
                termIdsWithParam.add(rset.getInt(1));
            }

            if (possibleTermIds == null) {
                // first param
                possibleTermIds = termIdsWithParam;
            } else {
                possibleTermIds = CollectionUtils.intersection(possibleTermIds, termIdsWithParam);
            }
        } finally {
            close(rset);
        }

        // no need to continue to next param if possibleTermIds is empty
        if (possibleTermIds.isEmpty()) {
            break;
        }
        ordinal++;
    }

    Integer kamNodeId = null;
    // iterate over all possible terms and check for label matches
    if (possibleTermIds != null) {
        for (Integer termId : possibleTermIds) {
            BelTerm belTerm = getBelTermById(termId);
            if (belTerm.getLabel().equals(belTermString)) {
                kamNodeId = getKamNodeId(belTerm);
                break;
            }
        }
    }

    if (kamNodeId != null) {
        supportingTermLabelReverseCache.put(belTermString, kamNodeId);
    }
    return kamNodeId;
}

From source file:org.openconcerto.utils.change.CollectionChangeEvent.java

public Collection getItemsNotChanged() {
    return CollectionUtils.intersection((Collection) this.getNewValue(), (Collection) this.getOldValue());
}

From source file:org.opencyc.constraintsolver.ForwardCheckingSearcher.java

/**
 * Performs forward checking of applicable rules to restrict the domains of remaining
 * variables.  Returns <tt>true</tt> iff no remaining variable domains are wiped out.
 *
 * @param remainingVariables the <tt>ArrayList</tt> of variables for which no domain
 * values have yet been bound//from  w w  w  . ja  v a  2s . co  m
 * @param currentBinding the current variable and bound value
 * @return <tt>true</tt> iff no remaining variable domains are wiped out
 */
protected boolean checkForwardRules(ArrayList remainingVariables, int level, Binding currentBinding)
        throws IOException, CycApiException {
    if (verbosity > 8)
        System.out.println("check forward rules applicable to binding " + currentBinding);
    for (int i = 0; i < constraintRules.size(); i++) {
        ConstraintRule rule = (ConstraintRule) constraintRules.get(i);
        ArrayList ruleVariables = rule.getVariables();
        if (verbosity > 8)
            System.out
                    .println("check forward rule \n  " + rule.cyclify() + "  with variables " + ruleVariables);
        if ((rule.getArity() > 1) && ruleVariables.contains(currentBinding.getCycVariable())) {
            // ConstraintRule applies to the selected variable.
            ArrayList remainingRuleVariables = (ArrayList) CollectionUtils.intersection(remainingVariables,
                    ruleVariables);
            if (remainingRuleVariables.size() > 0) {
                // It can rule out remaining variable values.

                if (verbosity > 4)
                    System.out.println("Applicable rule \n  " + rule.cyclify() + "  for "
                            + currentBinding.getCycVariable().cyclify());
                if (!checkForwardRule(rule, remainingRuleVariables, level, currentBinding))
                    // found a forward rule which wipes out a domain
                    return false;
            }
        }
    }
    return true;
}

From source file:org.openmrs.module.camerwa.db.hibernate.HibernateCamerwaDAO.java

public Collection treeCollectionsIntersection(Collection coll1, Collection coll2, Collection coll3) {
    return CollectionUtils.intersection(coll1, CollectionUtils.intersection(coll2, coll3));
}

From source file:org.openmrs.module.camerwa.db.hibernate.HibernateCamerwaDAO.java

public Collection twoCollectionsIntersection(Collection coll1, Collection coll2) {
    return CollectionUtils.intersection(coll1, coll2);
}

From source file:org.openmrs.module.camerwa.db.hibernate.HibernateCamerwaDAO.java

public Collection faurCollectionsIntersection(Collection coll1, Collection coll2, Collection coll3,
        Collection coll4) {/*  www  .  java  2 s  . c  o  m*/
    return CollectionUtils.intersection(CollectionUtils.intersection(coll1, coll2),
            CollectionUtils.intersection(coll3, coll4));
}

From source file:org.openmrs.module.cccgenerator.web.controller.CCCGeneratorFormController.java

@RequestMapping(method = RequestMethod.POST, value = "module/cccgenerator/cccgeneratorForm.form")
public void whenPageIsPosted(ModelMap map, HttpServletRequest request,
        @RequestParam(required = false, value = "site") String siteId,
        @RequestParam(required = true, value = "cohort") String cohortdefuuid) {
    //lengthen the session to make sure generation is complete
    HttpSession httpSession = request.getSession();
    Integer httpSessionvalue = httpSession.getMaxInactiveInterval();
    httpSession.setMaxInactiveInterval(-1);

    CCCGeneratorService service = Context.getService(CCCGeneratorService.class);
    EncounterService encounterservice = Context.getEncounterService();
    AdministrationService adminservice = Context.getAdministrationService();
    PatientService pService = Context.getPatientService();
    LocationService locservice = Context.getLocationService();
    List<Patient> listOfHIVPatientsPerSite = new ArrayList<Patient>();
    Set<Integer> patientIdsFromCohort = null;
    ///////try to find all the required ids for patient

    CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class);
    List<CohortDefinition> listOfCohorts = cohortDefinitionService.getAllDefinitions(false);

    List<Location> listOfLocations = Context.getLocationService().getAllLocations(false);

    map.addAttribute("listOfCohort", listOfCohorts);

    CohortDefinition cohortDefinition = Context.getService(CohortDefinitionService.class)
            .getDefinitionByUuid(cohortdefuuid);
    try {//from w w  w  .  j a v a2s  .  com
        EvaluationContext evaluationContext = new EvaluationContext();

        //add loctation to be displayed here
        ///evaluationContext.addParameterValue("locationList",Arrays.asList(Context.getLocationService().getLocation(Integer.parseInt(siteId))));

        //evaluation
        Cohort cohort = cohortDefinitionService.evaluate(cohortDefinition, evaluationContext);
        patientIdsFromCohort = new HashSet<Integer>();
        patientIdsFromCohort.addAll(cohort.getMemberIds());

    } catch (Exception e) {
        e.printStackTrace();
    }
    //////////////////////////////////////////////////

    //get the location from the jsp interface
    Location siteLocation = locservice.getLocation(Integer.parseInt(siteId));

    map.addAttribute("location1", siteLocation.getName());
    Integer CCC = 0;
    Integer lastcount = 0;
    String CCCIdentifier = "";
    String glbCCC = "";
    int number_of_hiv_patients_affected = 0;
    int number_of_hiv_patients_affected_generated = 0;

    //cohort to return all patient ids

    log.info("Get all patients who are  HIV positive " + patientIdsFromCohort.size());

    //get cohort of all the patient ids in the database
    Cohort allpatientscohort = Context.getPatientSetService().getAllPatients();

    Set<Integer> allpatientscohortset = allpatientscohort.getMemberIds();

    log.info("All patients in the databse are " + allpatientscohortset.size());

    //get all patients to exclude from the set
    Set<Integer> toExclude = new HashSet<Integer>(
            Context.getService(CCCGeneratorService.class).excludeDiscontinued().getMemberIds());
    log.info("The number of patients discontinued from care " + toExclude.size());

    //remove the above from the patientIdsFromCohort to get only true matches

    patientIdsFromCohort.removeAll(toExclude);
    //get the intersection of only the patients who are present no empty slots

    Set<Integer> uniqueSetids = new HashSet<Integer>(
            CollectionUtils.intersection(allpatientscohortset, patientIdsFromCohort));

    log.info("Only unique numbers selected " + uniqueSetids.size());

    //get aready generated members
    Cohort listOfHIVPatientIdAlreadygenerated = service.getAllHIVPatients();
    Set<Integer> listOfHIVPatientIdAlreadygeneratedpatientsIds = new HashSet<Integer>(
            listOfHIVPatientIdAlreadygenerated.getMemberIds());

    log.info("Already generated ones are " + listOfHIVPatientIdAlreadygeneratedpatientsIds.size());

    //get the difference in number of HIV patients

    uniqueSetids.removeAll(listOfHIVPatientIdAlreadygeneratedpatientsIds);

    log.info("Difference comes in here excluding already generated ones " + uniqueSetids.size());

    Patient patients;

    int count = 0;

    for (Integer patientId : uniqueSetids) {
        count++;
        log.info("This patient Number " + patientId + " and this number " + count + " Remaining "
                + (uniqueSetids.size() - count));
        cleanupafterCount(count);
        patients = pService.getPatient(patientId);

        List<Encounter> listOfEncounters = encounterservice.getEncountersByPatientId(patientId);

        Collections.sort(listOfEncounters, new SortEncountersByDateComparator());

        for (Encounter encounters : listOfEncounters) {

            log.info("Got in the encounters loop");

            if (encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ADULT_INITIAL)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ADULT_RETURN)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PEDS_INITIAL)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PEDS_RETURN)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_BASELINE_INVESTIGATION)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PMTCTANC)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_PMTCTPOSTNATAL)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ECPeds)
                    || encounters.getEncounterType().getName().equals(ENCOUNTER_TYPE_ECSTABLE)) {

                // log.info("Found a patient having HIV encounters");
                // log.info("Locations are seen here if equal is when we enter the loop ");
                log.info(encounters.getLocation() + "==" + locservice.getLocation(Integer.parseInt(siteId)));
                //starts here
                //get all the related locations in the database

                Set<Integer> getAllLocations = Context.getService(CCCGeneratorService.class)
                        .getIdsOfLocationsParentAndChildren(Integer.parseInt(siteId));
                log.info("All locations and their sub sites " + getAllLocations.size());
                for (Integer i : getAllLocations) {
                    if (encounters.getLocation() == locservice.getLocation(i)) {

                        log.info("Checking for provided location from the encounters");

                        CCCLocation ml = service
                                .getCCCLocationByLocation(locservice.getLocation(Integer.parseInt(siteId)));

                        //we pick the unique number for every facility
                        CCC = ml.getCCC();

                        //using CCC above we check for the last count
                        CCCCount mc = service.getCCCCountByCCC(CCC);
                        lastcount = mc.getLastCount();
                        log.info("This the last count per the location and CCC " + lastcount);

                        //we increament the count by one

                        lastcount++;
                        String pCCCIdentifier = "" + lastcount;

                        //check for the number of digits required to be concatnated to facility number
                        if (pCCCIdentifier.length() < 5) {
                            int x = 5 - pCCCIdentifier.length();
                            String y = "";
                            for (int k = 0; k < x; k++)
                                y += "0";
                            pCCCIdentifier = y + pCCCIdentifier;
                        }
                        CCCIdentifier = CCC + "-" + pCCCIdentifier;

                        glbCCC = adminservice.getGlobalProperty("cccgenerator.CCC");

                        PatientIdentifierType patientIdentifierType = pService
                                .getPatientIdentifierTypeByName(glbCCC);

                        List<PatientIdentifier> listOfCCCIdentifier = pService.getPatientIdentifiers(null,
                                Arrays.asList(patientIdentifierType), Arrays.asList(locservice.getLocation(i)),
                                Arrays.asList(patients), false);

                        log.info("Already patients ids per CCC " + listOfCCCIdentifier.size());
                        if (listOfCCCIdentifier.size() == 0) {

                            //}

                            PatientIdentifier patientIdentifier = new PatientIdentifier();

                            patientIdentifier.setPatient(patients);
                            patientIdentifier.setIdentifier(CCCIdentifier);
                            patientIdentifier.setIdentifierType(patientIdentifierType);
                            patientIdentifier.setLocation(locservice.getLocation(i));
                            patientIdentifier.setPreferred(false);

                            mc.setLastCount(lastcount);
                            //save the count thereby rewriting the previous one
                            service.saveCCCCount(mc);
                            Integer thecountLast = null;
                            Integer CCCcount = null;
                            CCCCount thecount = service.getCCCCountByCCC(CCC);
                            thecountLast = thecount.getCCC();
                            CCCcount = thecount.getLastCount();

                            //log.info("This is the count  "+CCCcount+" and CCC is "+thecountLast);

                            //add and save patient identserifier
                            pService.savePatientIdentifier(patientIdentifier);

                            number_of_hiv_patients_affected += 1;

                            number_of_hiv_patients_affected_generated += number_of_hiv_patients_affected;
                            //add the patients to the list so that we can use in the jsp
                            listOfHIVPatientsPerSite.add(patients);
                            ////////////////////////////////////////////////////////////////////////

                            //CCCCount allCCC=new CCCCount();
                            //update all other related sites
                            List<CCCCount> allCCC = service.getAllRelatedSites(thecountLast);
                            //log.info("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu "+allCCC.size());
                            //log.info("This is the CCC sizes "+allCCC.getLocation());
                            for (CCCCount m : allCCC) {
                                m.setLastCount(CCCcount);
                                service.saveCCCCount(m);
                            }

                            // log.info("After the count has been changed ");
                            ////////////////////////////////////////////////////////////////////////

                            cleanupaftersaving(number_of_hiv_patients_affected);
                        } else {
                            continue;
                        }

                    }

                }

            }

            break;

        }

    }
    List<Location> locations = locservice.getAllLocations(false);
    map.addAttribute("siteLocations", locations);
    map.addAttribute("totalcccnumbersgenerated", listOfHIVPatientsPerSite.size());
    httpSession.setMaxInactiveInterval(httpSessionvalue);

}

From source file:org.openmrs.module.odkconnector.serialization.processor.HttpProcessor.java

/**
 * Process any stream connection to this module
 *
 * @param inputStream  the input stream//from w  w w  .j  a va 2s  . co  m
 * @param outputStream the output stream
 * @throws Exception when the stream processing failed
 */
@Override
public void process(final InputStream inputStream, final OutputStream outputStream) throws Exception {

    GZIPInputStream gzipInputStream = new GZIPInputStream(new BufferedInputStream(inputStream));

    DataInputStream dataInputStream = new DataInputStream(gzipInputStream);
    String username = dataInputStream.readUTF();
    String password = dataInputStream.readUTF();
    Boolean savedSearch = dataInputStream.readBoolean();
    Integer cohortId = 0;
    Integer programId = 0;
    if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) {
        cohortId = dataInputStream.readInt();
        programId = dataInputStream.readInt();
    }
    dataInputStream.close();

    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new BufferedOutputStream(outputStream));
    DataOutputStream dataOutputStream = new DataOutputStream(gzipOutputStream);
    try {
        Context.openSession();
        Context.authenticate(username, password);

        dataOutputStream.writeInt(HttpURLConnection.HTTP_OK);
        dataOutputStream.flush();

        if (log.isDebugEnabled()) {
            log.debug("Saved Search Value: " + savedSearch);
            log.debug("Cohort ID: " + cohortId);
            log.debug("Program ID: " + programId);
        }

        Serializer serializer = HandlerUtil.getPreferredHandler(Serializer.class, List.class);
        if (StringUtils.equalsIgnoreCase(getAction(), HttpProcessor.PROCESS_PATIENTS)) {
            ConnectorService connectorService = Context.getService(ConnectorService.class);

            Cohort cohort = new Cohort();
            if (savedSearch) {
                CohortSearchHistory history = new CohortSearchHistory();
                PatientSearchReportObject patientSearchReportObject = (PatientSearchReportObject) Context
                        .getReportObjectService().getReportObject(cohortId);
                if (patientSearchReportObject != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Object Class: " + patientSearchReportObject.getClass());
                        log.debug("Object Name: " + patientSearchReportObject.getName());
                        log.debug("Object Subtype: " + patientSearchReportObject.getSubType());
                        log.debug("Object Type: " + patientSearchReportObject.getType());
                    }
                    history.addSearchItem(PatientSearch.createSavedSearchReference(cohortId));
                    cohort = history.getPatientSet(0, null);
                }
            } else {
                cohort = Context.getCohortService().getCohort(cohortId);
            }

            if (log.isDebugEnabled())
                log.debug("Cohort data: " + cohort.getMemberIds());

            log.info("Streaming patients information!");
            serializer.write(dataOutputStream, connectorService.getCohortPatients(cohort));

            // check the concept list
            Collection<Concept> concepts = null;
            ConceptConfiguration conceptConfiguration = connectorService.getConceptConfiguration(programId);
            if (conceptConfiguration != null) {

                if (log.isDebugEnabled())
                    log.debug("Printing concept configuration information: " + conceptConfiguration);

                concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts());
            }
            log.info("Streaming observations information!");
            serializer.write(dataOutputStream, connectorService.getCohortObservations(cohort, concepts));

            // evaluate and get the applicable form for the patients
            CohortDefinitionService cohortDefinitionService = Context.getService(CohortDefinitionService.class);
            ReportingConnectorService reportingService = Context.getService(ReportingConnectorService.class);
            List<ExtendedDefinition> definitions = reportingService.getAllExtendedDefinition();

            EvaluationContext context = new EvaluationContext();
            context.setBaseCohort(cohort);

            Collection intersectedMemberIds = Collections.emptyList();
            List<SerializedForm> serializedForms = new ArrayList<SerializedForm>();
            for (ExtendedDefinition definition : definitions) {
                if (definition.containsProperty(ExtendedDefinition.DEFINITION_PROPERTY_FORM)) {

                    if (log.isDebugEnabled())
                        log.debug("Evaluating: " + definition.getCohortDefinition().getName());

                    EvaluatedCohort evaluatedCohort = cohortDefinitionService
                            .evaluate(definition.getCohortDefinition(), context);
                    // the cohort could be null, so we don't want to get exception during the intersection process
                    if (cohort != null)
                        intersectedMemberIds = CollectionUtils.intersection(cohort.getMemberIds(),
                                evaluatedCohort.getMemberIds());

                    if (log.isDebugEnabled())
                        log.debug("Cohort data after intersection: " + intersectedMemberIds);

                    for (DefinitionProperty definitionProperty : definition.getProperties()) {
                        // skip retired definition property
                        if (definitionProperty.isRetired())
                            continue;

                        Integer formId = NumberUtils.toInt(definitionProperty.getPropertyValue());
                        for (Object patientId : intersectedMemberIds)
                            serializedForms.add(
                                    new SerializedForm(NumberUtils.toInt(String.valueOf(patientId)), formId));
                    }
                }
            }

            if (log.isDebugEnabled())
                log.debug("Serialized form informations:" + serializedForms);

            log.info("Streaming forms information!");
            serializer.write(dataOutputStream, serializedForms);

        } else {
            if (savedSearch) {
                List<SerializedCohort> serializedCohorts = new ArrayList<SerializedCohort>();
                List<AbstractReportObject> objects = Context.getReportObjectService()
                        .getReportObjectsByType(OpenmrsConstants.REPORT_OBJECT_TYPE_PATIENTSEARCH);
                for (AbstractReportObject object : objects) {
                    SerializedCohort serializedCohort = new SerializedCohort();
                    serializedCohort.setId(object.getReportObjectId());
                    serializedCohort.setName(object.getName());
                    serializedCohorts.add(serializedCohort);
                }
                serializer.write(dataOutputStream, serializedCohorts);

            } else {
                serializer.write(dataOutputStream, Context.getCohortService().getAllCohorts());
            }
        }

        dataOutputStream.close();
    } catch (Exception e) {
        log.error("Processing stream failed!", e);
        dataOutputStream.writeInt(HttpURLConnection.HTTP_UNAUTHORIZED);
        dataOutputStream.close();
    } finally {
        Context.closeSession();
    }
}

From source file:org.openmrs.module.odkconnector.web.controller.concept.ManageConceptController.java

@RequestMapping(value = "/module/odkconnector/concept/manageConcept", method = RequestMethod.POST)
public void process(final @RequestParam(value = "conceptUuids", required = true) String conceptUuids,
        final @RequestParam(value = "configurationUuid", required = true) String configurationUuid,
        final Model model, final HttpServletRequest request) {

    ConnectorService service = Context.getService(ConnectorService.class);
    ConceptConfiguration conceptConfiguration = service.getConceptConfigurationByUuid(configurationUuid);

    // the uuids coming from the web page. might contains new uuid and will not contains retired uuid
    Set<String> createdConceptUuidValues = new LinkedHashSet<String>(
            Arrays.asList(StringUtils.split(StringUtils.defaultString(conceptUuids), ",")));
    // the saved uuids. might contains retired uuid and will not contains new uuid
    Set<String> savedConceptUuidValues = new LinkedHashSet<String>();
    for (ConfiguredConcept configuredConcept : conceptConfiguration.getConfiguredConcepts()) {
        if (!configuredConcept.isRetired()) {
            Concept concept = configuredConcept.getConcept();
            savedConceptUuidValues.add(concept.getUuid());
        }//from w w  w .  j  a  v a  2 s  .  c  o  m
    }

    Collection intersectedUuids = CollectionUtils.intersection(createdConceptUuidValues,
            savedConceptUuidValues);
    Collection retiredConceptUuids = CollectionUtils.subtract(savedConceptUuidValues, intersectedUuids);
    Collection createdConceptUuids = CollectionUtils.subtract(createdConceptUuidValues, intersectedUuids);

    for (ConfiguredConcept configuredConcept : conceptConfiguration.getConfiguredConcepts()) {
        Concept concept = configuredConcept.getConcept();
        if (retiredConceptUuids.contains(concept.getUuid())) {
            configuredConcept.setRetired(Boolean.TRUE);
            configuredConcept.setRetiredBy(Context.getAuthenticatedUser());
            configuredConcept.setDateRetired(new Date());
        }
    }

    for (Object conceptUuid : createdConceptUuids) {
        Concept concept = Context.getConceptService().getConceptByUuid(String.valueOf(conceptUuid));
        if (concept != null) {
            ConfiguredConcept configuredConcept = new ConfiguredConcept();
            configuredConcept.setConcept(concept);
            configuredConcept.setConceptConfiguration(conceptConfiguration);
            conceptConfiguration.addConfiguredConcept(configuredConcept);
        }
    }
    service.saveConceptConfiguration(conceptConfiguration);

    Set<Concept> concepts = ConnectorUtils.getConcepts(conceptConfiguration.getConfiguredConcepts());
    model.addAttribute("configuration", conceptConfiguration);
    model.addAttribute("concepts", concepts);
    model.addAttribute("conceptUuids", ConnectorUtils.convertString(ConnectorUtils.getConceptUuids(concepts)));
}