Example usage for java.math MathContext MathContext

List of usage examples for java.math MathContext MathContext

Introduction

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

Prototype

public MathContext(int setPrecision, RoundingMode setRoundingMode) 

Source Link

Document

Constructs a new MathContext with a specified precision and rounding mode.

Usage

From source file:org.apache.fineract.portfolio.savings.service.DepositAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult adjustRDTransaction(final Long savingsId, final Long transactionId,
        final JsonCommand command) {

    AppUser user = getAppUserIfPresent();

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    this.depositAccountTransactionDataValidator.validate(command, DepositAccountType.RECURRING_DEPOSIT);

    final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository
            .findOneByIdAndSavingsAccountId(transactionId, savingsId);
    if (savingsAccountTransaction == null) {
        throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId);
    }//from  w w w. ja  v  a  2s  .  c o m

    if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal())
            || savingsAccountTransaction.isReversed()) {
        throw new TransactionUpdateNotAllowedException(savingsId, transactionId);
    }

    if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId,
            PortfolioAccountType.SAVINGS)) {
        throw new PlatformServiceUnavailableException(
                "error.msg.saving.account.transfer.transaction.update.not.allowed",
                "Deposit account transaction:" + transactionId
                        + " update not allowed as it involves in account transfer",
                transactionId);
    }

    final LocalDate today = DateUtils.getLocalDateOfTenant();

    final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler
            .assembleFrom(savingsId, DepositAccountType.RECURRING_DEPOSIT);
    if (account.isNotActive()) {
        throwValidationForActiveStatus(SavingsApiConstants.adjustTransactionAction);
    }
    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final LocalDate transactionDate = command
            .localDateValueOfParameterNamed(SavingsApiConstants.transactionDateParamName);
    final BigDecimal transactionAmount = command
            .bigDecimalValueOfParameterNamed(SavingsApiConstants.transactionAmountParamName);
    final Map<String, Object> changes = new LinkedHashMap<>();
    final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService
            .createAndPersistPaymentDetail(command, changes);

    final MathContext mc = new MathContext(10, MoneyHelper.getRoundingMode());
    account.undoTransaction(transactionId);

    SavingsAccountTransaction transaction = null;
    if (savingsAccountTransaction.isDeposit()) {
        final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt,
                transactionDate, transactionAmount, paymentDetail, savingsAccountTransaction.createdDate(),
                user);
        transaction = account.deposit(transactionDTO);
    } else {
        final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt,
                transactionDate, transactionAmount, paymentDetail, savingsAccountTransaction.createdDate(),
                user);
        transaction = account.withdraw(transactionDTO, true);
    }
    final Long newtransactionId = saveTransactionToGenerateTransactionId(transaction);
    boolean isInterestTransfer = false;
    if (account.isBeforeLastPostingPeriod(transactionDate)
            || account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) {
        account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
                financialYearBeginningMonth);
    } else {
        account.calculateInterestUsing(mc, today, isInterestTransfer,
                isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
    }
    List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions = null;
    if (account.getOnHoldFunds().compareTo(BigDecimal.ZERO) == 1) {
        depositAccountOnHoldTransactions = this.depositAccountOnHoldTransactionRepository
                .findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(account);
    }

    account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.adjustTransactionAction,
            depositAccountOnHoldTransactions);
    account.activateAccountBasedOnBalance();

    if (savingsAccountTransaction.isDeposit()) {
        account.handleScheduleInstallments(savingsAccountTransaction);
    }
    final LocalDate overdueUptoDate = DateUtils.getLocalDateOfTenant();
    account.updateOverduePayments(overdueUptoDate);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
    return new CommandProcessingResultBuilder() //
            .withEntityId(newtransactionId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .with(changes)//
            .build();
}

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

/**
 * updates item repository for a single item
 *///ww w .  j  a  v  a 2s.c  o  m
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:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

/**
 * main() method, for testing/*from w w w.j av  a2 s  .  co m*/
 * usage: java edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator testfile.tab varcount casecount column type
 * make sure the CLASSPATH contains ...
 * 
 */

public static void main(String[] args) {

    String tabFileName = args[0];
    int varcount = new Integer(args[1]).intValue();
    int casecount = new Integer(args[2]).intValue();
    int column = new Integer(args[3]).intValue();
    String type = args[4];

    File tabFile = new File(tabFileName);
    File rotatedImageFile = null;

    TabularSubsetGenerator subsetGenerator = new TabularSubsetGenerator();

    /*
    try {
    rotatedImageFile = subsetGenerator.getRotatedImage(tabFile, varcount, casecount);
    } catch (IOException ex) {
    System.out.println(ex.getMessage());
    }
    */

    //System.out.println("\nFinished generating \"rotated\" column image file."); 

    //System.out.println("\nOffsets:");

    MathContext doubleMathContext = new MathContext(15, RoundingMode.HALF_EVEN);
    String FORMAT_IEEE754 = "%+#.15e";

    try {
        //subsetGenerator.reverseRotatedImage(rotatedImageFile, varcount, casecount);
        //String[] columns = subsetGenerator.subsetStringVector(tabFile, column, varcount, casecount);
        if ("string".equals(type)) {
            String[] columns = subsetGenerator.subsetStringVector(tabFile, column, varcount, casecount);
            for (int i = 0; i < casecount; i++) {
                System.out.println(columns[i]);
            }
        } else {

            Double[] columns = subsetGenerator.subsetDoubleVector(tabFile, column, varcount, casecount);
            for (int i = 0; i < casecount; i++) {
                if (columns[i] != null) {
                    BigDecimal outBigDecimal = new BigDecimal(columns[i], doubleMathContext);
                    System.out.println(String.format(FORMAT_IEEE754, outBigDecimal));
                } else {
                    System.out.println("NA");
                }
                //System.out.println(columns[i]);
            }
        }
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

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

/**
 * updates item repository for Dimmer items
 *///from w w  w  . java  2  s. c  o m
private void updateDimmerItem(SappBindingProvider provider, SappAddressDimmer statusAddress, String itemName,
        Item item) {

    switch (statusAddress.getAddressType()) {
    case VIRTUAL:
        try {
            int result = statusAddress
                    .scaledValue(
                            SappBindingConfigUtils.maskWithSubAddress(statusAddress.getSubAddress(),
                                    getVirtualValue(provider, statusAddress.getPnmasId(),
                                            statusAddress.getAddress(), statusAddress.getSubAddress(), true)),
                            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)));
            }
        } catch (SappException e) {
            logger.error("could not run sappcommand", e);
        }
        break;

    case INPUT:
        logger.error("item type not yet implemented {} for address type {}", item.getClass().getSimpleName(),
                statusAddress.getAddressType());
        break;

    case OUTPUT:
        logger.error("item type not yet implemented {} for address type {}", item.getClass().getSimpleName(),
                statusAddress.getAddressType());
        break;

    default:
        logger.error("item type not yet implemented {} for address type {}", item.getClass().getSimpleName(),
                statusAddress.getAddressType());
        break;
    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private double base30Tobase10Conversion(String base30String) {

    // new base(radix) number
    int oldBase = 30;
    //dbgLog.fine("base30String="+base30String);

    // trim white-spaces from the both ends
    String base30StringClean = StringUtils.trim(base30String);
    //dbgLog.fine("base30StringClean="+base30StringClean);

    // check the negative/positive sign
    boolean isNegativeNumber = false;
    boolean hasPositiveSign = false;
    if (base30StringClean.startsWith("-")) {
        isNegativeNumber = true;//from   www  .j  a  v a  2s . c  o  m
    }

    if (base30StringClean.startsWith("+")) {
        hasPositiveSign = true;
    }

    // remove the sign if exits
    String base30StringNoSign = null;

    if ((isNegativeNumber) || (hasPositiveSign)) {
        base30StringNoSign = base30StringClean.substring(1);
    } else {
        base30StringNoSign = new String(base30StringClean);
    }

    // check the scientific notation
    // if so, divide it into the significand and exponent
    String significand = null;
    long exponent = 0;

    int plusIndex = base30StringNoSign.indexOf("+");
    int minusIndex = base30StringNoSign.indexOf("-");

    if (plusIndex > 0) {
        significand = base30StringNoSign.substring(0, plusIndex);
        exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase);

    } else if (minusIndex > 0) {
        significand = base30StringNoSign.substring(0, minusIndex);
        exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase);

    } else {
        significand = new String(base30StringNoSign);
    }

    // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal
    int decimalIndex = significand.indexOf(".");
    if (decimalIndex != -1) {
        exponent -= (significand.length() - (decimalIndex + 1));
        significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1);
    }

    MathContext mc = new MathContext(15, RoundingMode.HALF_UP);
    long base10Significand = Long.parseLong(significand, oldBase);
    BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc);
    BigDecimal exponentialComponent = new BigDecimal("1", mc);

    for (int g = 0; g < Math.abs(exponent); g++) {
        exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc));
    }

    if (exponent >= 0) {
        base10value = base10value.multiply(exponentialComponent, mc);
    } else {
        base10value = base10value.divide(exponentialComponent, mc);
    }

    // negative sign if applicable
    if (isNegativeNumber) {
        base10value = base10value.multiply(new BigDecimal("-1", mc));
    }

    return base10value.doubleValue();
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)/*from w  w  w  .  j a  v a  2 s. c  o m*/
public Map<String, Object> depreciacionAcumuladaPorCentroDeCosto(Map<String, Object> params) {
    Usuario usuario = (Usuario) params.get("usuario");
    Query tiposDeActivoQuery = currentSession().createQuery(
            "select new map(ta.nombre as nombre, ta.cuenta.id.idCtaMayor as cuenta, ta.id as id) from TipoActivo ta where ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId order by ta.cuenta.id.idCtaMayor");
    tiposDeActivoQuery.setString("ejercicioId", usuario.getEjercicio().getId().getIdEjercicio());
    tiposDeActivoQuery.setLong("organizacionId", usuario.getEjercicio().getId().getOrganizacion().getId());
    List<Map<String, Object>> tiposDeActivo = tiposDeActivoQuery.list();
    Map<String, Map<String, Object>> tiposDeActivoMap = new HashMap<>();
    for (Map<String, Object> tipoActivo : tiposDeActivo) {
        tipoActivo.put("total", BigDecimal.ZERO);
        tiposDeActivoMap.put((String) tipoActivo.get("cuenta"), tipoActivo);
    }
    Map<String, Object> totalCC = new HashMap<>();
    totalCC.put("nombre", "");
    totalCC.put("cuenta", "TOTAL");
    totalCC.put("id", 0);
    totalCC.put("total", BigDecimal.ZERO);
    tiposDeActivo.add(totalCC);
    tiposDeActivoMap.put("TOTAL", totalCC);
    params.put("tiposDeActivo", tiposDeActivo);

    Date fecha = (Date) params.get("fecha");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    Map<String, Map<String, Object>> mapa1 = new TreeMap<>();
    Query query = currentSession().createQuery(
            "select new Activo(a.id, a.version, a.moi, a.fechaCompra, a.tipoActivo.porciento, a.tipoActivo.vidaUtil, a.inactivo, a.fechaInactivo, a.fechaReubicado, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.centroCosto.nombre) from Activo a inner join a.tipoActivo where a.empresa.id = :empresaId and a.fechaCompra <= :fecha and a.fechaReubicado is null");
    query.setLong("empresaId", usuario.getEmpresa().getId());
    query.setDate("fecha", fecha);
    List<Activo> activos = query.list();
    for (Activo activo : activos) {
        log.trace("Depreciando activo {}", activo.getId());
        activo = this.deprecia(activo, fecha);

        this.depreciacionAcumuladaPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
    }

    // Busca activos reubicados
    query = currentSession().createQuery(
            "select new Activo(a.id, a.version, a.moi, a.fechaCompra, a.tipoActivo.porciento, a.tipoActivo.vidaUtil, a.inactivo, a.fechaInactivo, a.fechaReubicado, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.centroCosto.nombre) from Activo a inner join a.tipoActivo where a.empresa.id = :empresaId and a.fechaCompra <= :fecha and a.fechaReubicado != null");
    query.setLong("empresaId", usuario.getEmpresa().getId());
    query.setDate("fecha", fecha);
    activos = query.list();
    for (Activo activo : activos) {
        query = currentSession().createQuery(
                "select r from ReubicacionActivo r where r.activo.id = :activoId order by r.fecha");
        query.setLong("activoId", activo.getId());
        List<ReubicacionActivo> reubicaciones = query.list();
        Date fechaAnterior = null;
        boolean bandera1 = true;
        for (ReubicacionActivo reubicacion : reubicaciones) {
            if (reubicacion.getFecha().before(fecha)) {
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                this.deprecia(activo, reubicacion.getFecha());
                fechaAnterior = reubicacion.getFecha();
            } else {
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                this.deprecia(activo, fecha);
                bandera1 = false;
            }

            this.depreciacionAcumuladaPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
        }

        if (bandera1) {
            activo.setFechaCompra(activo.getFechaReubicado());
            this.deprecia(activo, fecha);
            this.depreciacionAcumuladaPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
        }
    }

    if (log.isTraceEnabled()) {
        for (Map<String, Object> centroCosto : mapa1.values()) {
            log.trace("CentroCosto: {} : {}", centroCosto.get("nombre"), centroCosto.get("totales"));
        }
    }

    params.put("centrosDeCosto", mapa1.values());
    return params;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private double base30Tobase10Conversion(String base30String) {

    // new base(radix) number
    int oldBase = 30;
    //dbgLog.fine("base30String="+base30String);

    // trim white-spaces from the both ends
    String base30StringClean = StringUtils.trim(base30String);
    //dbgLog.fine("base30StringClean="+base30StringClean);

    // check the negative/positive sign
    boolean isNegativeNumber = false;
    boolean hasPositiveSign = false;
    if (base30StringClean.startsWith("-")) {
        isNegativeNumber = true;/*from w w  w. j a  v a  2s  .  c  o m*/
    }

    if (base30StringClean.startsWith("+")) {
        hasPositiveSign = true;
    }

    // remove the sign if exits
    String base30StringNoSign = null;

    if ((isNegativeNumber) || (hasPositiveSign)) {
        base30StringNoSign = base30StringClean.substring(1);
    } else {
        base30StringNoSign = base30StringClean;
    }

    // check the scientific notation
    // if so, divide it into the significand and exponent
    String significand = null;
    long exponent = 0;

    int plusIndex = base30StringNoSign.indexOf("+");
    int minusIndex = base30StringNoSign.indexOf("-");

    if (plusIndex > 0) {
        significand = base30StringNoSign.substring(0, plusIndex);
        exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase);

    } else if (minusIndex > 0) {
        significand = base30StringNoSign.substring(0, minusIndex);
        exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase);

    } else {
        significand = base30StringNoSign;
    }

    // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal
    int decimalIndex = significand.indexOf(".");
    if (decimalIndex != -1) {
        exponent -= (significand.length() - (decimalIndex + 1));
        significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1);
    }

    // TODO: Verify that the MathContext/Rounding methods are OK:
    // -- L.A. 4.0 beta
    MathContext mc = new MathContext(15, RoundingMode.HALF_UP);
    long base10Significand = Long.parseLong(significand, oldBase);
    BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc);
    BigDecimal exponentialComponent = new BigDecimal("1", mc);

    for (int g = 0; g < Math.abs(exponent); g++) {
        exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc));
    }

    if (exponent >= 0) {
        base10value = base10value.multiply(exponentialComponent, mc);
    } else {
        base10value = base10value.divide(exponentialComponent, mc);
    }

    // negative sign if applicable
    if (isNegativeNumber) {
        base10value = base10value.multiply(new BigDecimal("-1", mc));
    }

    return base10value.doubleValue();
}

From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java

private ArrayList<HashMap<String, String>> calculateAccDefPlan(Period startingPeriod, int periodNumber,
        BigDecimal amount, String strCurrencyId) {
    Period period = startingPeriod;
    Date date = period.getEndingDate();
    ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>();
    int i = 1;/*from  w  w  w  .j a  v a  2s.  c o  m*/
    BigDecimal total = BigDecimal.ZERO;
    int stdPrecision = 0;
    OBContext.setAdminMode(true);
    try {
        stdPrecision = OBDal.getInstance().get(Currency.class, this.C_Currency_ID).getStandardPrecision()
                .intValue();
    } finally {
        OBContext.restorePreviousMode();
    }
    BigDecimal periodAmount = amount
            .divide(new BigDecimal(periodNumber), new MathContext(32, RoundingMode.HALF_UP))
            .setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);

    while (i <= periodNumber) {
        if (!OBDateUtils.formatDate(date).equals(DateAcct)) {
            HashMap<String, String> hm = new HashMap<String, String>();
            hm.put("date", OBDateUtils.formatDate(date));
            hm.put("amount", i == periodNumber ? amount.subtract(total).toString() : periodAmount.toString());
            plan.add(hm);
        }
        try {
            AcctServerData[] data = AcctServerData.periodOpen(connectionProvider, AD_Client_ID, DocumentType,
                    AD_Org_ID, OBDateUtils.formatDate(period.getEndingDate()));
            if ("".equals(data[0].period)) {
                setStatus(STATUS_PeriodClosed);
                throw new OBException("@PeriodNotAvailable@");
            }
        } catch (ServletException e) {
            log4j.warn("DocInvoice - Error checking period open.", e);
            e.printStackTrace();
        }
        if (i < periodNumber) {
            period = AccDefUtility.getNextPeriod(period);
            date = period.getEndingDate();
        }
        total = total.add(periodAmount);
        i++;
    }
    return plan;
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//  w  w  w . j  a  va2s .  co m
public Map<String, Object> depreciacionAcumuladaPorCentroDeCostoDetalle(Map<String, Object> params) {
    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    Map<String, BigDecimal> totales = new HashMap<>();
    totales.put("ACUMULADA", BigDecimal.ZERO);
    totales.put("MENSUAL", BigDecimal.ZERO);
    totales.put("ANUAL", BigDecimal.ZERO);
    totales.put("NETO", BigDecimal.ZERO);
    Usuario usuario = (Usuario) params.get("usuario");
    String centroCostoId = (String) params.get("centroCostoId");
    Date fecha = (Date) params.get("fecha");
    CCostoPK ccostoPK = new CCostoPK(usuario.getEjercicio(), centroCostoId);
    CentroCosto centroCosto = (CentroCosto) currentSession().get(CentroCosto.class, ccostoPK);
    params.put("centroCosto", centroCosto);
    Criteria criteria = currentSession().createCriteria(Activo.class);
    criteria.add(Restrictions.eq("empresa.id", usuario.getEmpresa().getId()));
    criteria.add(Restrictions.eq("centroCosto.id.ejercicio.id.idEjercicio",
            usuario.getEjercicio().getId().getIdEjercicio()));
    criteria.add(Restrictions.eq("centroCosto.id.ejercicio.id.organizacion.id",
            usuario.getEjercicio().getId().getOrganizacion().getId()));
    criteria.add(Restrictions.eq("centroCosto.id.idCosto", centroCostoId));
    criteria.add(Restrictions.le("fechaCompra", fecha));
    criteria.add(Restrictions.isNull("fechaReubicado"));
    List<Activo> activos = criteria.list();
    for (Activo activo : activos) {
        log.trace("Depreciando activo {}", activo.getId());
        activo = this.deprecia(activo, fecha);

        this.depreciacionAcumuladaPorCentroDeCostoDetalle(activo, mc, totales);
    }

    // busca reubicados
    Query query = currentSession().createQuery(
            "select a from ReubicacionActivo ra inner join ra.activo a where ra.empresa.id = :empresaId and (ra.centroCosto.id.idCosto = :centroCostoId or ra.centroCostoAnterior.id.idCosto = :centroCostoId) and a.fechaCompra < :fecha group by a");
    query.setLong("empresaId", usuario.getEmpresa().getId());
    query.setString("centroCostoId", centroCostoId);
    query.setDate("fecha", fecha);
    List<Activo> reubicados = query.list();
    for (Activo activo : reubicados) {
        log.trace("Depreciando reubicado {}", activo.getId());
        query = currentSession().createQuery(
                "select r from ReubicacionActivo r where r.activo.id = :activoId order by r.fecha");
        query.setLong("activoId", activo.getId());
        List<ReubicacionActivo> reubicaciones = query.list();
        Date fechaAnterior = null;
        boolean bandera1 = true;
        for (ReubicacionActivo reubicacion : reubicaciones) {
            boolean seDeprecio = false;
            if (reubicacion.getFecha().before(fecha)
                    && reubicacion.getCentroCostoAnterior().getId().getIdCosto().equals(centroCostoId)) {
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                this.deprecia(activo, reubicacion.getFecha());
                activos.add(activo);
                seDeprecio = true;
            } else if (reubicacion.getCentroCostoAnterior().getId().getIdCosto().equals(centroCostoId)) {
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                this.deprecia(activo, fecha);
                activos.add(activo);
                seDeprecio = true;
                bandera1 = false;
            } else {
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
            }
            fechaAnterior = reubicacion.getFecha();

            if (seDeprecio) {
                this.depreciacionAcumuladaPorCentroDeCostoDetalle(activo, mc, totales);
            }
        }

        if (bandera1 && activo.getCentroCosto().getId().getIdCosto().equals(centroCostoId)) {
            activo.setFechaCompra(activo.getFechaReubicado());
            this.deprecia(activo, fecha);
            activos.add(activo);
            this.depreciacionAcumuladaPorCentroDeCostoDetalle(activo, mc, totales);
        }

    }
    params.put("activos", activos);
    params.put("totales", totales);
    return params;
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//from www  . j a v a  2 s .  c  o  m
public Map<String, Object> depreciacionMensualPorCentroDeCosto(Map<String, Object> params) {
    Usuario usuario = (Usuario) params.get("usuario");
    Query tiposDeActivoQuery = currentSession().createQuery(
            "select new map(ta.nombre as nombre, ta.cuenta.id.idCtaMayor as cuenta, ta.id as id) from TipoActivo ta where ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId order by ta.cuenta.id.idCtaMayor");
    tiposDeActivoQuery.setString("ejercicioId", usuario.getEjercicio().getId().getIdEjercicio());
    tiposDeActivoQuery.setLong("organizacionId", usuario.getEjercicio().getId().getOrganizacion().getId());
    List<Map<String, Object>> tiposDeActivo = tiposDeActivoQuery.list();
    Map<String, Map<String, Object>> tiposDeActivoMap = new HashMap<>();
    for (Map<String, Object> tipoActivo : tiposDeActivo) {
        tipoActivo.put("total", BigDecimal.ZERO);
        tiposDeActivoMap.put((String) tipoActivo.get("cuenta"), tipoActivo);
    }
    Map<String, Object> totalCC = new HashMap<>();
    totalCC.put("nombre", "");
    totalCC.put("cuenta", "TOTAL");
    totalCC.put("id", 0);
    totalCC.put("total", BigDecimal.ZERO);
    tiposDeActivo.add(totalCC);
    tiposDeActivoMap.put("TOTAL", totalCC);
    params.put("tiposDeActivo", tiposDeActivo);

    Date fecha = (Date) params.get("fecha");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    Map<String, Map<String, Object>> mapa1 = new TreeMap<>();
    Query query = currentSession().createQuery(
            "select new Activo(a.id, a.version, a.moi, a.fechaCompra, a.tipoActivo.porciento, a.tipoActivo.vidaUtil, a.inactivo, a.fechaInactivo, a.fechaReubicado, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.centroCosto.nombre) from Activo a inner join a.tipoActivo where a.empresa.id = :empresaId and a.fechaCompra <= :fecha and a.fechaReubicado is null");
    query.setLong("empresaId", usuario.getEmpresa().getId());
    query.setDate("fecha", fecha);
    List<Activo> activos = query.list();
    for (Activo activo : activos) {
        log.trace("Depreciando activo {}", activo.getId());
        activo = this.deprecia(activo, fecha);

        this.depreciacionMensualPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
    }

    // busca reubicados
    query = currentSession().createQuery(
            "select new Activo(a.id, a.version, a.moi, a.fechaCompra, a.tipoActivo.porciento, a.tipoActivo.vidaUtil, a.inactivo, a.fechaInactivo, a.fechaReubicado, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.centroCosto.nombre) from Activo a inner join a.tipoActivo where a.empresa.id = :empresaId and a.fechaCompra <= :fecha and a.fechaReubicado != null");
    query.setLong("empresaId", usuario.getEmpresa().getId());
    query.setDate("fecha", fecha);
    activos = query.list();
    for (Activo activo : activos) {
        log.trace("Depreciando activo {}", activo.getId());
        query = currentSession().createQuery(
                "select r from ReubicacionActivo r where r.activo.id = :activoId order by r.fecha");
        query.setLong("activoId", activo.getId());
        List<ReubicacionActivo> reubicaciones = query.list();
        Date fechaAnterior = null;
        boolean bandera1 = true;
        for (ReubicacionActivo reubicacion : reubicaciones) {
            if (reubicacion.getFecha().before(fecha)) {
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                this.deprecia(activo, reubicacion.getFecha());
                fechaAnterior = reubicacion.getFecha();
            } else {
                if (fechaAnterior != null) {
                    activo.setFechaCompra(fechaAnterior);
                }
                activo.setCentroCosto(reubicacion.getCentroCostoAnterior());
                this.deprecia(activo, fecha);
                bandera1 = false;
            }

            this.depreciacionMensualPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
        }

        if (bandera1) {
            activo.setFechaCompra(activo.getFechaReubicado());
            this.deprecia(activo, fecha);
            this.depreciacionMensualPorCentroDeCosto(activo, mc, mapa1, tiposDeActivo, tiposDeActivoMap);
        }
    }

    if (log.isTraceEnabled()) {
        for (Map<String, Object> centroCosto : mapa1.values()) {
            log.trace("CentroCosto: {} : {}", centroCosto.get("nombre"), centroCosto.get("totales"));
        }
    }

    params.put("centrosDeCosto", mapa1.values());
    return params;
}