Example usage for java.lang Double doubleValue

List of usage examples for java.lang Double doubleValue

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public double doubleValue() 

Source Link

Document

Returns the double value of this Double object.

Usage

From source file:org.sakaiproject.tool.gradebook.ui.SpreadsheetUploadBean.java

/**
 * Returns a list of AssignmentGradeRecords that are different than in current
 * Gradebook. Returns empty List if no differences found.
 *
 * @param assignment/*from   ww w.  ja  v  a2 s . com*/
 *          The Assignment object whose grades need to be checked
 * @param fromSpreadsheet
 *          The rows of grades from the imported spreadsheet
 * @param index
 *          The column of spreadsheet to check
 *
 * @return
 *          List containing AssignmentGradeRecords for those student's grades that
 *          have changed
 */
private List gradeChanges(Assignment assignment, List fromSpreadsheet, int index,
        LetterGradePercentMapping lgpm) {
    List updatedGradeRecords = new ArrayList();
    List studentUids = new ArrayList();
    List studentRowsWithUids = new ArrayList();

    Iterator it = fromSpreadsheet.iterator();

    while (it.hasNext()) {
        final SpreadsheetRow row = (SpreadsheetRow) it.next();
        List line = row.getRowcontent();

        String userid = "";
        final String user = ((String) line.get(0)).toLowerCase();
        try {
            userid = ((User) rosterMap.get(user)).getUserUid();

            // create list of uids to get current grades from gradebook
            studentUids.add(userid);

            // add uid to each row so can check spreadsheet value against currently stored
            List linePlus = new ArrayList();
            linePlus.add(userid);
            linePlus.addAll(line);
            studentRowsWithUids.add(linePlus);

        } catch (Exception e) {
            // Weirdness. Should be caught when importing, not here
        }
    }

    List gbGrades = getGradebookManager().getAssignmentGradeRecordsConverted(assignment, studentUids);

    // now do the actual comparison
    it = studentRowsWithUids.iterator();

    boolean updatingExternalGrade = false;
    while (it.hasNext()) {
        final List aRow = (List) it.next();

        final String userid = (String) aRow.get(0);
        final String user = (String) aRow.get(1);

        AssignmentGradeRecord gr = findGradeRecord(gbGrades, userid);

        String score = null;
        if (index < aRow.size()) {
            score = ((String) aRow.get(index)).trim();
        }

        if (getGradeEntryByPercent() || getGradeEntryByPoints()) {
            Double scoreEarned = null;
            boolean updateScore = true;
            if (score != null && !"".equals(score)) {
                try {
                    scoreEarned = convertStringToDouble(score);
                } catch (ParseException pe) {
                    // this should have already been validated at this point, so there is
                    // something wrong if we made it here
                    logger.error(
                            "ParseException encountered while checking for grade updates with score: " + score);
                    updateScore = false;
                }

                // truncate to 2 decimal places
                if (scoreEarned != null)
                    scoreEarned = new Double(FacesUtil.getRoundDown(scoreEarned.doubleValue(), 2));
            }

            if (updateScore) {
                if (gr == null) {
                    if (scoreEarned != null) {
                        if (!assignment.isExternallyMaintained()) {
                            gr = new AssignmentGradeRecord(assignment, userid, scoreEarned);
                            gr.setPercentEarned(scoreEarned); // manager will handle if % vs point grading
                            updatedGradeRecords.add(gr);
                        } else {
                            updatingExternalGrade = true;
                        }
                    }
                } else {
                    // we need to truncate points earned to 2 decimal places to more accurately
                    // see if it was changed - scores that are entered as % can be stored with
                    // unlimited decimal places in db
                    Double gbScoreEarned = null;
                    if (getGradeEntryByPercent())
                        gbScoreEarned = gr.getPercentEarned();
                    else
                        gbScoreEarned = gr.getPointsEarned();

                    if (gbScoreEarned != null)
                        gbScoreEarned = new Double(FacesUtil.getRoundDown(gbScoreEarned.doubleValue(), 2));

                    // 3 ways points earned different: 1 null other not (both ways) or actual
                    // values different
                    if ((gbScoreEarned == null && scoreEarned != null)
                            || (gbScoreEarned != null && scoreEarned == null)
                            || (gbScoreEarned != null && scoreEarned != null
                                    && gbScoreEarned.doubleValue() != scoreEarned.doubleValue())) {

                        gr.setPointsEarned(scoreEarned); //manager will use correct field depending on grade entry method
                        gr.setPercentEarned(scoreEarned);
                        if (!assignment.isExternallyMaintained())
                            updatedGradeRecords.add(gr);
                        else
                            updatingExternalGrade = true;
                    }
                }
            }
        } else if (getGradeEntryByLetter()) {
            if (lgpm == null || lgpm.getGradeMap() == null)
                return null;
            if (score != null && score.length() > 0) {
                score = lgpm.standardizeInputGrade(score);
            }

            if (gr == null) {
                if (score != null && score.length() > 0) {
                    if (!assignment.isExternallyMaintained()) {
                        gr = new AssignmentGradeRecord(assignment, userid, null);
                        gr.setLetterEarned(score);
                        updatedGradeRecords.add(gr);
                    } else {
                        updatingExternalGrade = true;
                    }
                }
            } else {
                String gbLetterEarned = gr.getLetterEarned();

                if ((gbLetterEarned != null && !gbLetterEarned.equals(score))
                        || (gbLetterEarned == null && score != null)) {

                    gr.setLetterEarned(score);
                    if (!assignment.isExternallyMaintained())
                        updatedGradeRecords.add(gr);
                    else
                        updatingExternalGrade = true;
                }
            }
        }
    }

    if (updatingExternalGrade)
        externallyMaintainedImportMsg
                .append(getLocalizedString("import_assignment_externally_maintained_grades",
                        new String[] { Validator.escapeHtml(assignment.getName()),
                                Validator.escapeHtml(assignment.getExternalAppName()) })
                        + "<br/>");

    return updatedGradeRecords;
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private void setDeviceElevation(HmFolder folder) {
    Double apElevation = folder.getDeviceElevation();
    if (apElevation == null) {
        folder.setDeviceElevation(getDefaultApElevation(folder));
    } else {//from  w w w.j ava2 s.c  o m
        double maxApElevation = MAX_AP_ELEVATION;
        if (folder.getLengthUnit() == LengthUnit.FEET) {
            maxApElevation /= FEET_TO_METERS;
        }
        double elevation = Math.min(apElevation.doubleValue(), maxApElevation);
        folder.setDeviceElevation(elevation);
    }
}

From source file:es.sm2.openppm.front.servlets.ProjectPlanServlet.java

/**
  * Approve Project//from ww  w  . j  ava2  s  .c o  m
  * @param req
  * @param resp
  * @throws ServletException
  * @throws IOException
  */
private void approveProject(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Integer idProject = ParamUtil.getInteger(req, "id");
    String scopeStatement = ParamUtil.getString(req, "scope_statement", StringPool.BLANK);

    boolean error = false;
    Project project = null;
    List<ParamResourceBundle> errors = new ArrayList<ParamResourceBundle>();
    ProjectLogic projectLogic = new ProjectLogic(getSettings(req), getResourceBundle(req));
    try {
        MilestoneLogic milestoneLogic = new MilestoneLogic();
        ProjectKpiLogic kpiLogic = new ProjectKpiLogic();
        WBSNodeLogic wbsNodeLogic = new WBSNodeLogic();

        project = projectLogic.consProject(idProject);

        List<Projectkpi> kpis = kpiLogic.findByRelation(Projectkpi.PROJECT, project);

        if (kpis != null && !kpis.isEmpty()) {

            int weight = 0;
            for (Projectkpi kpi : kpis) {

                weight += (kpi.getWeight() == null ? 0 : kpi.getWeight());
            }
            if (weight != 100) {
                throw new LogicException("msg.error.kpi_total_weight");
            }
        }

        project.setScopeStatement(scopeStatement);
        projectLogic.saveAndUpdateDataProject(project);

        errors = wbsNodeLogic.checkErrorsWBS(project);

        Double budget = wbsNodeLogic.consTotalBudget(project);
        if (project.getBac() == null || budget == null
                || budget.doubleValue() != project.getBac().doubleValue()) {
            info(StringPool.INFORMATION, req, "msg.info.bac_equals_budget");
        }

        if (milestoneLogic.checkMilestones(project)) {
            errors.add(new ParamResourceBundle("msg.error.milestones_without_activity"));
        }
        if (!errors.isEmpty()) {
            error = true;
        }

    } catch (Exception e) {
        error = true;
        ExceptionUtil.evalueException(req, getResourceBundle(req), LOGGER, e);
    }

    if (!error) {
        try {
            projectLogic.approveProject(project, getUser(req));
        } catch (Exception e) {
            error = true;
            ExceptionUtil.evalueException(req, getResourceBundle(req), LOGGER, e);
        }
    }

    if (error) {
        if (!errors.isEmpty()) {
            StringBuilder infoMsg = new StringBuilder();
            for (ParamResourceBundle er : errors) {
                infoMsg.append(er.toString(getResourceBundle(req)) + "<br>");
            }
            req.setAttribute(StringPool.ERROR, infoMsg.toString());
        }

        viewProjectPlanning(req, resp, idProject);
    } else {
        forwardServlet(ProjectControlServlet.REFERENCE + "?accion=", req, resp);
    }
}

From source file:org.energy_home.jemma.ah.internal.greenathome.GreenathomeAppliance.java

public Hashtable getApplianceConfiguration(IAppliance peerAppliance, int endPointId)
        throws ApplianceException, ServiceClusterException {
    int availability = 0;
    int state = 0;
    int status = 0;
    boolean isStateChangable = false;

    String locationPid = null;/*  ww w .j  av  a 2 s  . co  m*/
    String categoryPid = null;

    Hashtable props = new Hashtable();

    AttributeValueExtended attributeValue = null;

    String appliancePid = getApplianceId(peerAppliance.getPid(), endPointId);

    String appType = peerAppliance.getDescriptor().getType();
    String endPointType = peerAppliance.getEndPoint(endPointId).getType();
    // !!! Energy@home webui compatibility
    if (endPointType == IEndPointTypes.ZIGBEE_ON_OFF_SWITCH_DEVICE)
        return null;

    appType = encodeGenericApplianceType(appType, endPointType);

    props.put(IAppliance.APPLIANCE_TYPE_PROPERTY, appType);
    props.put(IAppliance.APPLIANCE_PID, appliancePid);

    OnOffServer onOffServer = null;
    onOffServer = (OnOffServer) greenathomeEndPoint.getPeerServiceCluster(peerAppliance.getPid(),
            OnOffServer.class.getName(), endPointId);
    if (onOffServer != null) {
        isStateChangable = true;
        availability = ((IServiceCluster) onOffServer).getEndPoint().isAvailable() ? 2 : 0;
        boolean onOff = false;

        if (availability == 2) {
            Boolean onOffValue = (Boolean) this.onOffValues.get(peerAppliance.getPid());
            if (doReadOnOff() || (onOffValue == null)) {
                try {
                    onOff = onOffServer.getOnOff(onOffCommandContext);
                    this.onOffValues.put(peerAppliance.getPid(), new Boolean(onOff));

                } catch (Exception e) {
                    // availability = 0;
                    state = Unknown;
                }
            } else {
                onOff = onOffValue.booleanValue();
            }

            if (onOff)
                state = On;
            else
                state = Off;
        } else {
            this.onOffValues.remove(peerAppliance.getPid());
            state = Unknown;
        }
    }

    ApplianceControlServer applianceControlServer = (ApplianceControlServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), ApplianceControlServer.class.getName(), endPointId);

    /*
     * if (applianceControlServer != null) { availability =
     * ((IServiceCluster)
     * applianceControlServer).getEndPoint().isAvailable() ? 2 : 0; if
     * (readApplianceStatus) { isStateChangable = true;
     * 
     * int applianceStatus = 0;
     * 
     * try { applianceStatus =
     * applianceControlServer.getApplianceStatus(null);
     * 
     * if (logEnabled) log.debug("applianceStatus is " + applianceStatus);
     * 
     * if (applianceStatus < 0x03) { state = Off; } else { state = On; } }
     * catch (Exception e) { state = Unknown; } } else { state = Unknown; }
     * }
     */

    IASZoneServer iasZoneServer = (IASZoneServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), IASZoneServer.class.getName(), endPointId);

    if (iasZoneServer != null) {
        isStateChangable = false;
        availability = ((IServiceCluster) iasZoneServer).getEndPoint().isAvailable() ? 2 : 0;
        state = Unknown;

        Integer zoneStatus = (Integer) this.zoneStatusTable.get(peerAppliance.getPid());
        int iasZoneType = 0;

        if (zoneStatus != null) {

            Integer iasZoneTypeValue = (Integer) this.iasZoneTypeValues.get(peerAppliance.getPid());
            if (iasZoneTypeValue == null) {
                iasZoneType = iasZoneServer.getZoneType(onOffCommandContext);
                this.iasZoneTypeValues.put(peerAppliance.getPid(), new Integer(iasZoneType));
            } else {
                iasZoneType = iasZoneTypeValue.intValue();
            }

            String value = "";
            try {

                switch (iasZoneType) {
                case 0x0015:
                    if ((zoneStatus.intValue() & 0x01) > 0)
                        value = "Aperto";
                    else
                        value = "Chiuso";
                    break;

                case 0x002a:
                    if ((zoneStatus.intValue() & 0x01) > 0)
                        value = "Overflow";
                    else
                        value = "Normal";
                    break;
                }

                if ((zoneStatus.intValue() & 0x08) > 0)
                    value += "(Low Battery)";
                else
                    value += "";

                attributeValue = new AttributeValueExtended("ZoneStatus", new AttributeValue(value));
                if (attributeValue != null)
                    props.put("device_value", attributeValue);

            } catch (Exception e) {
                value = "nd";
            }

        } else if (hapService != null) {
            // Code added because IASZone cluster is now used by HAP Proxy and cannot be
            // simultaneously used by Green@Home appliance through connections

            String value = "";
            ContentInstance ci = null;
            try {
                AHContainerAddress containerAddress = hapService.getHagContainerAddress(appliancePid,
                        endPointId, AHContainers.attrId_ah_cluster_iascontact_open);
                ci = hapService.getCachedLatestContentInstance(containerAddress);
            } catch (Exception e) {
                log.error("Error while reading isopen container", e);
            }

            if (ci == null) {
                value = "nd";
            } else {
                Object content = ci.getContent();
                if (content != null) {
                    if (((Boolean) content).booleanValue())
                        value = "Aperto";
                    else
                        value = "Chiuso";
                }
                attributeValue = new AttributeValueExtended("ZoneStatus", new AttributeValue(value));
                if (attributeValue != null)
                    props.put("device_value", attributeValue);
            }
        }
    }

    IlluminanceMeasurementServer illuminanceMeasurementServer = (IlluminanceMeasurementServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), IlluminanceMeasurementServer.class.getName(),
                    endPointId);

    if (illuminanceMeasurementServer != null) {
        isStateChangable = false;
        availability = ((IServiceCluster) illuminanceMeasurementServer).getEndPoint().isAvailable() ? 2 : 0;
        state = Unknown;

        IAttributeValue measuredValue = (IAttributeValue) this.measuredValues.get(peerAppliance.getPid());
        if (measuredValue != null) {
            int illuminance = ((Integer) measuredValue.getValue()).intValue();
            String value = "";
            if (illuminance == 0x0000) {
                value = "Too Low";
            } else {
                value = new DecimalFormat("#.##").format(illuminance) + "";
            }

            attributeValue = new AttributeValueExtended("Illuminance", new AttributeValue(value));
            if (attributeValue != null)
                props.put("device_value", attributeValue);
        }
    }

    OccupancySensingServer occupancySensingServer = (OccupancySensingServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), OccupancySensingServer.class.getName(), endPointId);

    if (occupancySensingServer != null) {
        isStateChangable = true;
        availability = ((IServiceCluster) occupancySensingServer).getEndPoint().isAvailable() ? 2 : 0;
        state = Unknown;

        IAttributeValue occupancyValue = (IAttributeValue) this.occupancySensing.get(peerAppliance.getPid());
        if (occupancyValue != null) {
            Short value = (Short) occupancyValue.getValue();
            if ((value.intValue() & 0x01) > 0)
                attributeValue = new AttributeValueExtended("Occupancy", new AttributeValue("Occupato"));
            else
                attributeValue = new AttributeValueExtended("Occupancy", new AttributeValue("Libero"));

            if (attributeValue != null)
                props.put("device_value", attributeValue);
        }
    }

    TemperatureMeasurementServer temperatureMeasurementServer = (TemperatureMeasurementServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), TemperatureMeasurementServer.class.getName(),
                    endPointId);

    if (temperatureMeasurementServer != null) {
        isStateChangable = true;
        availability = ((IServiceCluster) temperatureMeasurementServer).getEndPoint().isAvailable() ? 2 : 0;
        state = Unknown;

        IAttributeValue measuredValue = (IAttributeValue) this.measuredValues.get(peerAppliance.getPid());
        if (measuredValue != null) {
            double value = ((double) ((Integer) measuredValue.getValue()).intValue()) / 100;
            attributeValue = new AttributeValueExtended("Temperature",
                    new AttributeValue(new DecimalFormat("#.##").format(value) + " C"));

            if (attributeValue != null)
                props.put("device_value", attributeValue);
        }
    }

    ThermostatServer thermostatServer = (ThermostatServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), ThermostatServer.class.getName(), endPointId);
    if (thermostatServer != null) {
        isStateChangable = true;
        availability = ((IServiceCluster) thermostatServer).getEndPoint().isAvailable() ? 2 : 0;
        int applianceStatus = 0;
    }
    RelativeHumidityMeasurementServer humidityServer = (RelativeHumidityMeasurementServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), RelativeHumidityMeasurementServer.class.getName());
    if (humidityServer != null) {
        isStateChangable = true;
        availability = ((IServiceCluster) humidityServer).getEndPoint().isAvailable() ? 2 : 0;

        int applianceStatus = 0;
    }

    // handle Smart Info and Smart Plugs
    SimpleMeteringServer simpleMeteringServer = (SimpleMeteringServer) greenathomeEndPoint
            .getPeerServiceCluster(peerAppliance.getPid(), SimpleMeteringServer.class.getName(), endPointId);

    if (onOffServer == null && simpleMeteringServer != null) {
        availability = ((IServiceCluster) simpleMeteringServer).getEndPoint().isAvailable() ? 2 : 0;
    }

    ConfigServer configServer = (ConfigServer) greenathomeEndPoint.getPeerServiceCluster(peerAppliance.getPid(),
            ConfigServer.class.getName(), endPointId);

    if (configServer != null) {
        locationPid = configServer.getLocationPid(null);

        if (locationPid == null) {
            locationPid = "0";
        }
        props.put(IAppliance.APPLIANCE_LOCATION_PID_PROPERTY, locationPid);

        categoryPid = configServer.getCategoryPid(null);
        if (categoryPid == null) {
            categoryPid = "0";
        }
        props.put(IAppliance.APPLIANCE_CATEGORY_PID_PROPERTY, categoryPid);

        try {
            props.put(IAppliance.APPLIANCE_NAME_PROPERTY, configServer.getName(null));
        } catch (Exception e) {
            props.put(IAppliance.APPLIANCE_NAME_PROPERTY, peerAppliance.getPid());
        }

        try {
            props.put(IAppliance.APPLIANCE_ICON_PROPERTY, configServer.getIconName(null));
        } catch (Exception e) {
            props.put(IAppliance.APPLIANCE_ICON_PROPERTY, "plug.png");
        }
    } else
        return null;

    props.put("device_state_avail", new Boolean(isStateChangable));
    props.put("device_state", new Integer(state));
    props.put("availability", new Integer(availability));
    props.put("device_status", new Integer(status));

    if (thermostatServer != null) {
        availability = ((IServiceCluster) thermostatServer).getEndPoint().isAvailable() ? 2 : 0;
        if (availability == 2) {
            float localTemperature = (float) (thermostatServer.getLocalTemperature(maxAgeContext) / 100.0);

            String value = localTemperature + " &degC";
            attributeValue = new AttributeValueExtended("LocalTemperature", new AttributeValue(value));
            if (humidityServer != null) {
                float humididy = (float) (humidityServer.getMeasuredValue(maxAgeContext) / 100.0);
                value += " " + humididy + "%";
            }
        }
    } else if (simpleMeteringServer != null) {
        if (!useReportingOnSimpleMetering) {
            double power;
            try {
                power = this.readPower(peerAppliance);
                if (power != ESPService.INVALID_INSTANTANEOUS_POWER_VALUE)
                    attributeValue = new AttributeValueExtended("IstantaneousDemands",
                            new AttributeValue(power));

            } catch (Exception e) {
                power = 0;
            }

        } else {
            Double istantaneousDemand = (Double) istantaneousDemands.get(peerAppliance.getPid());

            if (istantaneousDemand != null) {
                attributeValue = new AttributeValueExtended("IstantaneousDemands",
                        new AttributeValue(istantaneousDemand.doubleValue()));
            } else if (this.fakeMode) {
                attributeValue = new AttributeValueExtended("IstantaneousDemands", new AttributeValue(123.1));
            }
        }
    }

    if (attributeValue != null)
        props.put("device_value", attributeValue);
    return props;
}

From source file:org.sparkbit.jsonrpc.SparkBitJSONRPCServiceImpl.java

private synchronized String sendassetusing_impl(String walletID, String txid, Long vout, String address,
        String assetRef, Double quantity, Boolean senderPays, String message, Double btcAmount)
        throws com.bitmechanic.barrister.RpcException {
    String sendTxHash = null;/*from w  w w. j av a2  s. c om*/
    boolean sendValidated = false;
    boolean sendSuccessful = false;

    Wallet w = getWalletForWalletName(walletID);
    if (w == null) {
        JSONRPCError.WALLET_NOT_FOUND.raiseRpcException();
    }

    // Check send with txid and vout
    Sha256Hash sendWithTxidHash = null;
    boolean canSpendSendWithTxOut = false;
    if (txid != null) {
        try {
            sendWithTxidHash = new Sha256Hash(txid);
        } catch (IllegalArgumentException e) {
            // Not a valid tx hash string
            JSONRPCError.INVALID_TXID_HASH.raiseRpcException();
        }
        canSpendSendWithTxOut = isTxOutSpendable(w, sendWithTxidHash, vout.intValue());
    }

    if (quantity <= 0.0) {
        JSONRPCError.SEND_ASSET_AMOUNT_TOO_LOW.raiseRpcException();
    }

    // BTC send amount, if null, use default amount of 10,000 satoshis.
    String sendAmount;
    if (btcAmount == null) {
        sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);
    } else {
        double d = btcAmount.doubleValue();
        if (d <= 0.0) {
            JSONRPCError.SEND_BITCOIN_AMOUNT_TOO_LOW.raiseRpcException();
        }
        sendAmount = btcAmount.toString();
    }
    BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

    // Is the BTC amount more than what is in the wallet?
    BigInteger totalSpend = bitcoinAmountSatoshis.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
    BigInteger availableBalance = w.getBalance(Wallet.BalanceType.AVAILABLE);
    if (totalSpend.compareTo(availableBalance) > 0) {
        JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException();
    }

    // Does the BTC amount respect the migration fees of any assets?
    boolean migrationSafe = CSMiscUtils.canSafelySpendWhileRespectingMigrationFee(this.controller, w,
            bitcoinAmountSatoshis);
    if (!migrationSafe) {
        BigInteger migrationFee = CSMiscUtils.calcMigrationFeeSatoshis(controller, w);
        JSONRPCError.SEND_INSUFFICIENT_MONEY_MIGRATION.raiseRpcException(
                "Need to keep at least " + Utils.bitcoinValueToFriendlyString(migrationFee) + " BTC.");
    }

    CoinSparkPaymentRef paymentRef = null;
    String bitcoinAddress = address;
    if (!address.startsWith("s")) {
        JSONRPCError.ADDRESS_NOT_COINSPARK_ADDRESS.raiseRpcException();
    } else {
        bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address);
        if (bitcoinAddress == null) {
            JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException();
        }

        CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(address);
        if (!CSMiscUtils.canSendAssetsToCoinSparkAddress(csa)) {
            JSONRPCError.COINSPARK_ADDRESS_MISSING_ASSET_FLAG.raiseRpcException();
        }

        if (message != null && !CSMiscUtils.canSendTextMessageToCoinSparkAddress(csa)) {
            JSONRPCError.COINSPARK_ADDRESS_MISSING_TEXT_MESSAGE_FLAG.raiseRpcException();
        }

        // payment ref?
        int flags = csa.getAddressFlags();
        if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
            paymentRef = csa.getPaymentRef();
            //      log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString());
        }
    }
    boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller);
    if (!isValid) {
        JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException();
    }

    String filename = getFullPathForWalletName(walletID);
    final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename);
    if (wd.isBusy()) {
        JSONRPCError.WALLEY_IS_BUSY.raiseRpcException();
    } else {
        wd.setBusy(true);
        wd.setBusyTaskKey("jsonrpc.busy.sendasset");
        this.controller.fireWalletBusyChange(true);
    }

    Transaction sendTransaction = null;

    try {
        // -- boilerplate ends here....

        CSAsset asset = getAssetForAssetRefString(w, assetRef);
        if (asset == null) {
            if (isAssetRefValid(assetRef)) {
                JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException();
            } else {
                JSONRPCError.ASSETREF_INVALID.raiseRpcException();
            }
        }

        if (asset.getAssetState() != CSAsset.CSAssetState.VALID) {
            if (!CSMiscUtils.canSendInvalidAsset(controller)) {
                JSONRPCError.ASSET_STATE_INVALID.raiseRpcException();
            }
        }

        // Check number of confirms
        int lastHeight = w.getLastBlockSeenHeight();
        CoinSparkAssetRef assetReference = asset.getAssetReference();
        if (assetReference != null) {
            final int blockIndex = (int) assetReference.getBlockNum();
            final int numConfirmations = lastHeight - blockIndex + 1; // 0 means no confirmation, 1 is yes for sa
            int threshold = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD;
            // FIXME: REMOVE/COMMENT OUT BEFORE RELEASE?
            String sendAssetWithJustOneConfirmation = controller.getModel()
                    .getUserPreference("sendAssetWithJustOneConfirmation");
            if (Boolean.TRUE.toString().equals(sendAssetWithJustOneConfirmation)) {
                threshold = 1;
            }
            //System.out.println(">>>> " + CSMiscUtils.getHumanReadableAssetRef(asset) + " num confirmations " + numConfirmations + ", threshold = " + threshold);
            if (numConfirmations < threshold) {
                JSONRPCError.ASSET_NOT_CONFIRMED.raiseRpcException();
            }
        }

        String displayQtyString = new BigDecimal(quantity).toPlainString();
        BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, displayQtyString);
        int assetID = asset.getAssetID();
        BigInteger spendableAmount = w.CS.getAssetBalance(assetID).spendable;

        log.info("Want to send: " + assetAmountRawUnits + " , AssetID=" + assetID + ", total="
                + w.CS.getAssetBalance(assetID).total + ", spendable="
                + w.CS.getAssetBalance(assetID).spendable);

        //       String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT);       
        CoinSparkGenesis genesis = asset.getGenesis();

        long desiredRawUnits = assetAmountRawUnits.longValue();
        short chargeBasisPoints = genesis.getChargeBasisPoints();
        long rawFlatChargeAmount = genesis.getChargeFlat();
        boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0);
        if (chargeExists) {
            if (senderPays) {
                long x = genesis.calcGross(desiredRawUnits);
                assetAmountRawUnits = new BigInteger(String.valueOf(x));
            } else {
                // We don't have to do anything if recipient pays, just send gross amount.
                // calcNet() returns what the recipient will receive, but it's not what we send. 
            }
        }

        if (assetAmountRawUnits.compareTo(spendableAmount) > 0) {
            JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
        }

        // Create a SendRequest.
        Address sendAddressObject;
        String sendAddress = bitcoinAddress;
        sendAddressObject = new Address(controller.getModel().getNetworkParameters(), sendAddress);
        //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));

        //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) {
        //BigInteger assetAmountRawUnits = new BigInteger(assetAmount);
        //      BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount);

        Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, bitcoinAmountSatoshis,
                assetID, assetAmountRawUnits, 1);
        sendRequest.ensureMinRequiredFee = true;
        sendRequest.fee = BigInteger.ZERO;
        sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

        // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

        // Send with txout vout
        if (canSpendSendWithTxOut) {
            boolean addedInput = sendRequest.addInput(w,
                    new CSTransactionOutput(sendWithTxidHash, vout.intValue()));
            if (!addedInput) {
                // Failed to add input, so throw exception
                JSONRPCError.SEND_WITH_TXID_VOUT_FAILED.raiseRpcException();
            }
        }

        // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
        if (paymentRef != null && paymentRef.getRef() != 0) {
            sendRequest.setPaymentRef(paymentRef);
        }

        // Set up message if one exists
        boolean isEmptyMessage = false;
        if (message == null || message.trim().isEmpty()) {
            isEmptyMessage = true;
        }
        if (!isEmptyMessage) {
            CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(message) };
            String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(this.controller);
            sendRequest.setMessage(parts, serverURLs);
        }

        // Complete it (which works out the fee) but do not sign it yet.
        log.info("Just about to complete the tx (and calculate the fee)...");

        // there is enough money, so let's do it for real now
        w.completeTx(sendRequest, false);
        sendValidated = true;
        log.info("The fee after completing the transaction was " + sendRequest.fee);
        // Let's do it for real now.

        sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null);
        if (sendTransaction == null) {
            // a null transaction returned indicates there was not
            // enough money (in spite of our validation)
            JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
        } else {
            sendSuccessful = true;
            sendTxHash = sendTransaction.getHashAsString();
        }

        if (sendSuccessful) {
            // There is enough money.

            /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */
            if (address.startsWith("s")) {
                SparkBitMapDB.INSTANCE.putSendCoinSparkAddressForTxid(sendTxHash, address);
            }
        } else {
            // There is not enough money
        }

        //--- bolilerplate begins...
    } catch (InsufficientMoneyException ime) {
        JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException();
    } catch (com.bitmechanic.barrister.RpcException e) {
        throw (e);
    } catch (CSExceptions.CannotEncode e) {
        JSONRPCError.SEND_MESSAGE_CANNOT_ENCODE.raiseRpcException(e.getMessage());
    } catch (Exception e) {
        JSONRPCError.throwAsRpcException("Could not send asset due to error: ", e);
    } finally {
        // Save the wallet.
        try {
            this.controller.getFileHandler().savePerWalletModelData(wd, false);
        } catch (WalletSaveException e) {
            //        log.error(e.getMessage(), e);
        }

        if (sendSuccessful) {
            // This returns immediately if rpcsendassettimeout is 0.
            JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction);
            //      JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash);
        }

        // Declare that wallet is no longer busy with the task.
        wd.setBusyTaskKey(null);
        wd.setBusy(false);
        this.controller.fireWalletBusyChange(false);
    }

    if (sendSuccessful) {
        controller.fireRecreateAllViews(false);
    }
    return sendTxHash;
}

From source file:org.sakaiproject.gradebook.gwt.server.ImportExportUtilityImpl.java

private boolean handleSpecialPointsCaseForItem(Item item, double d, ImportExportInformation ieInfo) {

    boolean isFailure = false;

    if (item != null) {

        Double points = item.getPoints();

        if (points != null) {

            if (points.doubleValue() < d) {

                // GRBK-629 : We don't auto adjust total points for GradeItems that
                // are created new via the import process depending on entered user grades

                // If a grade is higher than total points possible, we flag an error
                isFailure = true;//from  www  . j ava2  s. c om
                ieInfo.setInvalidScore(true);
            }
        }
    }
    return isFailure;
}

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

/**
 * Export the assignments to actual work
 * /*from w w w .  j av a2 s  .co  m*/
 * @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.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java

@Override
public PointsPossibleValidation isPointsPossibleValid(String gradebookUid,
        org.sakaiproject.service.gradebook.shared.Assignment gradebookItem, Double pointsPossible) {
    if (gradebookUid == null) {
        throw new IllegalArgumentException("Null gradebookUid passed to isPointsPossibleValid");
    }//from w w  w .  j  a va  2 s .c  o m
    if (gradebookItem == null) {
        throw new IllegalArgumentException("Null gradebookItem passed to isPointsPossibleValid");
    }

    // At this time, all gradebook items follow the same business rules for
    // points possible (aka relative weight in % gradebooks) so special logic 
    // using the properties of the gradebook item is unnecessary. 
    // In the future, we will have the flexibility to change
    // that behavior without changing the method signature

    // the points possible must be a non-null value greater than 0 with
    // no more than 2 decimal places

    if (pointsPossible == null) {
        return PointsPossibleValidation.INVALID_NULL_VALUE;
    }

    if (pointsPossible.doubleValue() <= 0) {
        return PointsPossibleValidation.INVALID_NUMERIC_VALUE;
    }
    // ensure there are no more than 2 decimal places
    BigDecimal bd = new BigDecimal(pointsPossible.doubleValue());
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); // Two decimal places
    double roundedVal = bd.doubleValue();
    double diff = pointsPossible - roundedVal;
    if (diff != 0) {
        return PointsPossibleValidation.INVALID_DECIMAL;
    }

    return PointsPossibleValidation.VALID;
}

From source file:com.kodemore.utility.Kmu.java

/**
 * Safely add two Doubles. The result is always a non-null Double.
 *///from ww  w. ja  v  a 2  s .  c  o  m
public static Double add(Double a, Double b) {
    if (a == null && b == null)
        return 0.0;

    if (a == null)
        return b;

    if (b == null)
        return a;

    return a.doubleValue() + b.doubleValue();
}

From source file:com.lp.server.auftrag.ejbfac.AuftragFacBean.java

/**
 * Hier wird der Auftragsnettowert fuer eine Hibernate Liste von
 * eingegangenen Auftraegen bestimmt (Status Offen, Teilerledigt, Erledigt). <br>
 * Dabei werden alle Auftragswerte in Mandantenwaehrung beruecksichtigt.
 * //ww w .  jav a 2  s .c o m
 * @param listFLRAuftragFuerUebersichtI
 *            Liste von FLRAuftragFuerUebersicht Objekten
 * @param theClientDto
 *            der aktuelle Benutzer
 * @return BigDecimal der offene Auftragsnettowert
 * @throws Throwable
 *             Ausnahme
 */
private BigDecimal berechneAuftragsnettowertEingang(List<?> listFLRAuftragFuerUebersichtI,
        TheClientDto theClientDto) throws Throwable {
    BigDecimal nSummeAuftragsnettowert = new BigDecimal(0);

    if (listFLRAuftragFuerUebersichtI != null) {
        Iterator<?> it = listFLRAuftragFuerUebersichtI.iterator();

        while (it.hasNext()) {
            FLRAuftragFuerUebersicht flrauftrag = (FLRAuftragFuerUebersicht) it.next();

            // der Gesamtwert wurde bei der Aktivierung in Auftragswaehrung
            // hinterlegt
            BigDecimal nBeitragDiesesAuftrags = flrauftrag.getN_gesamtauftragswertinauftragswaehrung();

            // Umrechnen des Beitrags in Mandantenwaehrung
            Double ddWechselkursReziprok = flrauftrag.getF_wechselkursmandantwaehrungzuauftragswaehrung();

            if (ddWechselkursReziprok != null && ddWechselkursReziprok.doubleValue() != 1) {
                ddWechselkursReziprok = new Double(1 / ddWechselkursReziprok.doubleValue());

                nBeitragDiesesAuftrags = nBeitragDiesesAuftrags
                        .multiply(new BigDecimal(ddWechselkursReziprok.doubleValue()));
            }

            nBeitragDiesesAuftrags = Helper.rundeKaufmaennisch(nBeitragDiesesAuftrags, 4);
            checkNumberFormat(nBeitragDiesesAuftrags);

            nSummeAuftragsnettowert = nSummeAuftragsnettowert.add(nBeitragDiesesAuftrags);
        }
    }

    return nSummeAuftragsnettowert;
}