Example usage for java.lang Double intValue

List of usage examples for java.lang Double intValue

Introduction

In this page you can find the example usage for java.lang Double intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Double as an int after a narrowing primitive conversion.

Usage

From source file:org.opentaps.amazon.product.AmazonProductServices.java

/**
 * Posts inventory data relating to any new or changed AmazonProductInventory records to Amazon.
 * @param dctx a <code>DispatchContext</code> value
 * @param context the service context <code>Map</code>
 * @return the service response <code>Map</code>
 *///from   w  w  w .  ja v a  2s  . co  m
public static Map<String, Object> publishProductInventoryToAmazon(DispatchContext dctx,
        Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    String prodId = (String) context.get("productId");
    boolean postActualInventory = AmazonConstants.postActualInventory;

    try {

        List<EntityCondition> conditions = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition(
                "statusId", EntityOperator.IN, Arrays.asList(AmazonConstants.statusProductCreated,
                        AmazonConstants.statusProductError, AmazonConstants.statusProductChanged)));
        if (UtilValidate.isNotEmpty(prodId)) {
            conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, prodId));
        }

        TransactionUtil.begin();
        EntityListIterator amazonInventoryIt = delegator.findListIteratorByCondition("AmazonProductInventory",
                EntityCondition.makeCondition(conditions, EntityOperator.AND), null,
                Arrays.asList("productId"));
        TransactionUtil.commit();

        GenericValue productStore = delegator.findByPrimaryKey("ProductStore",
                UtilMisc.toMap("productStoreId", AmazonConstants.productStoreId));

        long messageId = 1;
        Map<GenericValue, String> invalidAmazonInventory = new HashMap<GenericValue, String>();
        List<GenericValue> validAmazonInventory = new ArrayList<GenericValue>();
        Document inventoryDoc = AmazonConstants.soapClient
                .createDocumentHeader(AmazonConstants.messageTypeInventory);
        GenericValue amazonProductInventory = null;
        while ((amazonProductInventory = amazonInventoryIt.next()) != null) {

            String errMessage = null;

            // Check that the failure threshold has not been reached previously
            if (AmazonConstants.productPostRetryThreshold <= amazonProductInventory.getLong("postFailures")
                    .intValue()) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostImageAttemptsOverThreshold",
                        UtilMisc.<String, Object>toMap("productId",
                                amazonProductInventory.getString("productId"), "threshold",
                                AmazonConstants.productPostRetryThreshold),
                        locale);
                Debug.logInfo(errorLog, MODULE);
                continue;
            }

            // Check if this product was exported and acknowledged earlier
            if (delegator.findCountByAnd("AmazonProduct",
                    UtilMisc.toMap("productId", amazonProductInventory.getString("productId"), "statusId",
                            AmazonConstants.statusProductPosted, "ackStatusId",
                            AmazonConstants.statusProductAckRecv)) != 1) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostInventoryNonExistentProduct",
                        UtilMisc.toMap("productId", amazonProductInventory.getString("productId")), locale);
                Debug.logError(errorLog, MODULE);
                continue;
            }

            // Ignore products marked deleted
            if (AmazonUtil.isAmazonProductDeleted(delegator, amazonProductInventory.getString("productId"))) {
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_IgnoringProductInventory_ProductDeleted",
                        UtilMisc.toMap("productId", amazonProductInventory.getString("productId")), locale);
                Debug.logError(errorLog, MODULE);
                continue;
            }

            String upc = null;
            if (AmazonConstants.requireUpcCodes || AmazonConstants.useUPCAsSKU) {

                // Establish and validate the UPC
                upc = getProductUPC(delegator, amazonProductInventory.getString("productId"), locale);
                if (UtilValidate.isEmpty(upc) && AmazonConstants.requireUpcCodes) {
                    errMessage = AmazonUtil.compoundError(errMessage,
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_MissingCodeUPC",
                                    UtilMisc.toMap("productId", amazonProductInventory.getString("productId")),
                                    locale));
                } else if (UtilValidate.isNotEmpty(upc) && !UtilProduct.isValidUPC(upc)) {
                    errMessage = AmazonUtil.compoundError(errMessage,
                            UtilProperties.getMessage(AmazonConstants.errorResource,
                                    "AmazonError_InvalidCodeUPC",
                                    UtilMisc.toMap("productId", amazonProductInventory.getString("productId")),
                                    locale));
                }
            }

            // Establish and validate the SKU
            String sku = getProductSKU(delegator, amazonProductInventory, upc);
            if (UtilValidate.isEmpty(sku) && !AmazonConstants.useUPCAsSKU) {
                errMessage = AmazonUtil.compoundError(errMessage,
                        UtilProperties.getMessage(AmazonConstants.errorResource,
                                "AmazonError_NoRequiredParameter", UtilMisc.toMap("parameterName", "SKU",
                                        "productName", amazonProductInventory.getString("productId")),
                                locale));
            }

            if (UtilValidate.isNotEmpty(errMessage)) {
                invalidAmazonInventory.put(amazonProductInventory, errMessage);
                continue;
            }

            Element message = UtilXml.addChildElement(inventoryDoc.getDocumentElement(), "Message",
                    inventoryDoc);
            UtilXml.addChildElementValue(message, "MessageID", "" + messageId, inventoryDoc);
            UtilXml.addChildElementValue(message, "OperationType", "Update", inventoryDoc);
            Element invElement = UtilXml.addChildElement(message, "Inventory", inventoryDoc);
            UtilXml.addChildElementValue(invElement, "SKU", sku, inventoryDoc);

            Double atp = new Double(0);
            TransactionUtil.begin();
            Map<String, Object> serviceResult = dispatcher.runSync("getInventoryAvailableByFacility",
                    UtilMisc.toMap("productId", amazonProductInventory.getString("productId"), "facilityId",
                            productStore.getString("inventoryFacilityId"), "userLogin", userLogin));
            TransactionUtil.commit();
            if (serviceResult.containsKey("availableToPromiseTotal")) {
                atp = (Double) serviceResult.get("availableToPromiseTotal");
            }

            // Amazon doesn't like inventory values < 0
            if (atp.doubleValue() < 0) {
                atp = new Double(0);
            }

            // Amazon doesn't like inventory values > 99,999,999
            if (atp.doubleValue() > 99999999) {
                postActualInventory = false;
            }

            GenericValue productFacility = delegator.findByPrimaryKey("ProductFacility",
                    UtilMisc.toMap("productId", amazonProductInventory.getString("productId"), "facilityId",
                            productStore.getString("inventoryFacilityId")));

            // Post inventory as Available if ProductFacility.minimumStock > 0 and AmazonConstants.inventoryIsAvailableIfMinimumStock, even if there is no actual inventory
            boolean available = atp.intValue() > 0;
            if ((!available) && AmazonConstants.inventoryIsAvailableIfMinimumStock
                    && UtilValidate.isNotEmpty(productFacility)
                    && UtilValidate.isNotEmpty(productFacility.getDouble("minimumStock"))
                    && productFacility.getDouble("minimumStock").doubleValue() > 0) {
                postActualInventory = false;
                available = true;
            }

            if (postActualInventory) {
                UtilXml.addChildElementValue(invElement, "Quantity", "" + atp.intValue(), inventoryDoc);
            } else {
                UtilXml.addChildElementValue(invElement, "Available", available ? "true" : "false",
                        inventoryDoc);
            }

            if (AmazonConstants.postInventoryDaysToShip && UtilValidate.isNotEmpty(productFacility)
                    && UtilValidate.isNotEmpty(productFacility.get("daysToShip"))) {
                long daysToShip = productFacility.getLong("daysToShip").longValue();

                // Amazon doesn't like FulfillmentLatency > 30
                if (daysToShip > 30) {
                    daysToShip = 30;
                }

                // Amazon doesn't like FulfillmentLatency <= 0
                if (daysToShip > 0) {
                    UtilXml.addChildElementValue(invElement, "FulfillmentLatency", "" + daysToShip,
                            inventoryDoc);
                }
            }

            amazonProductInventory.set("acknowledgeMessageId", "" + messageId);
            validAmazonInventory.add(amazonProductInventory);
            messageId++;
            if (messageId % 500 == 0)
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_Processed_Records_Inventory", UtilMisc.toMap("count", messageId), locale),
                        MODULE);
        }
        amazonInventoryIt.close();

        LinkedHashMap<GenericValue, String> emailErrorMessages = new LinkedHashMap<GenericValue, String>();

        if (UtilValidate.isEmpty(validAmazonInventory)) {
            String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource,
                    "AmazonError_PostNoNewProductInventory", locale);
            Debug.logInfo(infoMessage, MODULE);
        } else {

            boolean success = true;
            String postErrorMessage = null;
            long processingDocumentId = -1;
            try {
                String xml = UtilXml.writeXmlDocument(inventoryDoc);
                Debug.logVerbose(xml, MODULE);
                Writer writer = new OutputStreamWriter(
                        new FileOutputStream(AmazonConstants.xmlOutputLocation + "AmazonProductInventoryFeed_"
                                + AmazonConstants.xmlOutputDateFormat.format(new Date()) + ".xml"),
                        "UTF-8");
                writer.write(xml);
                writer.close();
                processingDocumentId = AmazonConstants.soapClient.postProductInventory(xml);
                Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_ProcessingDocumentId_Inventory",
                        UtilMisc.toMap("processingDocumentId", processingDocumentId), locale), MODULE);
            } catch (RemoteException e) {
                success = false;
                postErrorMessage = e.getMessage();
                List<String> productIds = EntityUtil.getFieldListFromEntityList(validAmazonInventory,
                        "productId", true);
                String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource,
                        "AmazonError_PostInventoryError",
                        UtilMisc.toMap("productIds", productIds, "errorMessage", postErrorMessage), locale);
                Debug.logError(errorLog, MODULE);
            }

            // Store operational data of the post attempt
            for (GenericValue validAmazonInv : validAmazonInventory) {
                validAmazonInv.set("statusId",
                        success ? AmazonConstants.statusProductPosted : AmazonConstants.statusProductError);
                validAmazonInv.set("postTimestamp", UtilDateTime.nowTimestamp());
                validAmazonInv.set("postErrorMessage", success ? null : postErrorMessage);
                if (!success) {
                    validAmazonInv.set("postFailures", validAmazonInv.getLong("postFailures") + 1);
                }
                validAmazonInv.set("processingDocumentId", success ? processingDocumentId : null);
                validAmazonInv.set("ackStatusId", AmazonConstants.statusProductNotAcked);
                validAmazonInv.set("acknowledgeTimestamp", null);
                validAmazonInv.set("acknowledgeErrorMessage", null);
                validAmazonInv.store();
                if (AmazonConstants.sendErrorEmails && !success) {
                    emailErrorMessages.put(validAmazonInv, postErrorMessage);
                }
            }
        }

        for (GenericValue invalidAmazonInv : invalidAmazonInventory.keySet()) {
            String errorMessage = invalidAmazonInventory.get(invalidAmazonInv);
            invalidAmazonInv.set("statusId", AmazonConstants.statusProductError);
            invalidAmazonInv.set("postTimestamp", UtilDateTime.nowTimestamp());
            invalidAmazonInv.set("postErrorMessage", errorMessage);
            invalidAmazonInv.set("postFailures", invalidAmazonInv.getLong("postFailures") + 1);
            invalidAmazonInv.set("processingDocumentId", null);
            invalidAmazonInv.set("ackStatusId", AmazonConstants.statusProductNotAcked);
            invalidAmazonInv.set("acknowledgeTimestamp", null);
            invalidAmazonInv.set("acknowledgeErrorMessage", null);
            invalidAmazonInv.store();
            if (AmazonConstants.sendErrorEmails) {
                emailErrorMessages.put(invalidAmazonInv, errorMessage);
            }
        }

        if (AmazonConstants.sendErrorEmails && UtilValidate.isNotEmpty(emailErrorMessages)) {
            AmazonUtil.sendBulkErrorEmail(dispatcher, userLogin, emailErrorMessages,
                    UtilProperties.getMessage(AmazonConstants.errorResource,
                            "AmazonError_ErrorEmailSubject_PostInventory", AmazonConstants.errorEmailLocale),
                    AmazonConstants.errorEmailScreenUriProducts);
        }

    } catch (GenericEntityException gee) {
        UtilMessage.createAndLogServiceError(gee, locale, MODULE);
    } catch (IOException ioe) {
        UtilMessage.createAndLogServiceError(ioe, locale, MODULE);
    } catch (GenericServiceException gse) {
        UtilMessage.createAndLogServiceError(gse, locale, MODULE);
    }

    return ServiceUtil.returnSuccess();
}

From source file:org.polymap.kaps.exporter.VertragStaBuExporter.java

private void createSegment(Element datenSegment, VertragComposite vertrag) {

    // Iterable<FlurstueckComposite> flurstuecke =
    // FlurstueckComposite.Mixin.forEntity( vertrag );
    // FlurstueckComposite flurstueck = null;
    Double bodenrichtwert = null;
    Integer baujahr = null;/* w  w w  .j a  v a  2 s.  c  o m*/
    Double wohnflaeche = null;
    GebaeudeTypStaBuComposite gebaeudeTyp = null;
    GebaeudeArtStaBuComposite gebaeudeArt = null;
    WohnlageStaBuComposite wohnlage = null;
    String stellplatz = null;
    String garage = null;
    String carport = null;

    KellerComposite keller = null;
    Double grundstuecksflaeche = null;
    VertragsdatenBaulandComposite baulandComposite = VertragsdatenBaulandComposite.Mixin.forVertrag(vertrag);
    if (baulandComposite != null) {
        bodenrichtwert = baulandComposite.richtwert().get();
        baujahr = baulandComposite.baujahr().get();
        wohnflaeche = baulandComposite.wohnflaeche().get();
        gebaeudeTyp = baulandComposite.gebaeudeTypStaBu().get();
        gebaeudeArt = baulandComposite.gebaeudeArtStaBu().get();
        keller = baulandComposite.keller().get();
        wohnlage = baulandComposite.wohnlageStaBu().get();
        stellplatz = baulandComposite.stellplaetze().get();
        carport = baulandComposite.carport().get();
        garage = baulandComposite.garage().get();
        grundstuecksflaeche = baulandComposite.verkaufteFlaeche().get();
    }
    FlurstueckComposite flurstueck = null;
    for (FlurstueckComposite f : FlurstueckComposite.Mixin.forEntity(vertrag)) {
        NutzungComposite nutzung = f.nutzung().get();
        if (nutzung != null && nutzung.isAgrar().get() != null && !nutzung.isAgrar().get().booleanValue()) {
            flurstueck = f;
            break;
        }
    }

    NutzungComposite nutzung = flurstueck.nutzung().get();
    Calendar cal = new GregorianCalendar();
    cal.setTime(vertrag.vertragsDatum().get());

    GemarkungComposite gemarkung = flurstueck.gemarkung().get();
    GemeindeComposite gemeinde = gemarkung != null ? gemarkung.gemeinde().get() : null;

    KaeuferKreisComposite verkaeufer = vertrag.verkaeuferKreis().get();
    KaeuferKreisStaBuComposite veraeusserer = verkaeufer != null ? verkaeufer.kaeuferKreisStabu().get() : null;

    KaeuferKreisComposite kaeufer = vertrag.kaeuferKreis().get();
    KaeuferKreisStaBuComposite erwerber = kaeufer != null ? kaeufer.kaeuferKreisStabu().get() : null;

    ArtDerBauflaecheStaBuComposite artDerBauflaeche = nutzung.artDerBauflaeche().get();

    VertragsdatenErweitertComposite vertragsdatenErweitertComposite = vertrag.erweiterteVertragsdaten().get();
    Double kaufpreis = vertragsdatenErweitertComposite != null
            && vertragsdatenErweitertComposite.bereinigterVollpreis().get() != null
                    ? vertragsdatenErweitertComposite.bereinigterVollpreis().get()
                    : vertrag.vollpreis().get();

    // TODO Wohnflche, Baujahr
    // Liste
    // WohnungComposite wohnung = WohnungComposite.Mixin.findWohnungenFor(
    // flurstueck );

    // grundstcksflche

    Element satz = addElement(datenSegment, "satz");
    String name;
    // TODO bebaut = 1, wohneigentum = 2
    // TODO sollte hier nicht auch mal Wohneigentum auftauchen?
    // if (nutzung.isWohneigentum().get()) {
    // satz.setAttribute( "kennung", "SA-Wohneigentum" );
    // addMM( satz, "Satzart", "2" );
    // name = "Wohnungseigentum";
    // }
    // else {
    satz.setAttribute("kennung", "SA-Bebaute-Grundstcke");
    addMM(satz, "Satzart", "1");
    name = "Bebaute_Grundstuecke";
    // }

    Element mmgrOuter = addElement(satz, "mmgr");
    mmgrOuter.setAttribute("name", name);

    Element pwi = addElement(mmgrOuter, "mmgr");
    pwi.setAttribute("name", "PWI");

    addMM(pwi, "Kennummer_Kauffall", String.valueOf(vertrag.eingangsNr().get()));
    addMM(pwi, "Kaufdatum_TT", twoCol(cal.get(Calendar.DAY_OF_MONTH)));
    addMM(pwi, "Kaufdatum_MM", twoCol(cal.get(Calendar.MONTH) + 1));
    addMM(pwi, "Kaufdatum_JJJJ", String.valueOf(cal.get(Calendar.YEAR)));
    // TODO Landkreiskennung in Properties erfassen
    if (gemeinde != null) {
        addMM(pwi, "Gemeindeschluessel", "14" + gemeinde.schl().get());
    }
    if (gemarkung != null) {
        addMM(pwi, "Gemarkungsschluessel", gemarkung.schl().get());
    }
    if (veraeusserer != null) {
        addMM(pwi, "Veraeusserer", veraeusserer.schl().get());
    }
    if (erwerber != null) {
        addMM(pwi, "Erwerber", erwerber.schl().get());
    }
    if (kaufpreis != null) {
        addMM(pwi, "Kaufpreis", String.valueOf(kaufpreis.intValue()));
    }
    if (bodenrichtwert != null) {
        addMM(pwi, "Bodenrichtwert", String.valueOf(bodenrichtwert.intValue()));
    }
    if (artDerBauflaeche != null) {
        // schlssel stabu in winakps und stabexport weichen voneinander ab
        addMM(pwi, "Flaechenart", artDerBauflaeche.schl().get() == "1" ? "10" : "21");
    }
    if (baujahr != null) {
        addMM(pwi, "Baujahr", String.valueOf(baujahr.intValue()));
    }
    if (wohnflaeche != null) {
        addMM(pwi, "Wohnflaeche", String.valueOf(wohnflaeche.intValue()));
    }
    // TODO Stellplatz
    // if (carport != null && carport.equals( "J" ) ||)

    if (wohnlage != null) {
        addMM(pwi, "Lagequalitaet", wohnlage.schl().get());
    }

    // TODO Unterscheidung Wohnungseigentum vs. Grundstuecke
    // if (nutzung.isWohneigentum().get()) {
    // Element wohnungseigentum = addElement( mmgrOuter, "Wohnungseigentum" );
    // }
    // else {
    Element grundstuecke = addElement(mmgrOuter, "Grundstuecke");
    if (grundstuecksflaeche != null && grundstuecksflaeche != 0.0d) {
        addMM(grundstuecke, "Grundstuecksflaeche", String.valueOf(new Double(grundstuecksflaeche).intValue()));
    }

    if (gebaeudeArt != null) {
        addMM(grundstuecke, "Gebaeudeart", gebaeudeArt.schl().get());
    }
    if (gebaeudeTyp != null) {
        addMM(grundstuecke, "Gebaeudetyp", gebaeudeTyp.schl().get());
    }
    if (keller != null && !keller.schl().get().endsWith("1")) {
        if (keller.schl().get().equals("2")) {
            addMM(grundstuecke, "Unterkellerung", "0");
        } else {
            addMM(grundstuecke, "Unterkellerung", "1");
        }
    }

}

From source file:org.openmrs.module.kenyaemr.page.controller.FamilyAndPartnerTestingPageController.java

SimpleObject extractFamilyAndPartnerTestingRows(Set<Obs> obsList) {

    Integer contactConcept = 160750;
    Integer ageConcept = 160617;/*from w  w w . j a  v a2s  .  c o m*/
    Integer relationshipConcept = 1560;
    Integer relStatusConcept = 163607;
    Integer baselineHivStatusConcept = 1169;
    Integer nextTestingDateConcept = 164400;
    Integer ageUnitConcept = 1732;
    Integer HIVTestResultConcept = 159427;
    Integer InCareConcept = 159811;
    Integer CCCNoConcept = 162053;

    String relType = null;
    Integer age = 0;
    Double artNo = null;
    String baselineStatus = null;
    String relStatus = null;
    String inCare = null;
    String hivTestResult = null;
    String nextTestDate = null;
    String contactName = null;
    String ageUnit = null;

    for (Obs obs : obsList) {

        if (obs.getConcept().getConceptId().equals(contactConcept)) {
            contactName = obs.getValueText();
        } else if (obs.getConcept().getConceptId().equals(ageConcept)) { // get age
            age = obs.getValueNumeric().intValue();
        } else if (obs.getConcept().getConceptId().equals(baselineHivStatusConcept)) {
            baselineStatus = hivStatusConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(relStatusConcept)) { // current HIV status
            relStatus = hivStatusConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(HIVTestResultConcept)) { // HIV test result
            hivTestResult = hivStatusConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(nextTestingDateConcept)) {
            nextTestDate = DATE_FORMAT.format(obs.getValueDate());
        } else if (obs.getConcept().getConceptId().equals(CCCNoConcept)) {
            artNo = obs.getValueNumeric();
        } else if (obs.getConcept().getConceptId().equals(InCareConcept)) {
            inCare = booleanAnswerConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(relationshipConcept)) {
            relType = relationshipConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(relStatusConcept)) {
            relStatus = statusConverter(obs.getValueCoded());
        } else if (obs.getConcept().getConceptId().equals(ageUnitConcept)) {
            ageUnit = ageUnitConverter(obs.getValueCoded());
        }
    }
    if (contactName != null) {
        return SimpleObject.create("contact", contactName.toUpperCase(), "relType",
                relType != null ? relType : "", "relStatus", relStatus != null ? relStatus : "", "age",
                age != null ? new StringBuilder().append(age).append(" ").append(ageUnit) : "", "art_no",
                artNo != null ? artNo.intValue() : "", "baselineStatus",
                baselineStatus != null ? baselineStatus : "", "nextTestDate",
                nextTestDate != null ? nextTestDate : "", "inCare", inCare != null ? inCare : "", "testResult",
                hivTestResult != null ? hivTestResult : "");
    }
    return null;

}

From source file:org.squale.squaleweb.applicationlayer.action.results.project.ProjectResultsAction.java

/**
 * Rcupre les dtails de la pratique/*from w w w.ja  v a  2 s . c  om*/
 * 
 * @param pMapping le mapping.
 * @param pForm le formulaire  lire.
 * @param pRequest la requte HTTP.
 * @param pResponse la rponse de la servlet.
 * @return l'action  raliser.
 */
public ActionForward mark(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest,
        HttpServletResponse pResponse) {

    ActionForward forward = null;
    ActionErrors errors = new ActionErrors();
    // sert aussi pour le traceur
    String value = "", minValue = "", maxValue = "", factorParent = "", param = "", note = "",
            markParamForTracker = "";
    try {
        forward = init(pMapping, pRequest, pForm);
        if (null == forward) {
            param = (String) pRequest.getParameter("tre");
            factorParent = (String) pRequest.getParameter("factorParent");
            IApplicationComponent acGrid = AccessDelegateHelper.getInstance("QualityGrid");
            // Obtention de la pratique
            long practiceId = Long.parseLong((String) pRequest.getParameter("tre"));
            PracticeRuleDTO practice = new PracticeRuleDTO();
            practice.setId(practiceId);
            practice = (PracticeRuleDTO) acGrid.execute("getQualityRule",
                    new Object[] { practice, new Boolean(false) });
            FactorRuleDTO factor = new FactorRuleDTO();
            if (factorParent != null) {
                // Obtention du facteur
                long factorId = Long.parseLong(factorParent);
                factor.setId(factorId);
                factor = (FactorRuleDTO) acGrid.execute("getQualityRule",
                        new Object[] { factor, new Boolean(false) });
            } else {
                factor.setId(-1);
                factor.setName("");
            }
            // Prparation de l'appel des couches mtier
            IApplicationComponent ac = AccessDelegateHelper.getInstance("Results");

            AuditDTO audit = (AuditDTO) (ActionUtils.getCurrentAuditsAsDTO(pRequest).get(0));
            ComponentDTO project = (ComponentDTO) pRequest.getSession()
                    .getAttribute(BaseDispatchAction.PROJECT_DTO);

            ResultsDTO result = null;
            value = (String) pRequest.getParameter("currentMark");
            // Suivant le type de paramtre pass, on peut savoir si on vient du graph ou si
            // on vient du tableau de rpartition
            if (value != null) { // Clic sur le tableau de rpartition
                                 // Note entire  ajouter  l'url du traceur
                markParamForTracker = "&currentMark=" + value;
                Integer intValue = new Integer(value);
                // Un nombre maximal de rsultats est retrouv
                Object[] paramIn = { audit, project, new Long(practiceId), intValue,
                        new Integer(WebMessages.getString(Locale.getDefault(), "component.max")) };
                // Appel de la couche mtier
                result = (ResultsDTO) ac.execute("getValueResults", paramIn);
                // Transformation vers le formulaire
                WTransformerFactory.objToForm(MarkTransformer.class, (WActionForm) pForm,
                        new Object[] { result, factor, practice, intValue });
                note = WebMessages.getString(pRequest, "project.results.mark.status_" + value);
            } else { // clic sur le graph
                minValue = (String) pRequest.getParameter("minMark");
                maxValue = (String) pRequest.getParameter("maxMark");
                // Intervalle  ajouter  l'url du traceur
                markParamForTracker = "&minMark=" + minValue + "&maxMark=" + maxValue;
                // Conversion en double
                Double minMark = new Double(minValue);
                Double maxMark = new Double(maxValue);
                // Un nombre maximal de rsultats est retrouv
                Object[] paramIn = { audit, project, new Long(practiceId), minMark, maxMark,
                        new Integer(WebMessages.getString(Locale.getDefault(), "component.max")) };
                // Appel de la couche mtier
                result = (ResultsDTO) ac.execute("getValueResultsForInterval", paramIn);
                // Transformation vers le formulaire
                WTransformerFactory.objToForm(MarkTransformer.class, (WActionForm) pForm,
                        new Object[] { result, factor, practice, minMark, maxMark });
                note = WebMessages.getString(pRequest, "project.results.mark");
                // pour le traceur
                note += "[" + minMark.doubleValue() + "," + maxMark.doubleValue();
                // Suivant la note, on l'inclus ou pas la dans l'intervalle
                // on ne l'inclus que si c'est 3
                if (maxMark.intValue() != PracticeResultBO.EXCELLENT) {
                    note += "[";
                } else {
                    note += "]";
                }
            }
            forward = pMapping.findForward("mark");
        }
    } catch (Exception e) {
        // Traitement factoris des exceptions
        handleException(e, errors, pRequest);
    }
    if (!errors.isEmpty()) {
        // Enregistrement des messages et routage vers une page d'erreur
        saveMessages(pRequest, errors);
        forward = pMapping.findForward("total_failure");
    }
    // Mise en place du traceur historique
    String url = "mark.do?action=mark&tre=" + param + markParamForTracker;
    if (factorParent != null) {
        url += "&factorparent=" + factorParent;
    }

    updateHistTracker(note, url, TrackerStructure.FACTOR_VIEW, pRequest, false);
    // Indique que l'on vient d'une vue synthse et pas d'une vue composant
    changeWay(pRequest, "false");
    // ICI on doit dire qu'il faudra effacer completement le traceur
    // aprs le passage sur le prochain composant
    needToReset(pRequest, "true");
    // *****************************************************************
    return forward;
}

From source file:org.opencb.opencga.storage.mongodb.variant.adaptors.VariantMongoDBAdaptor.java

@Override
public QueryResult getFrequency(Query query, Region region, int regionIntervalSize) {
    // db.variants.aggregate( { $match: { $and: [ {chr: "1"}, {start: {$gt: 251391, $lt: 2701391}} ] }},
    //                        { $group: { _id: { $subtract: [ { $divide: ["$start", 20000] }, { $divide: [{$mod: ["$start", 20000]},
    // 20000] } ] },
    //                                  totalCount: {$sum: 1}}})

    QueryOptions options = new QueryOptions();

    // If interval is not provided is set to the value that returns 200 values
    if (regionIntervalSize <= 0) {
        //            regionIntervalSize = options.getInt("interval", (region.getEnd() - region.getStart()) / 200);
        regionIntervalSize = (region.getEnd() - region.getStart()) / 200;
    }//from   w  w  w  . j  a  va  2 s  .  c o  m

    Document start = new Document("$gt", region.getStart());
    start.append("$lt", region.getEnd());

    BasicDBList andArr = new BasicDBList();
    andArr.add(new Document(DocumentToVariantConverter.CHROMOSOME_FIELD, region.getChromosome()));
    andArr.add(new Document(DocumentToVariantConverter.START_FIELD, start));

    // Parsing the rest of options
    Document mongoQuery = parseQuery(query);
    if (!mongoQuery.isEmpty()) {
        andArr.add(mongoQuery);
    }
    Document match = new Document("$match", new Document("$and", andArr));

    //        qb.and("_at.chunkIds").in(chunkIds);
    //        qb.and(DBObjectToVariantConverter.END_FIELD).greaterThanEquals(region.getStart());
    //        qb.and(DBObjectToVariantConverter.START_FIELD).lessThanEquals(region.getEnd());
    //
    //        List<String> chunkIds = getChunkIds(region);
    //        DBObject regionObject = new Document("_at.chunkIds", new Document("$in", chunkIds))
    //                .append(DBObjectToVariantConverter.END_FIELD, new Document("$gte", region.getStart()))
    //                .append(DBObjectToVariantConverter.START_FIELD, new Document("$lte", region.getEnd()));

    BasicDBList divide1 = new BasicDBList();
    divide1.add("$start");
    divide1.add(regionIntervalSize);

    BasicDBList divide2 = new BasicDBList();
    divide2.add(new Document("$mod", divide1));
    divide2.add(regionIntervalSize);

    BasicDBList subtractList = new BasicDBList();
    subtractList.add(new Document("$divide", divide1));
    subtractList.add(new Document("$divide", divide2));

    Document subtract = new Document("$subtract", subtractList);
    Document totalCount = new Document("$sum", 1);
    Document g = new Document("_id", subtract);
    g.append("features_count", totalCount);
    Document group = new Document("$group", g);
    Document sort = new Document("$sort", new Document("_id", 1));

    //        logger.info("getAllIntervalFrequencies - (>_)>");
    //        System.out.println(options.toString());
    //        System.out.println(match.toString());
    //        System.out.println(group.toString());
    //        System.out.println(sort.toString());

    long dbTimeStart = System.currentTimeMillis();
    QueryResult output = variantsCollection.aggregate(/*"$histogram", */Arrays.asList(match, group, sort),
            options);
    long dbTimeEnd = System.currentTimeMillis();

    Map<Long, Document> ids = new HashMap<>();
    // Create DBObject for intervals with features inside them
    for (Document intervalObj : (List<Document>) output.getResult()) {
        Long auxId = Math.round((Double) intervalObj.get("_id")); //is double

        Document intervalVisited = ids.get(auxId);
        if (intervalVisited == null) {
            intervalObj.put("_id", auxId);
            intervalObj.put("start", getChunkStart(auxId.intValue(), regionIntervalSize));
            intervalObj.put("end", getChunkEnd(auxId.intValue(), regionIntervalSize));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", Math.log((int) intervalObj.get("features_count")));
            ids.put(auxId, intervalObj);
        } else {
            Double sum = (Double) intervalVisited.get("features_count")
                    + Math.log((int) intervalObj.get("features_count"));
            intervalVisited.put("features_count", sum.intValue());
        }
    }

    // Create DBObject for intervals without features inside them
    BasicDBList resultList = new BasicDBList();
    int firstChunkId = getChunkId(region.getStart(), regionIntervalSize);
    int lastChunkId = getChunkId(region.getEnd(), regionIntervalSize);
    Document intervalObj;
    for (int chunkId = firstChunkId; chunkId <= lastChunkId; chunkId++) {
        intervalObj = ids.get((long) chunkId);
        if (intervalObj == null) {
            intervalObj = new Document();
            intervalObj.put("_id", chunkId);
            intervalObj.put("start", getChunkStart(chunkId, regionIntervalSize));
            intervalObj.put("end", getChunkEnd(chunkId, regionIntervalSize));
            intervalObj.put("chromosome", region.getChromosome());
            intervalObj.put("features_count", 0);
        }
        resultList.add(intervalObj);
    }

    QueryResult queryResult = new QueryResult(region.toString(), ((Long) (dbTimeEnd - dbTimeStart)).intValue(),
            resultList.size(), resultList.size(), null, null, resultList);
    return queryResult;
}

From source file:com.aurel.track.exchange.msProject.exporter.MsProjectExporterBL.java

/**
 * Export the assignments to actual work
 * //  w ww  .j a v  a2s . c  om
 * @param document
 * @param assignmentElementTemplate
 * @param timephasedDataElementTemplate
 * @param existingTrackPlusWorkItemsMap
 * @param allCostBeansList
 * @param workItemIDToTaskUIDMap
 * @param personIDToResourceUIDMap
 * @param hoursPerWorkday
 * @param removedTaskIDs
 * @param allowOvertimeBookings
 * @param maxOvertimeHoursPerDay
 * @param allowOverdayBookings
 * @param allowActualWorkOverlap
 * @param allowDayRestartIfOverlappedActualWork
 */
private static void exportAssignments(ProjectFile project,
        Map<Integer, TWorkItemBean> existingTrackPlusWorkItemsMap, List<TCostBean> allCostBeansList,
        Map<Integer, Integer> workItemIDToTaskUIDMap, Map<Integer, List<Integer>> personIDToResourceUIDMap,
        Double hoursPerWorkday, Set<Integer> removedTaskIDs, boolean allowOvertimeBookings,
        double maxOvertimeHoursPerDay, boolean allowOverdayBookings, boolean allowActualWorkOverlap, /*
                                                                                                     * boolean
                                                                                                     * allowDayRestartIfOverlappedActualWork
                                                                                                     * ,
                                                                                                     */
        Map<Integer, Map<String, List<String[]>>> calendarUIDBasedBaseCalendarExceptionWorkingTimes,
        Map<Integer, Map<Integer, List<String[]>>> calendarUIDBasedBaseCalendarWeekDayWorkingTimes,
        Map<Integer, Map<String, List<String[]>>> personBasedCalendarExceptionWorkingTimes,
        Map<Integer, Map<Integer, List<String[]>>> personBasedCalendarWeekDayWorkingTimes,
        Map<Integer, Integer> personIDToBaseCalendar) {
    // TODO unused MPXJ
    /*
     * Element assignmentsElement =
     * MsProjectExchangeDOMHelper.getChildByName(projectElement,
     * PROJECT_ELEMENTS.Assignments); Element assignmentsElement =
     * project.getAss() if (assignmentsElement==null) { assignmentsElement =
     * document.createElement(PROJECT_ELEMENTS.Assignments);
     * projectElement.appendChild(assignmentsElement); }
     */
    // get last imported assignments
    // List<Element> importedAssignmentsList =
    // MsProjectExchangeDOMHelper.getElementList(
    // projectElement, PROJECT_ELEMENTS.Assignments,
    // PROJECT_SUBELEMENTS.Assignment);
    List<ResourceAssignment> importedAssignmentsList = project.getAllResourceAssignments();
    /*
     * for(int i = 0; i < importedAssignmentsList.size(); i++) {
     * ResourceAssignment tmp = importedAssignmentsList.get(i);
     * tmp.setStart(tmp.getTask().getStart());;
     * tmp.setFinish(tmp.getTask().getFinish()); tmp.setActualStart(null);
     * tmp.setActualFinish(null); tmp.setActualWork(null); }
     */

    if (removedTaskIDs != null && removedTaskIDs.size() > 0) {
        // remove the assignments associated with removed tasks
        for (int i = 0; i < importedAssignmentsList.size(); i++) {
            ResourceAssignment assignmentElement = importedAssignmentsList.get(i);
            Integer taskID = assignmentElement.getTaskUniqueID();
            if (removedTaskIDs.contains(taskID)) {
                importedAssignmentsList.remove(i);
            }
        }
    }
    Map<Integer, ResourceAssignment> UIDBasedAssignmentsMap = MsProjectExchangeDOMHelper
            .getSubelementBasedElementMapAssignment(importedAssignmentsList);
    int maxAssignmentUID = getMaxInteger(UIDBasedAssignmentsMap.keySet());

    Map<Integer, Map<Integer, ResourceAssignment>> importedTaskUIDToResourceUIDToAssignmentsMap = MsProjectExchangeDOMHelper
            .getAssignmentsMap(importedAssignmentsList);
    Map<Integer, Task> UIDBasedTaskElementMap = getUIDBasedTasks(project);
    String emptyTimeSpan = MsProjectExchangeBL.getTimeSpanFromDouble(0.0);
    // NumberFormat numberFormatTimeSpan = new DecimalFormat("00");

    /**
     * Add empty assignment: if a workItem has no cost in Genji and it was
     * not imported before from MSPRoject a default assignment (with
     * actualWork=0 and work=total task budget and remainingWork=remaining
     * task budget) should still be added to the task, to assign the
     * workItem's responsible as resource to the task (otherwise the task
     * will have no duration)
     */
    Map<Integer, List<TCostBean>> worksByWorkItemMap = getWorksByWorkItem(allCostBeansList);
    Iterator<Integer> itrExistingWorkItems = existingTrackPlusWorkItemsMap.keySet().iterator();
    while (itrExistingWorkItems.hasNext()) {
        Integer workItemID = itrExistingWorkItems.next();
        TWorkItemBean workItemBean = existingTrackPlusWorkItemsMap.get(workItemID);
        Integer taskUID = workItemIDToTaskUIDMap.get(workItemID);
        if (!worksByWorkItemMap.containsKey(workItemID)
                && !importedTaskUIDToResourceUIDToAssignmentsMap.containsKey(taskUID)) {
            // it has no actualWork and was not imported before: it will not
            // be processed in the "existing costs" loop below
            List<Integer> personList = new ArrayList<Integer>();
            personList.add(workItemBean.getResponsibleID());
            personList.add(workItemBean.getOwnerID());
            personList.add(workItemBean.getOriginatorID());
            Integer resourceID = getBestResourceID(personList, personIDToResourceUIDMap);
            if (resourceID != null && taskUID != null) {
                Task taskElement = UIDBasedTaskElementMap.get(taskUID);
                if (taskElement != null) {
                    ResourceAssignment assignmentElement = new ResourceAssignment(project);
                    ResourceAssignment existing = importedTaskUIDToResourceUIDToAssignmentsMap.get(taskUID)
                            .get(resourceID);
                    assignmentElement.setUniqueID(++maxAssignmentUID);
                    assignmentElement.setTaskUniqueID(taskUID);
                    assignmentElement.setResourceUniqueID(resourceID);
                    // TODO set emptyTimeSpan string as duration not
                    // possible in MPXJ
                    // assignmentElement.setActualWork(Duration.emptyTimeSpan);
                    // get the values directly from the task: the Work and
                    // RemainingWork are probably equal
                    // String work =
                    // MsProjectExchangeDOMHelper.getSubelementText(taskElement,
                    // COMMON_ELEMENTS.Work);
                    if (importedTaskUIDToResourceUIDToAssignmentsMap.get(resourceID) != null) {
                        assignmentElement.setWork(existing.getWork());
                        assignmentElement.setRemainingWork(existing.getRemainingWork());
                        assignmentElement.setStart(existing.getStart());
                        assignmentElement.setStart(existing.getFinish());
                    }
                }
            }
        }
    }

    /**
     * The actual booked calendar for a certain date for a certain user
     */
    Map<Integer, Map<String, Calendar>> effortDateToCalBookedForPersonMap = new HashMap<Integer, Map<String, Calendar>>();
    /**
     * The exhausted effort dates for a certain user
     */
    Map<Integer, Map<String, Boolean>> effortDateExhaustedForPersonMap = new HashMap<Integer, Map<String, Boolean>>();
    // loop through the existing costs in track+ based on workItemID and
    // personID
    Iterator<Integer> itrWorksByWorkItemIDMap = worksByWorkItemMap.keySet().iterator();
    while (itrWorksByWorkItemIDMap.hasNext()) {
        Integer workItemID = itrWorksByWorkItemIDMap.next();
        List<TCostBean> costBeansWorkItem = worksByWorkItemMap.get(workItemID);
        // get the workItem costs pro person
        Map<Integer, List<TCostBean>> costsByPerson = getCostsByPerson(costBeansWorkItem);
        Map<Integer, Double> personActualWorkMap = new HashMap<Integer, Double>();
        for (Iterator<Integer> iterator = costsByPerson.keySet().iterator(); iterator.hasNext();) {
            Integer personID = iterator.next();
            List<TCostBean> costs = costsByPerson.get(personID);
            personActualWorkMap.put(personID, getSumOfActualWorks(costs));
        }
        Integer taskUID = workItemIDToTaskUIDMap.get(workItemID);
        if (taskUID != null) {
            Task taskElement = UIDBasedTaskElementMap.get(taskUID);
            if (taskElement != null) {
                Date taskActualStart = null;
                Date taskActualFinish = null;
                // all assignments for workItem: both last imported (even if
                // there is no actual work (costBean) associated) and new
                // ones
                Map<Integer, ResourceAssignment> resourceBasedAssignmentsForWorkItem = new HashMap<Integer, ResourceAssignment>();
                Set<Integer> resoucesWithImportedRemainingWork = new HashSet<Integer>();
                // iterate through costBeans for each person
                Iterator<Integer> itrPerson = costsByPerson.keySet().iterator();
                while (itrPerson.hasNext()) {
                    Integer personID = itrPerson.next();
                    List<TCostBean> costBeansPerson = costsByPerson.get(personID);
                    List<Integer> resourceUIDForPersonList = personIDToResourceUIDMap.get(personID);
                    Integer resourceUID = null;
                    if (resourceUIDForPersonList == null || resourceUIDForPersonList.isEmpty()) {
                        // unknown person, should never happen
                        continue;
                    } else {
                        if (resourceUIDForPersonList.size() == 1) {
                            // unambiguous person <-> resource: the
                            // corresponding person was mapped only to this
                            // resource
                            resourceUID = resourceUIDForPersonList.get(0);
                        }
                    }
                    ResourceAssignment assignmentElement = null;
                    Map<Integer, ResourceAssignment> importedResourceUIDToAssignmentsMap = importedTaskUIDToResourceUIDToAssignmentsMap
                            .get(taskUID);
                    // last imported assignments for task exist
                    if (importedResourceUIDToAssignmentsMap != null
                            && importedResourceUIDToAssignmentsMap.size() > 0) {
                        if (resourceUID == null && importedResourceUIDToAssignmentsMap.size() > 0) {
                            // ambiguous: the same person was mapped for
                            // more resources:
                            // find the resourceID based on the available
                            // assignments from the previous import:
                            // get the first last imported resourceID found
                            // which was mapped for the person.
                            // (as best effort but still error prone)
                            Iterator<Integer> itrResource = importedResourceUIDToAssignmentsMap.keySet()
                                    .iterator();
                            while (itrResource.hasNext()) {
                                resourceUID = itrResource.next();
                                if (resourceUIDForPersonList.contains(resourceUID)) {
                                    break;
                                } else {
                                    resourceUID = null;
                                }
                            }
                        }
                        // person had assignment to task both in the
                        // previous import and in track+: remove it if found
                        // to process them now
                        // assignments not processed (removed) here should
                        // be looped at the end for removing (probably their
                        // costBeans were removed)
                        assignmentElement = importedResourceUIDToAssignmentsMap.remove(resourceUID);

                    }
                    if (resourceUID == null) {
                        // no previous import for this assignment, so there
                        // is no way to uniquely identify the resourceID
                        // for adding the assignment for, as best effort
                        // take the first mapped for the person
                        resourceUID = resourceUIDForPersonList.get(0);
                    }
                    // the timephased data will be calculated depending on
                    // the unit
                    Double unit = new Double(1.0); // default 1.0 = 100%
                    boolean isNew = false;

                    if (assignmentElement == null) {
                        assignmentElement = new ResourceAssignment(project);
                        // new assignment: the workItem has actual work
                        // booked by a person but the previous
                        // import file contains no assignments: actual
                        // work(s) added in track+ exclusively since the
                        // last import
                        isNew = true;
                    } else {
                        // get the unit from the previously imported
                        // assignment
                        // unit =
                        // MsProjectExchangeDOMHelper.getSubelementDouble(assignmentElement,
                        // ASSIGNMENT_ELEMENTS.Units);
                        unit = assignmentElement.getUnits().doubleValue();
                        if (unit == null || Math.abs(unit.doubleValue()) < EPSILON) {
                            unit = new Double(1.0);
                        }
                        /*
                         * if assignmentElement was already imported try to
                         * preserve the remaining work pro person (taking
                         * into account the corresponding actual work
                         * difference). This counts by calculating the
                         * duration of the task
                         */
                        Double lastActualWorkPerson = assignmentElement.getActualWork().getDuration();
                        if (lastActualWorkPerson == null) {
                            lastActualWorkPerson = new Double(0.0);
                        }
                        Double lastRemainingWorkPerson = assignmentElement.getRemainingWork().getDuration();
                        if (lastRemainingWorkPerson == null) {
                            lastRemainingWorkPerson = new Double(0.0);
                        }
                        Double currentActualWorkPerson = personActualWorkMap.get(personID);
                        if (currentActualWorkPerson == null) {
                            currentActualWorkPerson = new Double(0.0);
                        }
                        double actualWorkDifference = currentActualWorkPerson.doubleValue()
                                - lastActualWorkPerson.doubleValue();
                        double newRemainingWorkPerson = 0.0;
                        if (lastRemainingWorkPerson.doubleValue() >= actualWorkDifference) {
                            newRemainingWorkPerson = lastRemainingWorkPerson.doubleValue()
                                    - actualWorkDifference;
                        }
                        assignmentElement
                                .setRemainingWork(Duration.getInstance(newRemainingWorkPerson, TimeUnit.HOURS));

                    }

                    // because it is not trivial to combine two lists of
                    // works for changes (last imported and actual from
                    // Genji),
                    // all imported ASSIGNMENT_ACTUAL_WORK and
                    // ASSIGNMENT_REMAINING_WORK type
                    // and without value timePhasedData elements will be
                    // removed
                    // (and later the ASSIGNMENT_ACTUAL_WORK elements from
                    // track+ will be added again based on Genji costBeans)
                    project.getAllResourceAssignments().remove(assignmentElement);
                    resourceBasedAssignmentsForWorkItem.put(resourceUID, assignmentElement);
                    if (isNew && costBeansPerson != null && costBeansPerson.size() > 0) {
                        ResourceAssignment newAssignmentElement = new ResourceAssignment(project);
                        newAssignmentElement.setUniqueID(++maxAssignmentUID);
                        assignmentElement.setTaskUniqueID(taskUID);
                        assignmentElement.setResourceUniqueID(resourceUID);
                    }
                    /**
                     * add TimephasedData elements
                     */
                    // if actualStart does not comply with the
                    // timephasedData elements
                    // then the Actual work may have the wrong value in
                    // MSProject
                    Date assignmentActualStart = null;
                    Date assignmentActualFinish = null;
                    int assignmentActualOvertimeHours = 0;
                    int assignmentActualOverTimeMinutes = 0;
                    // formatted effortDate mapped to calendar with with
                    // actualized times for
                    // a certain user to avoid double allocation for a user
                    // in a certain time
                    Map<String, Calendar> effortDateToCalBookedMap = null;
                    Map<String, Boolean> effortDateExhaustedMap = null;
                    if (!allowActualWorkOverlap) {
                        effortDateToCalBookedMap = effortDateToCalBookedForPersonMap.get(personID);
                        effortDateExhaustedMap = effortDateExhaustedForPersonMap.get(personID);
                    }
                    if (effortDateToCalBookedMap == null) {
                        effortDateToCalBookedMap = new HashMap<String, Calendar>();
                        if (!allowActualWorkOverlap) {
                            effortDateToCalBookedForPersonMap.put(personID, effortDateToCalBookedMap);
                        }
                    }
                    // whether the date was exhausted by previous works
                    if (effortDateExhaustedMap == null) {
                        effortDateExhaustedMap = new HashMap<String, Boolean>();
                        if (!allowActualWorkOverlap) {
                            effortDateExhaustedForPersonMap.put(personID, effortDateExhaustedMap);
                        }
                    }
                    if (costBeansPerson != null && costBeansPerson.size() > 0) {
                        // add the ASSIGNMENT_ACTUAL_WORK timephasedData
                        // elements from Genji
                        Date effortDate = null;
                        Date previousEffortDate = null;
                        for (TCostBean costBean : costBeansPerson) {
                            if (effortDate != null) {
                                // effort date is null at the beginning and
                                // after by overbooked days if
                                // allowOvertimeBookings=false
                                // in previousEffortDate the last valid
                                // (non-null) effortDate should be kept
                                previousEffortDate = effortDate;
                            }
                            effortDate = costBean.getEffortdate();
                            if (previousEffortDate != null && effortDate != null
                                    && previousEffortDate.before(effortDate)) {
                                // add empty timespans for the gaps between
                                // actual work,
                                // otherwise the gap is considered as
                                // actually worked
                                addEmptyIntervals(project, assignmentElement, previousEffortDate, effortDate,
                                        emptyTimeSpan, effortDateToCalBookedMap, effortDateExhaustedMap,
                                        personBasedCalendarExceptionWorkingTimes.get(personID),
                                        personBasedCalendarWeekDayWorkingTimes.get(personID),
                                        calendarUIDBasedBaseCalendarExceptionWorkingTimes
                                                .get(personIDToBaseCalendar.get(personID)),
                                        calendarUIDBasedBaseCalendarWeekDayWorkingTimes.get(
                                                personIDToBaseCalendar.get(personID)),
                                        allowOvertimeBookings);
                            }
                            Double hours = costBean.getHours();
                            if (effortDate != null && hours != null && hours.intValue() > 0.0) {
                                // calculate the unit proportional values,
                                // because in TimephasedData element the
                                // Start and Finish
                                // date fields are based on unit
                                // proportional hours, but the Value field
                                // is based on real hours
                                // depending on Assignment element's Unit
                                // sub-element
                                Double unitHours = hours.doubleValue() / unit.doubleValue();
                                int unitProportionalHours = unitHours.intValue();
                                double unitDecimalHours = unitHours - unitProportionalHours;
                                int unitProportionalMinutes = (int) Math.round(unitDecimalHours * 60);
                                // date over-booked by previous costBeans
                                effortDate = getNextValidDate(effortDate, effortDateExhaustedMap,
                                        personBasedCalendarExceptionWorkingTimes.get(personID),
                                        personBasedCalendarWeekDayWorkingTimes.get(personID),
                                        calendarUIDBasedBaseCalendarExceptionWorkingTimes
                                                .get(personIDToBaseCalendar.get(personID)),
                                        calendarUIDBasedBaseCalendarWeekDayWorkingTimes.get(
                                                personIDToBaseCalendar.get(personID)),
                                        allowOverdayBookings);
                                if (effortDate == null) {
                                    if (allowOverdayBookings) {
                                        LOGGER.warn("No reasonable effort date found for person " + personID
                                                + " workItem " + workItemID + " costID "
                                                + costBean.getObjectID());
                                    } else {
                                        LOGGER.warn("The work " + hours.doubleValue() + " for person "
                                                + personID + " workItem " + workItemID + " costID "
                                                + costBean.getObjectID()
                                                + " could not be added because the worktime for date "
                                                + MsProjectExchangeBL.formatDateTime(effortDate)
                                                + " is exhausted by previous works");
                                    }
                                    continue;// to the next costBean
                                }
                                String effortDateStr = MsProjectExchangeBL.formatDate(effortDate);
                                Calendar calToTime = Calendar.getInstance();
                                calToTime.setTime(effortDate);
                                boolean jumpToNextWorkingTimeInterval = false;
                                List<String[]> workingPeriods = getWorkingTimeForDay(
                                        personBasedCalendarExceptionWorkingTimes.get(personID),
                                        personBasedCalendarWeekDayWorkingTimes.get(personID),
                                        calendarUIDBasedBaseCalendarExceptionWorkingTimes
                                                .get(personIDToBaseCalendar.get(personID)),
                                        calendarUIDBasedBaseCalendarWeekDayWorkingTimes
                                                .get(personIDToBaseCalendar.get(personID)),
                                        effortDate);
                                if (workingPeriods == null) {
                                    // should never happen,
                                    continue;
                                } // else {
                                int realHours = 0;
                                int realMinutes = 0;
                                boolean isOvertime = false;
                                // the Start date of the timephasedData
                                Date timePhasedDataStart = null;
                                for (Iterator itrWorkPeriod = workingPeriods.iterator(); itrWorkPeriod
                                        .hasNext();) {
                                    // try each workingTime interval to see
                                    // where the work can be added
                                    String[] workingTime = (String[]) itrWorkPeriod.next();
                                    String fromTime = workingTime[0];
                                    String toTime = workingTime[1];
                                    Map<String, Integer> timeUnitsMapFromTime = MsProjectExchangeBL
                                            .getTimeUnitsMapFromCalendarTime(fromTime);
                                    Map<String, Integer> timeUnitsMapToTime = MsProjectExchangeBL
                                            .getTimeUnitsMapFromCalendarTime(toTime);
                                    Integer previousHour = calToTime.get(Calendar.HOUR_OF_DAY);
                                    calToTime.set(Calendar.HOUR_OF_DAY,
                                            timeUnitsMapToTime.get(MSPROJECT_TIME_UNITS.HOUR));
                                    calToTime.set(Calendar.MINUTE,
                                            timeUnitsMapToTime.get(MSPROJECT_TIME_UNITS.MINUTE));
                                    Integer nextHour = calToTime.get(Calendar.HOUR_OF_DAY);
                                    if (!itrWorkPeriod.hasNext() && allowOvertimeBookings) {
                                        // midnight means the start of the
                                        // next day
                                        if (previousHour > nextHour) {
                                            // overtime over the midnight
                                            calToTime.add(Calendar.DATE, 1);
                                        }
                                        isOvertime = true;
                                    } else {
                                        isOvertime = false;
                                    }
                                    Calendar calBookedForPerson = effortDateToCalBookedMap.get(effortDateStr);
                                    if (calBookedForPerson == null) {
                                        calBookedForPerson = Calendar.getInstance();
                                        calBookedForPerson.setTime(effortDate);
                                        calBookedForPerson.set(Calendar.HOUR_OF_DAY,
                                                timeUnitsMapFromTime.get(MSPROJECT_TIME_UNITS.HOUR));
                                        calBookedForPerson.set(Calendar.MINUTE,
                                                timeUnitsMapFromTime.get(MSPROJECT_TIME_UNITS.MINUTE));
                                        effortDateToCalBookedMap.put(effortDateStr, calBookedForPerson);
                                    }
                                    // jumped first time or from the
                                    // previous workingTime interval
                                    if (jumpToNextWorkingTimeInterval) {
                                        calBookedForPerson.set(Calendar.HOUR_OF_DAY,
                                                timeUnitsMapFromTime.get(MSPROJECT_TIME_UNITS.HOUR));
                                        calBookedForPerson.set(Calendar.MINUTE,
                                                timeUnitsMapFromTime.get(MSPROJECT_TIME_UNITS.MINUTE));
                                        jumpToNextWorkingTimeInterval = false;
                                    }
                                    if (calBookedForPerson.getTime().after(calToTime.getTime())
                                            || calBookedForPerson.getTimeInMillis() == calToTime
                                                    .getTimeInMillis()) {
                                        // try the next workingTime interval
                                        // because till this time
                                        // the user booked previous
                                        // costBeans
                                        LOGGER.debug("Period from "
                                                + MsProjectExchangeBL.formatDateTime(calToTime.getTime())
                                                + " for personID " + personID + " workItemID " + workItemID
                                                + " costID " + costBean.getObjectID() + " added at date "
                                                + MsProjectExchangeBL.formatDateTime(effortDate)
                                                + " expense work " + hours.doubleValue()
                                                + " already booked by other costBeans.");
                                        if (calBookedForPerson.getTimeInMillis() == calToTime
                                                .getTimeInMillis()) {
                                            jumpToNextWorkingTimeInterval = true;
                                        }
                                        continue; // to the next working
                                                  // time of the current
                                                  // date
                                    } else {
                                        // available working time found
                                        if (timePhasedDataStart == null) {
                                            timePhasedDataStart = calBookedForPerson.getTime();
                                        }
                                        long millisecondsLeftInInterval = calToTime.getTimeInMillis()
                                                - calBookedForPerson.getTimeInMillis();
                                        if (millisecondsLeftInInterval == 0) {
                                            continue; // to the next working
                                                      // time of the
                                                      // current date
                                        }
                                        long diffHours = millisecondsLeftInInterval / (60 * 60 * 1000);
                                        long diffMinutes = (millisecondsLeftInInterval
                                                - diffHours * 60 * 60 * 1000) / (60 * 1000);
                                        if (unitProportionalHours < diffHours
                                                || (unitProportionalHours == diffHours
                                                        && unitProportionalMinutes <= diffMinutes)) {
                                            // the current workingTime
                                            // interval is enough for work
                                            // to add
                                            calBookedForPerson.add(Calendar.HOUR_OF_DAY, unitProportionalHours);
                                            calBookedForPerson.add(Calendar.MINUTE, unitProportionalMinutes);
                                            Double unitPropRemainingHours = new Double(unitProportionalHours
                                                    + (double) unitProportionalMinutes / 60);
                                            // add the real hours
                                            Double realHoursDouble = new Double(
                                                    unitPropRemainingHours * unit.doubleValue());
                                            realHours += realHoursDouble.intValue();
                                            if (isOvertime) {
                                                assignmentActualOvertimeHours += realHoursDouble.intValue();
                                            }
                                            double decimalHours = realHoursDouble - realHoursDouble.intValue();
                                            realMinutes += (int) Math.round(decimalHours * 60);
                                            if (isOvertime) {
                                                assignmentActualOverTimeMinutes += (int) Math
                                                        .round(decimalHours * 60);
                                            }
                                            addTimephasedDataElement(project, assignmentElement,
                                                    timePhasedDataStart, calBookedForPerson.getTime(),
                                                    MsProjectExchangeBL.getTimeSpanFromHoursAndMinutes(
                                                            realHours, realMinutes));
                                            if (assignmentActualStart == null
                                                    || assignmentActualStart.after(timePhasedDataStart)) {
                                                assignmentActualStart = timePhasedDataStart;
                                            }
                                            if (assignmentActualFinish == null || assignmentActualFinish
                                                    .before(calBookedForPerson.getTime())) {
                                                assignmentActualFinish = calBookedForPerson.getTime();
                                            }
                                            LOGGER.debug("Added actual work for person " + personID
                                                    + " workItem " + workItemID + " cost "
                                                    + costBean.getObjectID() + " added at date "
                                                    + MsProjectExchangeBL.formatDateTime(effortDate) + " start "
                                                    + MsProjectExchangeBL.formatDateTime(timePhasedDataStart)
                                                    + " finish "
                                                    + MsProjectExchangeBL
                                                            .formatDateTime(calBookedForPerson.getTime())
                                                    + " expense work " + hours.doubleValue() + " actual work "
                                                    + realHours + ":" + realMinutes);
                                            if (!itrWorkPeriod.hasNext() && allowOverdayBookings
                                                    && unitProportionalHours == diffHours
                                                    && unitProportionalMinutes == diffMinutes) {
                                                // if terminated exactly at
                                                // midnight reset the
                                                // effortDateToEffortDateWithTime
                                                // to start again at the
                                                // first FromTime
                                                // effortDateToCalBookedForPersonMap.remove(effortDateStr);
                                                effortDateExhaustedMap.put(effortDateStr, Boolean.TRUE);
                                            }
                                            break; // successfully added for
                                                   // this day, break to
                                                   // continue with the
                                                   // next CostBean
                                        } else {
                                            // the current workingTime
                                            // interval is not enough for
                                            // the entire work to add:
                                            // add only a part of the work
                                            // till the end of the current
                                            // interval
                                            int remainingHoursInWorkingTimePeriod = Long.valueOf(diffHours)
                                                    .intValue();
                                            int remainingMinutesInWorkingTimePeriod = Long.valueOf(diffMinutes)
                                                    .intValue();
                                            // book up to the end of the
                                            // current workingTime
                                            calBookedForPerson.setTime(calToTime.getTime());
                                            jumpToNextWorkingTimeInterval = true;
                                            unitProportionalHours -= remainingHoursInWorkingTimePeriod;
                                            if (unitProportionalMinutes < remainingMinutesInWorkingTimePeriod) {
                                                unitProportionalMinutes += 60;
                                                unitProportionalHours--;
                                            }
                                            unitProportionalMinutes -= remainingMinutesInWorkingTimePeriod;
                                            // add only a part of the work
                                            // till the end of this
                                            // workingTime interval
                                            // add the real hours
                                            Double remainingHours = new Double(millisecondsLeftInInterval
                                                    * unit.doubleValue() / (60 * 60 * 1000));
                                            realHours += remainingHours.intValue();
                                            if (isOvertime) {
                                                assignmentActualOvertimeHours += remainingHours.intValue();
                                            }
                                            double decimalHours = remainingHours - remainingHours.intValue();
                                            realMinutes += (int) Math.round(decimalHours * 60);
                                            if (isOvertime) {
                                                assignmentActualOverTimeMinutes += (int) Math
                                                        .round(decimalHours * 60);
                                            }
                                            if (!itrWorkPeriod.hasNext()) {
                                                // the user consumed the
                                                // entire workDay and
                                                // overtime
                                                // till midnight but this is
                                                // still not enough
                                                // add the biggest possible
                                                // part of the work as best
                                                // effort
                                                addTimephasedDataElement(project, assignmentElement,
                                                        timePhasedDataStart, calBookedForPerson.getTime(),
                                                        MsProjectExchangeBL.getTimeSpanFromHoursAndMinutes(
                                                                realHours, realMinutes));
                                                if (assignmentActualStart == null
                                                        || assignmentActualStart.after(timePhasedDataStart)) {
                                                    assignmentActualStart = timePhasedDataStart;
                                                }
                                                if (assignmentActualFinish == null || assignmentActualFinish
                                                        .before(calBookedForPerson.getTime())) {
                                                    assignmentActualFinish = calBookedForPerson.getTime();
                                                }
                                                LOGGER.debug("Added actual work part for person " + personID
                                                        + " workItem " + workItemID + " cost "
                                                        + costBean.getObjectID() + " start "
                                                        + MsProjectExchangeBL
                                                                .formatDateTime(timePhasedDataStart)
                                                        + " finish "
                                                        + MsProjectExchangeBL
                                                                .formatDateTime(calBookedForPerson.getTime())
                                                        + " expense work " + hours.doubleValue()
                                                        + " actual work " + realHours + ":" + realMinutes);
                                                // effortDateToCalBookedForPersonMap.remove(effortDateStr);
                                                effortDateExhaustedMap.put(effortDateStr, Boolean.TRUE);
                                                // force to initialize again
                                                // at the first FromTime
                                                calBookedForPerson = null;
                                                timePhasedDataStart = null;
                                                realHours = 0;
                                                realMinutes = 0;
                                                effortDate = getNextValidDate(effortDate,
                                                        effortDateExhaustedMap,
                                                        personBasedCalendarExceptionWorkingTimes.get(personID),
                                                        personBasedCalendarWeekDayWorkingTimes.get(personID),
                                                        calendarUIDBasedBaseCalendarExceptionWorkingTimes
                                                                .get(personIDToBaseCalendar.get(personID)),
                                                        calendarUIDBasedBaseCalendarWeekDayWorkingTimes
                                                                .get(personIDToBaseCalendar.get(personID)),
                                                        allowOverdayBookings);
                                                if (effortDate == null) {
                                                    if (allowOvertimeBookings) {
                                                        LOGGER.warn(
                                                                "No reasonable effort date found for person "
                                                                        + personID + " workItem " + workItemID
                                                                        + " costID " + costBean.getObjectID());
                                                    } else {
                                                        LOGGER.warn("The work " + unitProportionalHours + ":"
                                                                + unitProportionalMinutes + " for person "
                                                                + personID + " workItem " + workItemID
                                                                + " costID " + costBean.getObjectID()
                                                                + " could not be added because the worktime for date "
                                                                + MsProjectExchangeBL.formatDateTime(effortDate)
                                                                + " is exhausted");
                                                    }
                                                    break;
                                                }
                                                effortDateStr = MsProjectExchangeBL.formatDate(effortDate);
                                                // calToTime is now midnight
                                                // (starting of the next
                                                // day).
                                                // set to the actual
                                                // effortDate day because
                                                // the
                                                // iterator for workPeriods
                                                // is started again with
                                                // this new date
                                                calToTime.setTime(effortDate);
                                                workingPeriods = getWorkingTimeForDay(
                                                        personBasedCalendarExceptionWorkingTimes.get(personID),
                                                        personBasedCalendarWeekDayWorkingTimes.get(personID),
                                                        calendarUIDBasedBaseCalendarExceptionWorkingTimes
                                                                .get(personIDToBaseCalendar.get(personID)),
                                                        calendarUIDBasedBaseCalendarWeekDayWorkingTimes
                                                                .get(personIDToBaseCalendar.get(personID)),
                                                        effortDate);

                                                itrWorkPeriod = workingPeriods.iterator();

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // assignment level ActualStart, Start and ActualFinish
                    // dates
                    if (assignmentActualStart != null) {
                        assignmentElement.setActualStart(assignmentActualStart);
                        if (taskActualStart == null || taskActualStart.after(assignmentActualStart)) {
                            taskActualStart = assignmentActualStart;
                        }
                    }
                    // the Start should be not later as the ActualStart
                    Date startElement = assignmentElement.getStart();
                    if (startElement != null) {
                        Date startDate = assignmentElement.getStart();
                        if (startDate != null && assignmentActualStart != null
                                && startDate.after(assignmentActualStart)) {
                            assignmentElement.setStart(assignmentActualStart);
                        }
                    }
                    if (assignmentActualFinish != null) {
                        // it is actually finished only when remaining work
                        // is 0
                        // so it might be removed later
                        assignmentElement.setActualFinish(assignmentActualFinish);
                        if (taskActualFinish == null || taskActualFinish.before(assignmentActualFinish)) {
                            taskActualFinish = assignmentActualFinish;
                        }
                    }
                    // do we have ActualOvertimeWork?
                    if (assignmentActualOvertimeHours > 0 || assignmentActualOverTimeMinutes > 0) {

                        String actualOverTimeHoursTimeSpan = MsProjectExchangeBL.getTimeSpanFromHoursAndMinutes(
                                assignmentActualOvertimeHours, assignmentActualOverTimeMinutes);
                        DateFormat df = new SimpleDateFormat();
                        Double actualOverTimeWork = assignmentElement.getActualOvertimeWork().getDuration();
                        if (actualOverTimeWork == null) {
                            actualOverTimeWork = new Double(0);
                        }
                        Double overtimeWork = assignmentElement.getOvertimeWork().getDuration();
                        if (overtimeWork == null) {
                            overtimeWork = new Double(0);
                        }
                        // the OvertimeWork will not be less than the
                        // ActualOvertimeWork
                        if (actualOverTimeWork.doubleValue() > overtimeWork.doubleValue()) {
                            // TODO MPXJ, set setOvertimeWork check.
                            try {
                                Calendar myCal = Calendar.getInstance();
                                myCal.setTime(df.parse(actualOverTimeHoursTimeSpan));
                                int hours = myCal.get(Calendar.HOUR_OF_DAY);
                                assignmentElement.setOvertimeWork(Duration.getInstance(hours, TimeUnit.HOURS));
                            } catch (Exception ex) {
                                LOGGER.error("Date parse error: " + ex.getMessage());
                            }
                        }
                    }
                } // end person loop

                /**
                 * actualize the remaining work and work for each assignment
                 * of the current task it is important because the duration
                 * is calculated based on the works assigned to each person
                 * (for example if a user is set to 100% but no Work and
                 * RemainingWork is set for him then it will not shorten the
                 * duration as expected)
                 */
                // process those assignments of the current task which were
                // imported last time but
                // no TCostBean corresponding to person were found for them
                // consequently
                // they wern't processed (removed) above in the loop for
                // persons.
                // Probably the TCostBean was removed since the last import.
                // The assignment will not be deleted (that should be made
                // in MsProject) but the
                // actual work will be set to 0 (no TCostBean). We still
                // need the assignment because of the
                // remaining work: if we would remove the entire assignment
                // the task duration would increase
                // because the remaining work of this assignment should be
                // taken by other resources
                Map<Integer, ResourceAssignment> importedResourceUIDToAssignmentsMap = importedTaskUIDToResourceUIDToAssignmentsMap
                        .get(taskUID);
                if (importedResourceUIDToAssignmentsMap != null
                        && importedResourceUIDToAssignmentsMap.size() > 0) {
                    Iterator<Integer> itrResource = importedResourceUIDToAssignmentsMap.keySet().iterator();
                    while (itrResource.hasNext()) {
                        Integer resouceID = itrResource.next();

                        ResourceAssignment noCostAssignmentElement = importedResourceUIDToAssignmentsMap
                                .remove(resouceID);
                        // String emptyValue =
                        // MsProjectExchangeBL.getTimeSpanFromDouble(0.0);
                        // reset the ActualWork to 0 because there is no
                        // costBean for this
                        // TODO MPXJ
                        // noCostAssignmentElement.setActualWork(emptyTimeSpan);
                        resoucesWithImportedRemainingWork.add(resouceID);
                        resourceBasedAssignmentsForWorkItem.put(resouceID, noCostAssignmentElement);
                        // TODO MPXJ
                        // removeTimephasedData(noCostAssignmentElement);
                    }
                }
                /**
                 * "normalize" the RemainingWork and Work for assignments
                 */
                // sum up the remaining work from each resource
                // (both new and imported assignments, but for new it is 0
                // anyway)
                double allPersonsRemainingWork = 0.0;
                for (Map.Entry<Integer, ResourceAssignment> entry : resourceBasedAssignmentsForWorkItem
                        .entrySet()) {
                    // Integer resourceID = entry.getKey();
                    ResourceAssignment assignmentElement = entry.getValue();
                    Double remainingWork = assignmentElement.getRemainingWork().getDuration();
                    if (remainingWork != null) {
                        allPersonsRemainingWork += remainingWork.doubleValue();
                    }
                }
                // remaining work for the entire task
                Double taskRemainingHours = taskElement.getRemainingWork().getDuration();
                if (taskRemainingHours == null) {
                    taskRemainingHours = new Double(0.0);
                }
                if (Math.abs(allPersonsRemainingWork - taskRemainingHours.doubleValue()) > 0.001) {
                    // "normalization" needed
                    if (allPersonsRemainingWork > taskRemainingHours.doubleValue()) {
                        // the task level remaining work is less than the
                        // sum if remaining work for assignments:
                        // (probably was explicitly set in track+ to a
                        // smaller value)
                        // we must remove some person level remainingWork at
                        // best effort
                        double difference = allPersonsRemainingWork - taskRemainingHours.doubleValue();
                        for (Iterator itrAssignments = resourceBasedAssignmentsForWorkItem.keySet()
                                .iterator(); itrAssignments.hasNext();) {
                            Integer resourceID = (Integer) itrAssignments.next();
                            ResourceAssignment assignmentElement = resourceBasedAssignmentsForWorkItem
                                    .get(resourceID);
                            Double remainingWork = assignmentElement.getRemainingWork().getDuration();
                            if (remainingWork != null && Math.abs(remainingWork.doubleValue()) > EPSILON) {
                                if (difference > remainingWork.doubleValue()) {
                                    // TODO MPXJ set setRemainingWork
                                    // validation.
                                    assignmentElement.setRemainingWork(
                                            Duration.getInstance(remainingWork, TimeUnit.HOURS));
                                    difference -= remainingWork.doubleValue();
                                } else {
                                    assignmentElement.setRemainingWork(Duration.getInstance(
                                            remainingWork.doubleValue() - difference, TimeUnit.HOURS));
                                    break;
                                }
                            }
                        }
                    } else {
                        // the difference should be added to one or more
                        // person specific remainingWork at best effort:
                        double difference = taskRemainingHours.doubleValue() - allPersonsRemainingWork;
                        List<ResourceAssignment> newRemainingWorkElements = new ArrayList<ResourceAssignment>();
                        // see whether there are new assignments (those
                        // which doesn't appear in the last import)
                        // because for them the remainingWork should not be
                        // preserved
                        for (Iterator itrAssignments = resourceBasedAssignmentsForWorkItem.keySet()
                                .iterator(); itrAssignments.hasNext();) {
                            Integer resourceID = (Integer) itrAssignments.next();
                            if (!resoucesWithImportedRemainingWork.contains(resourceID)) {
                                newRemainingWorkElements
                                        .add(resourceBasedAssignmentsForWorkItem.get(resourceID));
                            }
                        }
                        if (newRemainingWorkElements.isEmpty()
                                && resourceBasedAssignmentsForWorkItem.size() > 0) {
                            // no new assignment found, we must mess up a
                            // "to be preserved" remainingWork of an
                            // existing assignment
                            ResourceAssignment assignmentElement = resourceBasedAssignmentsForWorkItem.values()
                                    .iterator().next();
                            double remainingWork = assignmentElement.getRemainingWork().getDuration();
                            assignmentElement.setRemainingWork(
                                    Duration.getInstance(remainingWork + difference, TimeUnit.HOURS));
                        } else {
                            // new assignment(s) found: divide the remaining
                            // work equally for each new assignment
                            Double remainingWorkProPerson = difference / newRemainingWorkElements.size();
                            for (Iterator<ResourceAssignment> iterator = newRemainingWorkElements
                                    .iterator(); iterator.hasNext();) {
                                ResourceAssignment assignmentElement = iterator.next();
                                assignmentElement.setRemainingWork(
                                        Duration.getInstance(remainingWorkProPerson, TimeUnit.HOURS));
                            }
                        }
                    }
                }
                /*
                 * set the Works for each assignment: it is always the sum
                 * of actual work and remaining work (doesn't matter the
                 * value from track+ total budget)
                 */
                double taskActualOvertimeWork = 0.0;
                if (resourceBasedAssignmentsForWorkItem != null
                        && resourceBasedAssignmentsForWorkItem.size() > 0) {
                    for (Iterator itrAssignments = resourceBasedAssignmentsForWorkItem.keySet()
                            .iterator(); itrAssignments.hasNext();) {
                        Integer resourceID = (Integer) itrAssignments.next();
                        ResourceAssignment assignmentElement = resourceBasedAssignmentsForWorkItem
                                .get(resourceID);
                        Double remainingWorkHours = assignmentElement.getRemainingWork().getDuration();
                        if (remainingWorkHours != null
                                && Math.abs(remainingWorkHours.doubleValue()) > EPSILON) {
                            // if there is remaining work then remove the
                            // actual finish date
                            Date actualFinishElement = assignmentElement.getActualFinish();
                            if (actualFinishElement != null) {
                                project.getAllResourceAssignments().remove(assignmentElement);
                            }
                        }
                        // assignment level OvertimeWork,
                        // ActualOvertimeWork, RegularWork
                        Duration actualWorkDuration = assignmentElement.getActualWork();
                        Double actualWorkHours = null;
                        if (actualWorkDuration != null) {
                            actualWorkHours = actualWorkDuration.getDuration();
                        }
                        if (actualWorkHours == null) {
                            actualWorkHours = Double.valueOf(0);
                        }
                        Double work = remainingWorkHours + actualWorkHours;
                        assignmentElement.setWork(Duration.getInstance(work, TimeUnit.HOURS));
                        Duration overtimeWorkDuration = assignmentElement.getOvertimeWork();
                        Double assignmentOvertimeWork = null;
                        if (overtimeWorkDuration != null) {
                            assignmentOvertimeWork = overtimeWorkDuration.getDuration();
                        }
                        if (assignmentOvertimeWork == null) {
                            assignmentOvertimeWork = new Double(0);
                        }
                        /*
                         * Double assignmentActualOvertimeWork =
                         * assignmentElement.getActualWork().getDuration();
                         * if (assignmentActualOvertimeWork==null) {
                         * assignmentActualOvertimeWork = new Double(0); }
                         * taskActualOvertimeWork +=
                         * assignmentActualOvertimeWork.doubleValue();
                         */
                        taskActualOvertimeWork += actualWorkHours;
                        assignmentElement.setRegularWork(
                                Duration.getInstance(work - assignmentOvertimeWork, TimeUnit.HOURS));

                    }
                }
                // task level OvertimeWork, ActualOvertimeWork, RegularWork
                Duration overtimeWorkDuration = taskElement.getOvertimeWork();
                Double taskOvertimeWork = null;
                if (overtimeWorkDuration != null) {
                    taskOvertimeWork = overtimeWorkDuration.getDuration();
                }
                if (taskOvertimeWork == null) {
                    taskOvertimeWork = new Double(0);
                }
                // the OvertimeWork will not be less than the
                // ActualOvertimeWork
                if (taskActualOvertimeWork > taskOvertimeWork.doubleValue()) {
                    taskElement.setOvertimeWork(Duration.getInstance(taskActualOvertimeWork, TimeUnit.HOURS));
                    taskOvertimeWork = taskActualOvertimeWork;
                }
                if (taskActualOvertimeWork > 0.0) {
                    // taskElement.setActualOvertimeWork(Duration.getInstance(taskActualOvertimeWork,
                    // TimeUnit.HOURS));
                }
                Double work = taskElement.getWork().getDuration();
                if (work == null) {
                    work = new Double(0);
                }
                taskElement.setRegularWork(Duration
                        .getInstance(work.doubleValue() - taskOvertimeWork.doubleValue(), TimeUnit.HOURS));
                // task level ActualStart, Start and ActualFinish dates
                if (taskActualStart != null) {
                }
                Date startElement = taskElement.getStart();
                if (startElement != null) {
                    Date startDate = taskElement.getStart();
                    if (startDate != null && taskActualStart != null && startDate.after(taskActualStart)) {
                        // taskElement.setStart(taskActualStart);
                    }
                }
                if (taskActualFinish != null && taskRemainingHours != null
                        && Math.abs(taskRemainingHours.doubleValue()) < 0.0001) {
                    taskElement.setActualFinish(taskActualFinish);
                }
            }
        }
    }
    // assignments which still remained are probably from tasks which
    // doesn't have actualWork.
    // The actual work should be set to 0 (no TCostBean) anyway for each
    // one, but ideally none of them should
    // be deleted (the assignment is still needed because of their remaining
    // work assigned to a person).
    // If the remainingWork is changed for the workItem then we would have
    // the evenly distribute the difference
    // among the previously imported assignments' remainingWorks. This is
    // too complicated, instead we assign
    // the task's entire remainingWork to the first person and delete the
    // assignments for the other persons
    if (importedTaskUIDToResourceUIDToAssignmentsMap.size() > 0) {
        // TODO Parsing correctness validation
        for (Integer key : importedTaskUIDToResourceUIDToAssignmentsMap.keySet()) {
            Integer taskUID = key;
            Task taskElement = UIDBasedTaskElementMap.get(taskUID);
            if (taskElement != null && taskElement.getRemainingWork() != null) {
                Double taskRemainingWork = taskElement.getRemainingWork().getDuration();
                Map<Integer, ResourceAssignment> resourceUIDToAssignmentsMap = importedTaskUIDToResourceUIDToAssignmentsMap
                        .get(taskUID);
                if (resourceUIDToAssignmentsMap != null) {
                    boolean first = true;
                    for (Integer key2 : resourceUIDToAssignmentsMap.keySet()) {
                        Integer resourceID = resourceUIDToAssignmentsMap.get(key2).getUniqueID();
                        // only the real resourceIDs are important
                        if (first) {
                            // TODO assignmentElement REMAINING_WORK field
                            // missing
                            first = false;
                            ResourceAssignment assignmentElement = resourceUIDToAssignmentsMap.get(resourceID);
                            // assignmentElement.getTim
                            // reset the ActualWork to 0 because there is no
                            // costBean for this
                            // removeTimephasedData(assignmentElement);
                            // TODO MPXJ!
                            // assignmentElement.setActualWork(Duration.getInstance(emptyTimeSpan,
                            // TimeUnit.HOURS));
                            // work = actualWork + remainingWork
                            // so if we set actual work to emptyTimeSpan we
                            // should make work=remainingWork, otherwise the
                            // file doesn't open
                            // TODO MPXJ!!
                            // assignmentElement.setRemainingWork(Duration.getInstance(taskRemainingWork,
                            // TimeUnit.HOURS));
                            // MsProjectExchangeDOMHelper.setChildTextByName(assignmentElement,
                            // COMMON_ELEMENTS.Work, taskRemainingWork,
                            // true);
                            // TODO remove if statement MPXJ
                            if (assignmentElement != null) {
                                assignmentElement
                                        .setWork(Duration.getInstance(taskRemainingWork, TimeUnit.HOURS));
                            }
                        } else {
                            ResourceAssignment assignmentElement = resourceUIDToAssignmentsMap.get(resourceID);
                            project.getAllResourceAssignments().remove(assignmentElement);
                            // reset the ActualWork to 0 because there is no
                            // costBean for this
                        }
                    }
                }
            }
        }
    }
}

From source file:org.kalypso.ui.wizards.results.editor.EditStyleDialog.java

private void createStyleComponent(final Composite commonComposite) {
    m_symbolizer = parseStyle();//from w  w w.j a  v  a 2 s  .  c o  m
    /* choose the composite, depending on the style */
    if (m_symbolizer[0] instanceof SurfaceLineSymbolizer) {
        final SurfaceLineSymbolizer symb = (SurfaceLineSymbolizer) m_symbolizer[0];
        final LineColorMap colorMap = symb.getColorMap();
        if (colorMap.getColorMap().length > 0) {
            final LineColorMapEditorComposite comp = new LineColorMapEditorComposite(commonComposite, SWT.NONE,
                    colorMap, m_minValue, m_maxValue);
            final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
            gridDataComp.horizontalSpan = 2;
            comp.setLayoutData(gridDataComp);
        } else {
            final Text errorText = new Text(commonComposite, SWT.NONE);
            errorText.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.5")); //$NON-NLS-1$
            errorText.setBackground(commonComposite.getBackground());
        }
    } else if (m_symbolizer[0] instanceof SurfacePolygonSymbolizer) {
        final SurfacePolygonSymbolizer symb = (SurfacePolygonSymbolizer) m_symbolizer[0];
        final PolygonColorMap colorMap = symb.getColorMap();
        final PolygonColorMapEntry[] colorMapEntries = colorMap.getColorMap();
        if (colorMapEntries.length > 0) {
            final PolygonColorMapEntry fromEntry = colorMapEntries[0];
            final PolygonColorMapEntry toEntry = colorMapEntries[colorMapEntries.length - 1];

            final PolygonColorMapEditorComposite comp = new PolygonColorMapEditorComposite(commonComposite,
                    SWT.NONE, fromEntry, toEntry, m_minValue, m_maxValue) {
                @Override
                protected void colorMapChanged() {
                    final List<PolygonColorMapEntry> colorMapList = getColorMap();
                    if (colorMapList.size() > 0)
                        colorMap.replaceColorMap(colorMapList);
                }
            };
            final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
            gridDataComp.horizontalSpan = 2;
            comp.setLayoutData(gridDataComp);
        } else {
            final Text errorText = new Text(commonComposite, SWT.NONE);
            errorText.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.6")); //$NON-NLS-1$
            errorText.setBackground(commonComposite.getBackground());
        }
    } else if (m_symbolizer[0] instanceof PointSymbolizer) {
        final PointSymbolizer symb = (PointSymbolizer) m_symbolizer[0];
        final Object[] mag = symb.getGraphic().getMarksAndExtGraphics();
        final Object object = mag[0];
        /*
         * getting the static map for actual step with settings for using in property function
         */
        final String sourceFile = m_resultAddLayerCommandData.getSource();
        final int beginIndex = sourceFile.indexOf(ResultMeta1d2dHelper.TIME_STEP_PREFIX)
                + ResultMeta1d2dHelper.TIME_STEP_PREFIX.length();
        final String stepName = sourceFile.substring(beginIndex, beginIndex + 16);
        final String nodeStyleType = ResultMeta1d2dHelper
                .resolveResultTypeFromSldFileName(m_fileName, NodeResultHelper.NODE_TYPE).toLowerCase();
        // m_mapSldSettingsIntern = NodeResultHelper.getSldSettingsMapForStyleStep( nodeStyleType, stepName );
        m_mapSldSettingsIntern = NodeResultHelper.getSldSettingsMapForStep(stepName);
        if (object instanceof Mark) {
            m_mark = (Mark) object;
            try {
                m_fill = m_mark.getFill();
                if (m_fill.getGraphicFill() == null
                        && !nodeStyleType.equals(NodeResultHelper.VELO_TYPE.toLowerCase())
                        && !nodeStyleType.equals(NodeResultHelper.WAVE_DIRECTION_TYPE.toLowerCase())) {
                    /*
                     * getting the according values from sld file, needen to save the last selected configuration for next calls
                     */
                    final CssParameter cssFillMin = m_fill.getParameter("minColor"); //$NON-NLS-1$
                    final CssParameter cssFillMax = m_fill.getParameter("maxColor"); //$NON-NLS-1$
                    final CssParameter cssValueAmountClasses = m_fill.getParameter("amountClasses"); //$NON-NLS-1$
                    Color fromColor = resolveColor(
                            m_mapSldSettingsIntern.get(NodeResultHelper.COLOR_MIN_PREFIX + nodeStyleType));
                    Color toColor = resolveColor(
                            m_mapSldSettingsIntern.get(NodeResultHelper.COLOR_MAX_PREFIX + nodeStyleType));
                    Double amountOfClasses = (Double) m_mapSldSettingsIntern
                            .get(NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType);
                    try {
                        /*
                         * replacing the information needed for color settings from the loaded sld. initially set from the static
                         * map in the helper. if this data was provided in sld, set it also in to the map
                         */
                        fromColor = (Color) extractCssValue(cssFillMin);
                        toColor = (Color) extractCssValue(cssFillMax);
                        final Double extValueMin = (Double) m_mapSldSettingsIntern
                                .get(NodeResultHelper.VALUE_MIN_PREFIX + nodeStyleType);
                        final Double extValueMax = (Double) m_mapSldSettingsIntern
                                .get(NodeResultHelper.VALUE_MAX_PREFIX + nodeStyleType);
                        amountOfClasses = (Double) extractCssValue(cssValueAmountClasses);
                        m_mapSldSettingsIntern.put(NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType,
                                amountOfClasses);
                        m_maxValue = new BigDecimal(extValueMax);
                        m_minValue = new BigDecimal(extValueMin);
                    } catch (final Exception e) {
                        e.printStackTrace();
                    }
                    final BigDecimal width = m_maxValue.subtract(m_minValue)
                            .divide(new BigDecimal(4), BigDecimal.ROUND_HALF_UP)
                            .setScale(3, BigDecimal.ROUND_HALF_UP);

                    final PolygonColorMapEntry fromEntry = StyleFactory.createPolygonColorMapEntry(fromColor,
                            fromColor, m_minValue, m_minValue.add(width));
                    final PolygonColorMapEntry toEntry = StyleFactory.createPolygonColorMapEntry(toColor,
                            toColor, m_maxValue.subtract(width), m_maxValue);
                    final NodeStyleEditorComposite comp = new NodeStyleEditorComposite(commonComposite,
                            SWT.NONE, fromEntry, toEntry, m_minValue, m_maxValue, amountOfClasses.intValue()) {
                        private Map<Integer, Color> m_mapActualColorsCache;

                        @Override
                        protected void contentChanged() {
                            m_boolNodeStyleChanged = true;
                            /*
                             * changing the name is needed to be placed in sld file.
                             */
                            final CssParameter newMinColor = getFromEntry().getFill().getParameter("fill"); //$NON-NLS-1$
                            newMinColor.setName("minColor"); //$NON-NLS-1$
                            m_fill.addCssParameter("minColor", newMinColor); //$NON-NLS-1$
                            final CssParameter newMaxColor = getToEntry().getFill().getParameter("fill"); //$NON-NLS-1$
                            newMaxColor.setName("maxColor"); //$NON-NLS-1$
                            m_fill.addCssParameter("maxColor", newMaxColor); //$NON-NLS-1$

                            final Double newAmountClasses = ((Integer) getAmountOfClassesForInterpolation())
                                    .doubleValue();
                            final CssParameter cssNewValueAmountClasses = m_fill.getParameter("amountClasses"); //$NON-NLS-1$
                            cssNewValueAmountClasses.setValue("" + newAmountClasses); //$NON-NLS-1$
                            m_fill.addCssParameter("amountClasses", cssNewValueAmountClasses); //$NON-NLS-1$

                            final Color extractedCssValueMinColor = (Color) extractCssValue(newMinColor);
                            m_mapSldSettingsIntern.put(NodeResultHelper.COLOR_MIN_PREFIX + nodeStyleType,
                                    extractedCssValueMinColor);
                            final Color extractedCssValueMaxColor = (Color) extractCssValue(newMaxColor);
                            m_mapSldSettingsIntern.put(NodeResultHelper.COLOR_MAX_PREFIX + nodeStyleType,
                                    extractedCssValueMaxColor);
                            m_mapSldSettingsIntern.put(
                                    NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType,
                                    newAmountClasses);
                            /*
                             * this map placed also in the settings of actual result step, works as a cache of interpolated color,
                             * by changing of color settings should be reseted
                             */
                            m_mapActualColorsCache = (Map<Integer, Color>) m_mapSldSettingsIntern
                                    .get(NodeResultHelper.COLOR_MAP_PREFIX + nodeStyleType);
                            if (m_mapActualColorsCache != null)
                                m_mapActualColorsCache.clear();
                        }
                    };
                    final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
                    gridDataComp.horizontalSpan = 2;
                    comp.setLayoutData(gridDataComp);

                    return;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        final Double extValueMin = (Double) m_mapSldSettingsIntern
                .get(NodeResultHelper.VALUE_MIN_PREFIX + nodeStyleType);
        final Double extValueMax = (Double) m_mapSldSettingsIntern
                .get(NodeResultHelper.VALUE_MAX_PREFIX + nodeStyleType);
        m_maxValue = new BigDecimal(extValueMax).setScale(2, BigDecimal.ROUND_HALF_UP);
        m_minValue = new BigDecimal(extValueMin).setScale(2, BigDecimal.ROUND_HALF_UP);
        final VectorEditorComposite comp = new VectorEditorComposite(commonComposite, SWT.NONE, symb,
                m_minValue, m_maxValue);
        final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
        gridDataComp.horizontalSpan = 2;
        comp.setLayoutData(gridDataComp);
    } else {
        final Text errorText1 = new Text(commonComposite, SWT.NONE);
        final GridData gridDataText1 = new GridData(SWT.BEGINNING, SWT.CENTER, true, true);
        gridDataText1.horizontalSpan = 2;
        gridDataText1.widthHint = 400;

        errorText1.setLayoutData(gridDataText1);
        errorText1.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.7")); //$NON-NLS-1$
        errorText1.setBackground(commonComposite.getBackground());

        final Text errorText2 = new Text(commonComposite, SWT.NONE);
        errorText2.setLayoutData(gridDataText1);
        errorText2.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.8")); //$NON-NLS-1$
        errorText2.setBackground(commonComposite.getBackground());
    }
}

From source file:org.openmrs.web.controller.ConceptStatsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 *//* ww  w .  j  a  v a  2  s . co m*/
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    if (!Context.hasPrivilege("View Observations")) {
        return map;
    }

    MessageSourceAccessor msa = getMessageSourceAccessor();
    Locale locale = Context.getLocale();
    ConceptService cs = Context.getConceptService();
    String conceptId = request.getParameter("conceptId");
    //List<Obs> obs = new Vector<Obs>();
    //List<Obs> obsAnswered = new Vector<Obs>();

    if (conceptId != null) {
        Concept concept = cs.getConcept(Integer.valueOf(conceptId));
        ObsService obsService = Context.getObsService();

        if (concept != null) {

            // previous/next ids for links
            map.put("previousConcept", cs.getPrevConcept(concept));
            map.put("nextConcept", cs.getNextConcept(concept));

            //obs = obsService.getObservations(concept, "valueNumeric, obsId");
            //obsAnswered = obsService.getObservationsAnsweredByConcept(concept);

            if (ConceptDatatype.NUMERIC.equals(concept.getDatatype().getHl7Abbreviation())) {
                map.put("displayType", "numeric");

                List<Obs> numericAnswers = obsService.getObservations(null, null,
                        Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null,
                        Collections.singletonList("valueNumeric"), null, null, null, null, false);

                if (numericAnswers.size() > 0) {
                    Double min = numericAnswers.get(0).getValueNumeric();
                    Double max = (Double) numericAnswers.get(numericAnswers.size() - 1).getValueNumeric();
                    Double median = (Double) numericAnswers.get(numericAnswers.size() / 2).getValueNumeric();

                    Map<Double, Integer> counts = new HashMap<Double, Integer>(); // counts for the histogram
                    Double total = 0.0; // sum of values. used for mean

                    // dataset setup for lineChart
                    TimeSeries timeSeries = new TimeSeries(concept.getName().getName(), Day.class);
                    TimeSeriesCollection timeDataset = new TimeSeriesCollection();
                    Calendar calendar = Calendar.getInstance();

                    // array for histogram
                    double[] obsNumerics = new double[(numericAnswers.size())];

                    Integer i = 0;
                    for (Obs obs : numericAnswers) {
                        Date date = (Date) obs.getObsDatetime();
                        Double value = (Double) obs.getValueNumeric();

                        // for mean calculation
                        total += value;

                        // for histogram
                        obsNumerics[i++] = value;
                        Integer count = counts.get(value);
                        counts.put(value, count == null ? 1 : count + 1);

                        // for line chart
                        calendar.setTime(date);
                        Day day = new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, // January = 0 
                                calendar.get(Calendar.YEAR) < 1900 ? 1900 : calendar.get(Calendar.YEAR) // jfree chart doesn't like the 19th century
                        );
                        timeSeries.addOrUpdate(day, value);
                    }

                    Double size = new Double(numericAnswers.size());
                    Double mean = total / size;

                    map.put("size", numericAnswers.size());
                    map.put("min", min);
                    map.put("max", max);
                    map.put("mean", mean);
                    map.put("median", median);

                    // create histogram chart
                    HistogramDataset histDataset = new HistogramDataset(); // dataset for histogram
                    histDataset.addSeries(concept.getName().getName(), obsNumerics, counts.size());

                    JFreeChart histogram = ChartFactory.createHistogram(concept.getName().getName(),
                            msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                            msa.getMessage("Concept.stats.histogramRangeAxisTitle"), histDataset,
                            PlotOrientation.VERTICAL, false, true, false);
                    map.put("histogram", histogram);

                    if (size > 25) {
                        // calculate 98th percentile of the data:
                        Double x = 0.98;
                        Integer xpercentile = (int) (x * size);
                        Double upperQuartile = numericAnswers.get(xpercentile).getValueNumeric();
                        Double lowerQuartile = numericAnswers.get((int) (size - xpercentile)).getValueNumeric();
                        Double innerQuartile = upperQuartile - lowerQuartile;
                        Double innerQuartileLimit = innerQuartile * 1.5; // outliers will be greater than this from the upper/lower quartile
                        Double upperQuartileLimit = upperQuartile + innerQuartileLimit;
                        Double lowerQuartileLimit = lowerQuartile - innerQuartileLimit;

                        List<Obs> outliers = new Vector<Obs>();

                        // move outliers to the outliers list
                        // removing lower quartile outliers
                        for (i = 0; i < size - xpercentile; i++) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() >= lowerQuartileLimit) {
                                break; // quit if this value is greater than the lower limit
                            }
                            outliers.add(possibleOutlier);
                        }

                        // removing upper quartile outliers
                        for (i = size.intValue() - 1; i >= xpercentile; i--) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() <= upperQuartileLimit) {
                                break; // quit if this value is less than the upper limit
                            }
                            outliers.add(possibleOutlier);
                        }
                        numericAnswers.removeAll(outliers);

                        double[] obsNumericsOutliers = new double[(numericAnswers.size())];
                        i = 0;
                        counts.clear();
                        for (Obs values : numericAnswers) {
                            Double value = values.getValueNumeric();
                            obsNumericsOutliers[i++] = value;
                            Integer count = counts.get(value);
                            counts.put(value, count == null ? 1 : count + 1);
                        }

                        // create outlier histogram chart
                        HistogramDataset outlierHistDataset = new HistogramDataset();
                        outlierHistDataset.addSeries(concept.getName().getName(), obsNumericsOutliers,
                                counts.size());

                        JFreeChart histogramOutliers = ChartFactory.createHistogram(concept.getName().getName(),
                                msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                                msa.getMessage("Concept.stats.histogramRangeAxisTitle"), outlierHistDataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        map.put("histogramOutliers", histogramOutliers);
                        map.put("outliers", outliers);

                    }

                    // create line graph chart
                    timeDataset.addSeries(timeSeries);
                    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(concept.getName().getName(),
                            msa.getMessage("Concept.stats.lineChartDomainAxisLabel"),
                            msa.getMessage("Concept.stats.lineChartRangeAxisLabel"), timeDataset, false, true,
                            false);
                    map.put("timeSeries", lineChart);

                }
            } else if (ConceptDatatype.BOOLEAN.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create bar chart for boolean answers
                map.put("displayType", "boolean");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Boolean answer = o.getValueAsBoolean();
                    if (answer == null) {
                        answer = false;
                    }
                    String name = answer.toString();
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            } else if (ConceptDatatype.CODED.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create pie graph for coded answers
                map.put("displayType", "coded");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Concept value = o.getValueCoded();
                    String name;
                    if (value == null) {
                        name = "[value_coded is null]";
                    } else {
                        name = value.getName().getName();
                    }
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            }
        }

    }

    //map.put("obs", obs);
    //map.put("obsAnswered", obsAnswered);

    map.put("locale", locale.getLanguage().substring(0, 2));

    return map;
}

From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java

public Date getLastDoseObsDate(Integer personId, String conceptName, Integer doseNumber) {
    List<Obs> matchingObs = obsService.getObservationsByPersonAndConcept(personService.getPerson(personId),
            conceptService.getConcept(conceptName));
    for (Obs obs : matchingObs) {
        Double value = obs.getValueNumeric();
        if (value != null && doseNumber == value.intValue()) {
            return obs.getObsDatetime();
        }/*  w  w w . jav a  2s .c o m*/
    }
    return null;
}

From source file:org.motechproject.server.svc.impl.RegistrarBeanImpl.java

public Date getLastDoseObsDateInActivePregnancy(Integer patientId, String conceptName, Integer doseNumber) {
    Obs pregnancy = getActivePregnancy(patientId);
    if (pregnancy != null) {
        Integer pregnancyObsId = pregnancy.getObsId();
        List<Obs> matchingObs = getMatchingObs(personService.getPerson(patientId),
                conceptService.getConcept(conceptName), null, pregnancyObsId, null, null);
        for (Obs obs : matchingObs) {
            Double value = obs.getValueNumeric();
            if (value != null && doseNumber == value.intValue()) {
                return obs.getObsDatetime();
            }/*from ww  w.  j a  v  a  2  s. co m*/
        }
    }
    return null;
}