Example usage for java.math RoundingMode HALF_EVEN

List of usage examples for java.math RoundingMode HALF_EVEN

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_EVEN.

Prototype

RoundingMode HALF_EVEN

To view the source code for java.math RoundingMode HALF_EVEN.

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line convertToSAFTWorkDocumentLine(
        InvoiceEntry entry, Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    oecd.standardauditfile_tax.pt_1.Product currentProduct = null;

    Product product = entry.getProduct();

    if (product.getCode() != null && baseProducts.containsKey(product.getCode())) {
        currentProduct = baseProducts.get(product.getCode());
    } else {//  w  w  w.j  a va 2 s  .  c  o m
        currentProduct = convertProductToSAFTProduct(product);
        baseProducts.put(currentProduct.getProductCode(), currentProduct);
    }
    XMLGregorianCalendar documentDateCalendar = null;
    try {
        DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = entry.getFinantialDocument().getDocumentDate();
        documentDateCalendar = convertToXMLDateTime(dataTypeFactory, documentDate);
    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = new oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line();

    if (entry.isCreditNoteEntry()) {
        line.setCreditAmount(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));
    } else if (entry.isDebitNoteEntry()) {
        line.setDebitAmount(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));
    }

    // Description
    line.setDescription(entry.getDescription());
    List<OrderReferences> orderReferences = line.getOrderReferences();

    //Add the references on the document creditEntries <-> debitEntries
    if (entry.isCreditNoteEntry()) {
        CreditEntry creditEntry = (CreditEntry) entry;
        if (creditEntry.getDebitEntry() != null) {
            OrderReferences reference = new OrderReferences();
            reference
                    .setOriginatingON(creditEntry.getDebitEntry().getFinantialDocument().getUiDocumentNumber());
            reference.setOrderDate(documentDateCalendar);
            orderReferences.add(reference);
        }

    } else if (entry.isDebitNoteEntry()) {
        //            DebitEntry debitEntry = (DebitEntry) entry;
        //            for (CreditEntry creditEntry : debitEntry.getCreditEntriesSet()) {
        //                OrderReferences reference = new OrderReferences();
        //                reference.setOriginatingON(creditEntry.getFinantialDocument().getUiDocumentNumber());
        //                reference.setOrderDate(documentDateCalendar);
        //                orderReferences.add(reference);
        //            }
    }

    // ProductCode
    line.setProductCode(currentProduct.getProductCode());

    // ProductDescription
    line.setProductDescription(currentProduct.getProductDescription());

    // Quantity
    line.setQuantity(entry.getQuantity());

    // SettlementAmount
    line.setSettlementAmount(BigDecimal.ZERO);

    // Tax
    line.setTax(getSAFTWorkingDocumentsTax(product, entry.getVat()));

    line.setTaxPointDate(documentDateCalendar);

    // TaxExemptionReason
    /*
     * Motivo da isen??o de imposto (TaxExemptionReason). Campo de
     * preenchimento obrigat?rio, quando os campos percentagem da taxa de
     * imposto (TaxPercentage) ou montante do imposto (TaxAmount) s?o iguais
     * a zero. Deve ser referido o preceito legal aplic?vel. . . . . . . . .
     * . Texto 60
     */
    if (line.getTax().getTaxPercentage() == BigDecimal.ZERO) {
        Vat vat = entry.getVat();

        if (vat.getVatExemptionReason() != null) {
            line.setTaxExemptionReason(
                    vat.getVatExemptionReason().getCode() + "-" + vat.getVatExemptionReason().getName());
        } else {
            // HACK : DEFAULT
            // line.setTaxExemptionReason(VatExemptionReason.M1().getCode()
            // + "-" + VatExemptionReason.M1().getDescription());
        }
    }

    // UnitOfMeasure
    line.setUnitOfMeasure(product.getUnitOfMeasure().getContent());
    // UnitPrice
    line.setUnitPrice(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));

    return line;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.scholarship.utl.report.StudentLine.java

public Boolean getStudentHadPerformanceLastYear() {
    BigDecimal numberOfApprovedEctsOneYearAgo = getNumberOfApprovedEctsOneYearAgo();
    BigDecimal numberOfEnrolledEctsOneYearAgo = getNumberOfEnrolledEctsOneYearAgo();

    if (numberOfEnrolledEctsOneYearAgo.compareTo(BigDecimal.ZERO) == 0) {
        return false;
    }//from w  w w. j a  v a  2  s  .  c  o m

    BigDecimal average = numberOfApprovedEctsOneYearAgo.divide(numberOfEnrolledEctsOneYearAgo,
            RoundingMode.HALF_EVEN);
    average.setScale(2);

    return average.compareTo(new BigDecimal(0.5f)) >= 0;
}

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

public void postUpdateFunction(int x, int y, byte[] dataValue) {
    int startDatapoint = (48 * x) + (y * 3) + 1;
    int Id = proservData.getFunctionMapId(x, y, 0);
    int IdPreset = proservData.getFunctionMapId(x, y, 1);

    proservData.setFunctionDataPoint(startDatapoint, x, y, 0);
    switch ((int) proservData.getFunctionCodes(x, y) & 0xFF) {
    case 0x01:/* w  w w .  j  a v  a2  s . c  o m*/
    case 0x02:
    case 0x04:
    case 0x05: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x11:
    case 0x12:
    case 0x13: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        if (proservData.getFunctionStateIsInverted(x, y))
            b = !b;
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x21:
    case 0x31: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        if (proservData.getFunctionStateIsInverted(x, y))
            b = !b;
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x26:
    case 0x34: {
        float f = proservData.parse2ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    case 0x38: {
        float f = proservData.parse4ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    case 0x32:
    case 0x91: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            int i = proservData.parse1BytePercentValue(dataValue[0]);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            int preset = proservData.parse1BytePercentValue(dataValue[2]);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset), new DecimalType(preset));
        }
    }
        break;
    case 0x33:
    case 0x92: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            int preset = proservData.parse1ByteUnsignedValue(dataValue[2]);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset), new DecimalType(preset));
        }
    }
        break;
    case 0x94: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            float f = proservData.parse2ByteFloatValue(dataValue, 0);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                    new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            float f = proservData.parse2ByteFloatValue(dataValue, 4);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
                    new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
        }
    }
        break;
    case 0x35:
    case 0x95: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            long uint32 = proservData.parse4ByteUnsignedValue(dataValue, 0);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            long uint32Preset = proservData.parse4ByteUnsignedValue(dataValue, 8);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
                    new DecimalType(uint32Preset));
        }
    }
        break;
    case 0x36:
    case 0x96: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            long int32 = proservData.parse4ByteSignedValue(dataValue, 0);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            long int32Preset = proservData.parse4ByteSignedValue(dataValue, 8);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
                    new DecimalType(int32Preset));
        }
    }
        break;
    case 0x97: {
        if (proservData.getFunctionLogThis(x, y, 0)) {
            float f = proservData.parse4ByteFloatValue(dataValue, 0);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                    new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
        }
        if (proservData.getFunctionLogThis(x, y, 1)) {
            shortDelayBetweenBusEvents();
            proservData.setFunctionDataPoint(startDatapoint + 2, x, y, 1);
            float f = proservData.parse4ByteFloatValue(dataValue, 8);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
                    new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
        }
    }
        break;
    default:
        logger.debug("proServ binding, unhandled functioncode 0x{}",
                Integer.toHexString(((int) proservData.getFunctionCodes(x, y) & 0xFF)));
    }
    shortDelayBetweenBusEvents();
}

From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java

@Override
public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues);

    try {//w  w  w .  ja v a 2s  . c o  m
        AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount(
                new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId()))
                        .getParentAccount();
        BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount();
        BigDecimal membersAmount = BigDecimal.ZERO;

        for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) {
            LoanBO individual = loanDao.findById(entry.getKey());
            Double chargeAmount = Double.valueOf(entry.getValue());
            if (chargeAmount.equals(0.0)) {
                continue;
            }
            membersAmount = membersAmount.add(individual.getLoanAmount().getAmount());
            individual.updateDetails(userContext);

            if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount));
            } else {
                individual.applyCharge(chargeId, chargeAmount);
            }
        }

        boolean isRateCharge = false;

        if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES))
                && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {

            if (isPenaltyType) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                if (penalty instanceof RatePenaltyBO) {
                    isRateCharge = true;
                }
            } else {
                FeeBO fee = feeDao.findById(chargeId);
                if (fee.getFeeType().equals(RateAmountFlag.RATE)) {
                    isRateCharge = true;
                }
            }
        }

        Double chargeAmount = null;

        if (!isRateCharge) {
            chargeAmount = sumCharge(idsAndValues);
        } else {
            chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue());
            BigDecimal chargeAmountBig = new BigDecimal(chargeAmount);
            membersAmount = membersAmount.multiply(chargeAmountBig);
            int scale = Money.getInternalPrecision();
            chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN);
            chargeAmount = chargeAmountBig.doubleValue();
        }

        parentAccount.updateDetails(userContext);

        CustomerLevel customerLevel = null;
        if (parentAccount.isCustomerAccount()) {
            customerLevel = parentAccount.getCustomer().getLevel();
        }
        if (parentAccount.getPersonnel() != null) {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), userContext.getId());
        }

        this.transactionHelper.startTransaction();

        if (isPenaltyType && parentAccount instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) parentAccount)
                    .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount));
        } else {
            parentAccount.applyCharge(chargeId, chargeAmount);
        }

        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }

}

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

public void postUpdateSingleValueHeating(int x, int z, byte[] dataValue) {
    int Id = proservData.getHeatingMapId(x, z);
    int startDatapoint = 865 + x * 5;
    switch ((int) (proservData.getHeatingCodes(x) & 0xFF)) {
    case 0x41:/* w w  w  .j  av a 2 s  .  co  m*/
    case 0x42:
    case 0x43:
    case 0x44:
        float f = proservData.parse2ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
        break;
    default:
        logger.debug("proServ binding, unhandled heatingCode {}",
                Integer.toHexString(((int) proservData.getHeatingCodes(x) & 0xFF)));
    }
}

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

public void postUpdateHeating(int x, byte[] dataValue) {
    int IdActual = proservData.getHeatingMapId(x, 0);
    int IdPreset = proservData.getHeatingMapId(x, 1);

    int startDatapoint = 865 + x * 5;

    switch ((int) (proservData.getHeatingCodes(x) & 0xFF)) {
    case 0x41:/*w w  w .  ja va 2 s .  co m*/
    case 0x42:
    case 0x43:
    case 0x44:
        proservData.setHeatingDataPoint(startDatapoint, x, 0);
        float f0 = proservData.parse2ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdActual),
                new DecimalType(new BigDecimal(f0).setScale(2, RoundingMode.HALF_EVEN)));
        proservData.setHeatingDataPoint(startDatapoint + 2, x, 1);
        float f1 = proservData.parse2ByteFloatValue(dataValue, 4);
        shortDelayBetweenBusEvents();
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
                new DecimalType(new BigDecimal(f1).setScale(2, RoundingMode.HALF_EVEN)));
        /*
        logger.info("{}{}: {}{}: {}", padRight(proservData.getHeatingDescription(x), 20), 
              padRight(proservData.getStringProservLang(0), 5), padRight(Float.toString(f0), 10), 
              padRight(proservData.getStringProservLang(1), 5), padRight(Float.toString(f1), 10));
              */
        break;
    default:
        logger.debug("proServ binding, unhandled heatingCode {}",
                Integer.toHexString(((int) proservData.getHeatingCodes(x) & 0xFF)));
    }
}

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

public void postUpdateWeather(byte[] dataValue, int i) {
    int Id = proservData.getWeatherStationMapId(i);
    if (Id != 0) {
        if (i >= 0 && i <= 4) {
            float f0 = proservData.parse2ByteFloatValue(dataValue, 0);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                    new DecimalType(new BigDecimal(f0).setScale(2, RoundingMode.HALF_EVEN)));
        } else if (i == 5) {
            boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
            eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                    b ? OnOffType.ON : OnOffType.OFF);
        }//w ww  .  j av  a  2 s  .  c o m
    }
}

From source file:org.openhab.binding.sapp.internal.SappBinding.java

/**
 * updates item repository for a single item
 *///from w  ww  .j  a v  a 2  s .c  om
private void updateState(String pnmasId, SappAddressType sappAddressType, int addressToUpdate, int newState,
        SappBindingProvider provider) {
    logger.debug("Updating {} {} with new value {}", sappAddressType, addressToUpdate, newState);
    for (String itemName : provider.getItemNames()) {
        try {
            Item item = itemRegistry.getItem(itemName);

            if (item instanceof SwitchItem && !(item instanceof DimmerItem)) {
                SappBindingConfigSwitchItem sappBindingConfigSwitchItem = (SappBindingConfigSwitchItem) provider
                        .getBindingConfig(itemName);
                if (!sappBindingConfigSwitchItem.isPollerSuspender()) {
                    SappAddressOnOffStatus statusAddress = sappBindingConfigSwitchItem.getStatus();
                    if (statusAddress.getAddressType() == sappAddressType
                            && statusAddress.getPnmasId().equals(pnmasId)
                            && addressToUpdate == statusAddress.getAddress()) {
                        logger.debug("found binding to update {}", sappBindingConfigSwitchItem);
                        int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(),
                                newState);
                        eventPublisher.postUpdate(itemName,
                                result == statusAddress.getOnValue() ? OnOffType.ON : OnOffType.OFF);
                    }
                }
            } else if (item instanceof ContactItem) {
                SappBindingConfigContactItem sappBindingConfigContactItem = (SappBindingConfigContactItem) provider
                        .getBindingConfig(itemName);
                SappAddressOpenClosedStatus statusAddress = sappBindingConfigContactItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType
                        && statusAddress.getPnmasId().equals(pnmasId)
                        && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigContactItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(),
                            newState);
                    eventPublisher.postUpdate(itemName,
                            result == statusAddress.getOpenValue() ? OpenClosedType.OPEN
                                    : OpenClosedType.CLOSED);
                }
            } else if (item instanceof NumberItem) {
                SappBindingConfigNumberItem sappBindingConfigNumberItem = (SappBindingConfigNumberItem) provider
                        .getBindingConfig(itemName);
                SappAddressDecimal address = sappBindingConfigNumberItem.getStatus();
                if (address.getAddressType() == sappAddressType && address.getPnmasId().equals(pnmasId)
                        && addressToUpdate == address.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigNumberItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(address.getSubAddress(), newState);
                    eventPublisher.postUpdate(itemName,
                            new DecimalType(address.scaledValue(result, address.getSubAddress())));
                }
            } else if (item instanceof RollershutterItem) {
                SappBindingConfigRollershutterItem sappBindingConfigRollershutterItem = (SappBindingConfigRollershutterItem) provider
                        .getBindingConfig(itemName);
                SappAddressRollershutterStatus statusAddress = sappBindingConfigRollershutterItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType
                        && statusAddress.getPnmasId().equals(pnmasId)
                        && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigRollershutterItem);
                    int result = SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(),
                            newState);
                    eventPublisher.postUpdate(itemName,
                            result == statusAddress.getOpenValue() ? PercentType.HUNDRED
                                    : (result == statusAddress.getClosedValue() ? PercentType.ZERO
                                            : PercentType.valueOf("50")));
                }
            } else if (item instanceof DimmerItem) {
                SappBindingConfigDimmerItem sappBindingConfigDimmerItem = (SappBindingConfigDimmerItem) provider
                        .getBindingConfig(itemName);
                SappAddressDimmer statusAddress = sappBindingConfigDimmerItem.getStatus();
                if (statusAddress.getAddressType() == sappAddressType
                        && statusAddress.getPnmasId().equals(pnmasId)
                        && addressToUpdate == statusAddress.getAddress()) {
                    logger.debug("found binding to update {}", sappBindingConfigDimmerItem);
                    int result = statusAddress
                            .scaledValue(SappBindingConfigUtils.maskWithSubAddress(
                                    statusAddress.getSubAddress(), newState), statusAddress.getSubAddress())
                            .round(new MathContext(0, RoundingMode.HALF_EVEN)).intValue();
                    if (result <= PercentType.ZERO.intValue()) {
                        eventPublisher.postUpdate(itemName, PercentType.ZERO);
                    } else if (result >= PercentType.HUNDRED.intValue()) {
                        eventPublisher.postUpdate(itemName, PercentType.HUNDRED);
                    } else {
                        eventPublisher.postUpdate(itemName, PercentType.valueOf(String.valueOf(result)));
                    }
                }
            } else {
                logger.error("unimplemented item type: {}", item.getClass().getSimpleName());
            }
        } catch (ItemNotFoundException e) {
            logger.error("Item {} not found", itemName);
        }
    }
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@link java.math.BigDecimal#setScale(int, RoundingMode)}
 *
 * @param o the object. number or String.
 * @param scale scale of the BigDecimal value to be returned.
 * @param roundingMode the rounding mode to apply.
 * @param type number type to be returned.
 * @return//from   ww w .  ja va 2  s . co m
 */
private static <T extends Number> T setScale(final Object o, final Number scale,
        final RoundingMode roundingMode, final Class<T> type) {
    if (isNaN(o))
        return NumberObject.of(type == null ? getClass(valueOf(o)) : type).valueOf(valueOf(o));
    BigDecimal n = valueOf(o, BigDecimal.class);

    return NumberObject.of(type == null ? getClass(valueOf(o)) : type)
            .valueOf(n == null ? null
                    : n.setScale(valueOf(scale, int.class),
                            roundingMode == null ? RoundingMode.HALF_EVEN : roundingMode));
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param empcntClientProjectDataList//from   www .  j a v  a 2 s .  com
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 * @return
 */

private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getMultipleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    // For all invalid projects calculate count zero
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());

    // If List is empty
    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects (: Find by Revenue)===>");

        Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>();
        BigDecimal sumOfRevenue = BigDecimal.ZERO;

        List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId(
                costCentre.getCostCentreId(), year.getYearId(), month.getMonthId());

        for (Object[] collageProjectRevenue : collageProjectRevenueList) {
            Integer projectId = (Integer) collageProjectRevenue[0];
            BigDecimal revenue = (BigDecimal) collageProjectRevenue[1];
            projectRevenueMap.put(projectId, revenue);
        }
        // logger.debug("projectRevenueMap size===>" +
        // projectRevenueMap.size());

        for (Integer key : projectRevenueMap.keySet()) {
            sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key));
        }
        logger.debug("sumOfRevenue===>" + sumOfRevenue);

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            BigDecimal revenue = projectRevenueMap.get(projectId);
            logger.debug("revenue===>" + revenue);
            BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN);
            projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING);
            // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : "
            // + projectRevenueCount);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects
        Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }

        if (validEmployeeProjectCount == validAllProjectCount
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                BigDecimal timeByProject = assignedProjects.get(key);
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+
                // " : "+toatlTime);
                BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    // logger.debug("Project Id===>"+key);
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }
                // logger.debug("Aligned Hours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("Only in unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug(" unassigned projects Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("unassigned projects Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) {
                    BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                    getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                            employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                            countTypeId, employeePcTagsTeamStructMap);
                }
            }
        }

    }
    // logger.debug("<====getMultipleProjectDetail END====>");
}