Example usage for java.math BigDecimal abs

List of usage examples for java.math BigDecimal abs

Introduction

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

Prototype

public BigDecimal abs() 

Source Link

Document

Returns a BigDecimal whose value is the absolute value of this BigDecimal , and whose scale is this.scale() .

Usage

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

/**
 * Create Source Line for Suspense Balancing. Only if Suspense Balancing is enabled and not a
 * multi-currency document (double check as otherwise the rule should not have fired) If not
 * balanced create balancing entry in currency of the document
 * // w ww.ja  va  2  s .  co m
 * @return FactLine
 */
public FactLine balanceSource(ConnectionProvider conn) {
    if (!m_acctSchema.isSuspenseBalancing() || m_doc.MultiCurrency)
        return null;
    if (m_lines.size() == 0) {
        log4jFact.error("balanceSouce failed.");
        return null;
    }
    FactLine fl = (FactLine) m_lines.get(0);
    BigDecimal diff = getSourceBalance();
    log4jFact.debug("balanceSource = " + diff);
    // new line
    FactLine line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID, "", fl.m_Fact_Acct_Group_ID, fl.m_SeqNo,
            fl.m_DocBaseType);// antes
    // "0".
    line.setDocumentInfo(m_doc, null);
    line.setJournalInfo(m_doc.GL_Category_ID);
    line.setPostingType(m_postingType);
    // Amount
    if (diff.compareTo(ZERO) < 0) // negative balance => DR
        line.setAmtSource(m_doc.C_Currency_ID, diff.abs().toString(), ZERO.toString());
    else
        // positive balance => CR
        line.setAmtSource(m_doc.C_Currency_ID, ZERO.toString(), diff.toString());
    // Convert
    line.convert(m_acctSchema.getC_Currency_ID(), m_doc.DateAcct, m_acctSchema.getCurrencyRateType(), conn);
    line.setAccount(m_acctSchema, m_acctSchema.getSuspenseBalancing_Acct());
    //
    log4jFact.debug("balanceSource - ");
    log4jFact.debug("****************** fact - balancesource -  m_lines.size() - " + m_lines.size());
    m_lines.add(line);
    return line;
}

From source file:nl.strohalm.cyclos.services.elements.MemberImportServiceImpl.java

private void importMember(final MemberImport memberImport, final MemberGroupAccountSettings accountSettings,
        final int lineNumber, final Map<String, CustomField> customFieldMap,
        final Map<String, MemberRecordType> recordTypeMap,
        final Map<MemberRecordType, Map<String, CustomField>> recordTypeFieldsMap,
        final LocalSettings localSettings, final AccessSettings accessSettings, final List<String> headers,
        final List<String> values, final Set<String> importedUsernames) {
    final Map<MemberRecordType, ImportedMemberRecord> records = new HashMap<MemberRecordType, ImportedMemberRecord>();

    final Map<String, String> customFieldValues = new HashMap<String, String>();
    final Map<MemberRecordType, Map<String, String>> recordFieldValues = new HashMap<MemberRecordType, Map<String, String>>();

    // Insert the member
    ImportedMember member = new ImportedMember();
    member.setSalt(hashHandler.newSalt());
    member.setLineNumber(lineNumber);// w w  w  . j  a v  a  2s .  co  m
    member.setImport(memberImport);
    member.setStatus(ImportedMember.Status.SUCCESS);
    member = importedMemberDao.insert(member);

    final Calendar today = DateHelper.truncate(Calendar.getInstance());
    try {
        member.setCustomValues(new ArrayList<MemberCustomFieldValue>());
        final CalendarConverter dateConverter = localSettings.getRawDateConverter();

        // Process each field. Field names are lowercased to ignore case
        for (int i = 0; i < headers.size() && i < values.size(); i++) {
            final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase();
            final String value = StringUtils.trimToNull(values.get(i));
            if ("name".equals(field)) {
                member.setName(value);
            } else if ("username".equals(field)) {
                member.setUsername(value);
            } else if ("password".equals(field)) {
                member.setPassword(hashHandler.hash(member.getSalt(), value));
            } else if ("email".equals(field)) {
                member.setEmail(value);
            } else if ("creationdate".equals(field)) {
                try {
                    final Calendar creationDate = dateConverter.valueOf(value);
                    if (creationDate != null) {
                        if (creationDate.after(today) || creationDate.get(Calendar.YEAR) < 1950) {
                            throw new Exception();
                        }
                        member.setCreationDate(creationDate);
                    }
                } catch (final Exception e) {
                    member.setStatus(ImportedMember.Status.INVALID_CREATION_DATE);
                    member.setErrorArgument1(value);
                    break;
                }
            } else if ("balance".equals(field)) {
                try {
                    member.setInitialBalance(localSettings.getNumberConverter().valueOf(value));
                } catch (final Exception e) {
                    member.setStatus(ImportedMember.Status.INVALID_BALANCE);
                    member.setErrorArgument1(value);
                    break;
                }
            } else if ("creditlimit".equals(field)) {
                try {
                    BigDecimal limit = localSettings.getNumberConverter().valueOf(value);
                    // Ensure the limit is positive
                    if (limit != null) {
                        limit = limit.abs();
                    }
                    member.setCreditLimit(limit);
                } catch (final Exception e) {
                    member.setStatus(ImportedMember.Status.INVALID_CREDIT_LIMIT);
                    member.setErrorArgument1(value);
                    break;
                }
            } else if ("uppercreditlimit".equals(field)) {
                try {
                    member.setUpperCreditLimit(localSettings.getNumberConverter().valueOf(value));
                } catch (final Exception e) {
                    member.setStatus(ImportedMember.Status.INVALID_UPPER_CREDIT_LIMIT);
                    member.setErrorArgument1(value);
                    break;
                }
            } else if (customFieldMap.containsKey(field)) {
                // Create a custom field value
                CustomField customField = customFieldMap.get(field);
                final MemberCustomFieldValue fieldValue = new MemberCustomFieldValue();
                fieldValue.setField(customField);
                fieldValue.setValue(preprocessCustomFieldValue(customField, value));
                member.getCustomValues().add(fieldValue);
                customFieldValues.put(field, value);
            } else if (field.contains(".")) {
                // A record type value
                final String[] parts = field.split("\\.");
                // Find the record type
                final String recordTypeName = parts[0];
                final MemberRecordType recordType = recordTypeMap.get(recordTypeName);
                if (recordType == null) {
                    member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE);
                    member.setErrorArgument1(recordTypeName);
                    break;
                }
                // Find the custom field
                final String recordTypeField = parts[1];
                final Map<String, CustomField> fieldsMap = recordTypeFieldsMap.get(recordType);
                final CustomField customField = fieldsMap.get(recordTypeField);
                if (customField == null) {
                    member.setStatus(ImportedMember.Status.INVALID_RECORD_TYPE_FIELD);
                    member.setErrorArgument1(recordTypeName);
                    member.setErrorArgument2(recordTypeField);
                    break;
                }
                // Find the imported member record
                ImportedMemberRecord record = records.get(recordType);
                if (record == null) {
                    // None yet - create a new one
                    record = new ImportedMemberRecord();
                    record.setMember(member);
                    record.setType(recordType);
                    record = importedMemberRecordDao.insert(record);
                    record.setCustomValues(new ArrayList<ImportedMemberRecordCustomFieldValue>());
                    records.put(recordType, record);
                }
                // Set the custom field
                final ImportedMemberRecordCustomFieldValue fieldValue = new ImportedMemberRecordCustomFieldValue();
                fieldValue.setField(customField);
                fieldValue.setValue(preprocessCustomFieldValue(customField, value));
                record.getCustomValues().add(fieldValue);

                // Store the field value in a map
                Map<String, String> fieldValues = recordFieldValues.get(recordType);
                if (fieldValues == null) {
                    fieldValues = new HashMap<String, String>();
                    recordFieldValues.put(recordType, fieldValues);
                }
                fieldValues.put(recordTypeField, value);
            } else {
                throw new UnknownColumnException(field);
            }
        }

        // When there was an error, stop processing
        if (member.getStatus() != ImportedMember.Status.SUCCESS) {
            return;
        }

        // Validate some data
        if (member.getName() == null) {
            // Name is always required
            member.setStatus(ImportedMember.Status.MISSING_NAME);
            return;
        }
        final String username = member.getUsername();
        if (accessSettings.getUsernameGeneration() == UsernameGeneration.NONE && username == null) {
            // Username is required when it's not generated
            member.setStatus(ImportedMember.Status.MISSING_USERNAME);
            return;
        }
        // Validate the username
        if (username != null) {
            // Check the username format
            ValidationError error = new RegexValidation(accessSettings.getUsernameRegex()).validate(null, null,
                    username);
            if (error == null) {
                // Check the username length
                error = new LengthValidation(accessSettings.getUsernameLength()).validate(null, null, username);
            }
            if (error != null) {
                member.setStatus(ImportedMember.Status.INVALID_USERNAME);
                member.setErrorArgument1(username);
                return;
            }
            // Check if username is duplicated in this import
            if (!importedUsernames.add(username)) {
                member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE);
                member.setErrorArgument1(username);
                return;
            }
            // Check if username is already used by another member in cyclos
            try {
                elementService.loadUser(username);
                // If an user could be loaded, it means that the username is already in use
                member.setStatus(ImportedMember.Status.USERNAME_ALREADY_IN_USE);
                member.setErrorArgument1(username);
                return;
            } catch (final EntityNotFoundException e) {
                // Ok - not used yet
            }
        }
        if (member.getEmail() == null && localSettings.isEmailRequired()) {
            // Mail is required
            member.setStatus(ImportedMember.Status.MISSING_EMAIL);
            return;
        }
        if (EmailValidation.instance().validate(null, null, member.getEmail()) != null) {
            // Mail format is invalid
            member.setStatus(ImportedMember.Status.INVALID_EMAIL);
            member.setErrorArgument1(member.getEmail());
            return;
        }

        if (memberImport.getAccountType() == null) {
            // Nothing related to accounts will be imported
            member.setInitialBalance(null);
            member.setCreditLimit(null);
            member.setUpperCreditLimit(null);
        } else {
            if (member.getCreditLimit() == null) {
                // Get the default group credit limit
                member.setCreditLimit(accountSettings.getDefaultCreditLimit());
            }
            if (member.getUpperCreditLimit() == null) {
                // Get the default group upper credit limit
                member.setUpperCreditLimit(accountSettings.getDefaultUpperCreditLimit());
            }
            final BigDecimal balance = member.getInitialBalance();

            if (balance != null) {
                double balanceValue = balance.doubleValue();
                if (balanceValue > 0 && memberImport.getInitialCreditTransferType() == null) {
                    // There was an initial credit, but no TT for it: ignore
                    member.setInitialBalance(null);
                    balanceValue = 0;
                } else if (balanceValue < 0 && memberImport.getInitialDebitTransferType() == null) {
                    // There was an initial debit, but no TT for it: ignore
                    member.setInitialBalance(null);
                    balanceValue = 0;
                }

                final BigDecimal creditLimit = member.getCreditLimit();
                if (creditLimit != null && balanceValue < 0 && balance.compareTo(creditLimit.negate()) < 0) {
                    // When the initial balance is negative, ensure the credit limit accommodates it
                    member.setStatus(ImportedMember.Status.BALANCE_LOWER_THAN_CREDIT_LIMIT);
                    return;
                }

                final BigDecimal upperCreditLimit = member.getUpperCreditLimit();
                if (upperCreditLimit != null && balanceValue > 0 && balance.compareTo(upperCreditLimit) > 0) {
                    // When the initial balance is positive, ensure the credit limit accommodates it
                    member.setStatus(ImportedMember.Status.BALANCE_UPPER_THAN_CREDIT_LIMIT);
                    return;
                }

            }
        }
        // Save the custom field values
        try {
            memberCustomFieldService.saveValues(member);
        } catch (final Exception e) {
            member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD);
            if (e instanceof ValidationException) {
                final ValidationException vex = (ValidationException) e;
                final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty();
                if (MapUtils.isNotEmpty(errorsByProperty)) {
                    final String fieldName = errorsByProperty.keySet().iterator().next();
                    final String displayName = vex.getDisplayNameByProperty().get(fieldName);
                    member.setErrorArgument1(StringUtils.isEmpty(displayName) ? fieldName : displayName);
                    final String fieldValue = StringUtils
                            .trimToNull(customFieldValues.get(fieldName.toLowerCase()));
                    if (CollectionUtils.isNotEmpty(errorsByProperty.get(fieldName))) {
                        ValidationError ve = errorsByProperty.get(fieldName).iterator().next();
                        if (ve instanceof UniqueError) {
                            member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_UNIQUE);
                            member.setErrorArgument2(ve.getArguments().iterator().next().toString());
                        } else if (ve instanceof RequiredError) {
                            member.setStatus(ImportedMember.Status.MISSING_CUSTOM_FIELD);
                        } else if (ve instanceof MaxLengthError) {
                            member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MAX_LENGTH);
                            member.setErrorArgument2(ve.getArguments().iterator().next().toString());
                        } else if (ve instanceof MinLengthError) {
                            member.setStatus(ImportedMember.Status.INVALID_CUSTOM_FIELD_VALUE_MIN_LENGTH);
                            member.setErrorArgument2(ve.getArguments().iterator().next().toString());
                        }
                    }
                    if (StringUtils.isEmpty(member.getErrorArgument2()) && fieldValue != null) {
                        member.setErrorArgument2(fieldValue);
                    }
                }
            }
            return;
        }

        // Save each record field values
        for (final ImportedMemberRecord record : records.values()) {
            final MemberRecordType recordType = record.getType();
            final Map<String, String> fieldValues = recordFieldValues.get(recordType);
            // Check if the record is not empty
            boolean empty = true;
            for (final String value : fieldValues.values()) {
                if (StringUtils.isNotEmpty(value)) {
                    empty = false;
                    break;
                }
            }
            if (empty) {
                // There are no fields for this record: remove the record itself
                importedMemberRecordDao.delete(record.getId());
                continue;
            }
            try {
                memberRecordCustomFieldService.saveValues(record);
            } catch (final Exception e) {
                member.setStatus(ImportedMember.Status.INVALID_RECORD_FIELD);
                if (e instanceof ValidationException) {
                    final ValidationException vex = (ValidationException) e;
                    final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty();
                    if (MapUtils.isNotEmpty(errorsByProperty)) {
                        final String fieldName = errorsByProperty.keySet().iterator().next();
                        member.setErrorArgument1(recordType.getName() + "." + fieldName);
                        final String fieldValue = StringUtils.trimToNull(fieldValues.get(fieldName));
                        if (fieldValue == null) {
                            // When validation failed and the field is null, it's actually missing
                            member.setStatus(ImportedMember.Status.MISSING_RECORD_FIELD);
                        } else {
                            member.setErrorArgument2(fieldValue);
                        }
                    }
                }
                return;
            }
        }

    } catch (final UnknownColumnException e) {
        throw e;
    } catch (final Exception e) {
        member.setStatus(ImportedMember.Status.UNKNOWN_ERROR);
        member.setErrorArgument1(e.toString());
    } finally {
        importedMemberDao.update(member);
    }
}

From source file:org.kuali.kfs.module.endow.batch.service.impl.GeneralLedgerInterfaceBatchProcessServiceImpl.java

/**
 * method to create origin entry and populate the fields
 * @param transactionArchive, postedDate
 * @return oef/*from  w  ww  .  ja va2  s.  c  o  m*/
 */
protected OriginEntryFull createOriginEntryFull(GlInterfaceBatchProcessKemLine transactionArchive,
        java.util.Date postedDate, GLInterfaceBatchStatisticsReportDetailTableRow statisticsDataRow) {

    OriginEntryFull oef = new OriginEntryFull();

    try {
        oef.setChartOfAccountsCode(transactionArchive.getChartCode());
        oef.setAccountNumber(transactionArchive.getAccountNumber());
        oef.setFinancialObjectCode(transactionArchive.getObjectCode());
        oef.setFinancialDocumentTypeCode(transactionArchive.getTypeCode());
        oef.setFinancialSystemOriginationCode(
                EndowConstants.KemToGLInterfaceBatchProcess.SYSTEM_ORIGINATION_CODE_FOR_ENDOWMENT);
        oef.setDocumentNumber(transactionArchive.getDocumentNumber());
        oef.setTransactionLedgerEntryDescription(getTransactionDescription(transactionArchive, postedDate));
        BigDecimal transactionAmount = getTransactionAmount(transactionArchive);
        oef.setTransactionLedgerEntryAmount(new KualiDecimal(transactionAmount.abs()));
        oef.setTransactionDebitCreditCode(getTransactionDebitCreditCode(transactionArchive.getTypeCode(),
                transactionAmount, transactionArchive.getSubTypeCode()));
    } catch (Exception ex) {
        statisticsDataRow.increaseNumberOfExceptionsCount();
        writeExceptionRecord(transactionArchive, ex.getMessage());
    }

    return oef;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic cosine.//ww w. ja  va 2s  .co m
 *
 * @param x The argument.
 * @return The cosh(x) = (exp(x)+exp(-x))/2 .
 */
static public BigDecimal cosh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cos(x.negate());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ONE;
    } else {
        if (x.doubleValue() > 1.5) {
            /* cosh^2(x) = 1+ sinh^2(x).
             */
            return hypot(1, sinh(x));

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */
            BigDecimal resul = BigDecimal.ONE;
            /* x^i */
            BigDecimal xpowi = BigDecimal.ONE;
            /* 2i factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The absolute error in the result is the error in x^2/2 which is x times the error in x.
             */

            double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue();
            /* The error in the result is set by the error in x^2/2 itself, xUlpDbl.
             * We need at most k terms to push x^(2k)/(2k)! below this value.
             * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl);
             */

            int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2;
            /* The individual terms are all smaller than 1, so an estimate of 1.0 for
             * the absolute value will give a safe relative error estimate for the indivdual terms
             */
            MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i-1 or 2*i overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i - 1)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is governed by the error in x itself.
              */
            MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl));

            return resul.round(mc);

        }
    }
}

From source file:org.openbravo.advpaymentmngt.actionHandler.ModifyPaymentPlanActionHandler.java

/**
 * Given a list of payment schedule element and a list of amounts associated to orders, creates
 * the payment schedule details for the given payment schedule element
 * /*from w w  w .  j a  v  a  2  s .  co m*/
 */
private HashMap<FIN_PaymentSchedule, BigDecimal> createPaymentScheduleDetail(FIN_PaymentSchedule invoicePS,
        HashMap<FIN_PaymentSchedule, BigDecimal> ordersProvided) {
    HashMap<FIN_PaymentSchedule, BigDecimal> orders = ordersProvided;
    Iterator<FIN_PaymentSchedule> ite = orders.keySet().iterator();
    BigDecimal amount = getPendingPSAmounts(invoicePS);
    List<FIN_PaymentSchedule> lOrdersToRemove = new ArrayList<FIN_PaymentSchedule>();
    FIN_PaymentSchedule orderPS = null;
    BigDecimal orderAmount = BigDecimal.ZERO;
    if (orders.containsKey(null)) {
        orderAmount = orders.get(null);
    } else {
        lOrdersToRemove.add(null);
    }
    while (amount.compareTo(BigDecimal.ZERO) != 0 && ite.hasNext()) {
        if (lOrdersToRemove.contains(orderPS) || orderAmount.compareTo(BigDecimal.ZERO) == 0) {
            orderPS = ite.next();
            orderAmount = orders.get(orderPS);
        }
        if (amount.abs().compareTo(orderAmount.abs()) >= 0) {
            if (orderAmount.compareTo(BigDecimal.ZERO) != 0) {
                dao.getNewPaymentScheduleDetail(invoicePS, orderPS, orderAmount, BigDecimal.ZERO, null);
            }
            amount = amount.subtract(orderAmount);
            orderAmount = BigDecimal.ZERO;
            lOrdersToRemove.add(orderPS);
        } else {
            if (amount.compareTo(BigDecimal.ZERO) != 0) {
                dao.getNewPaymentScheduleDetail(invoicePS, orderPS, amount, BigDecimal.ZERO, null);
            }
            orderAmount = orderAmount.subtract(amount);
            amount = BigDecimal.ZERO;
        }
        orders.put(orderPS, orderAmount);
    }
    OBDal.getInstance().flush();

    for (FIN_PaymentSchedule ps : lOrdersToRemove) {
        orders.remove(ps);
    }
    return orders;
}

From source file:org.kuali.kfs.module.endow.batch.service.impl.GeneralLedgerInterfaceBatchProcessServiceImpl.java

/**
 * method to create an offset record when document type is NON-CASH
 * @param oef OriginEntryFull//  ww w  .  j a v  a 2  s  .  c  o  m
 * @param transactionArchive
 * @param OUTPUT_KEM_TO_GL_DATA_FILE_ps the output file
 * @param statisticsDataRow
 * @return success true if successfully created offset or gain loss entry else false
 */
protected boolean createOffsetEntry(OriginEntryFull oef, GlInterfaceBatchProcessKemLine transactionArchive,
        PrintStream OUTPUT_KEM_TO_GL_DATA_FILE_ps,
        GLInterfaceBatchStatisticsReportDetailTableRow statisticsDataRow) {
    boolean success = true;

    oef.setFinancialObjectCode(transactionArchive.getNonCashOffsetObjectCode());

    BigDecimal transactionAmount = transactionArchive.getHoldingCost();
    oef.setTransactionLedgerEntryAmount(new KualiDecimal(transactionAmount.abs()));
    oef.setTransactionDebitCreditCode(getTransactionDebitCreditCodeForOffSetEntry(transactionAmount));
    try {
        createOutputEntry(oef, OUTPUT_KEM_TO_GL_DATA_FILE_ps);
        statisticsDataRow.increaseGLEntriesGeneratedCount();

        GlInterfaceBatchProcessKemLine transactionArchiveLossGain = new GlInterfaceBatchProcessKemLine();
        transactionArchiveLossGain.setTypeCode(transactionArchive.getTypeCode());
        transactionArchiveLossGain.setChartCode(transactionArchive.getChartCode());
        transactionArchiveLossGain.setObjectCode(oef.getFinancialObjectCode());
        transactionArchiveLossGain.setShortTermGainLoss(transactionArchive.getShortTermGainLoss());
        transactionArchiveLossGain.setLongTermGainLoss(transactionArchive.getLongTermGainLoss());
        transactionArchiveLossGain.setSubTypeCode(transactionArchive.getSubTypeCode());
        transactionArchiveLossGain.setHoldingCost(transactionArchive.getHoldingCost());
        transactionArchiveLossGain
                .setTransactionArchiveIncomeAmount(transactionArchive.getTransactionArchiveIncomeAmount());
        transactionArchiveLossGain.setTransactionArchivePrincipalAmount(
                transactionArchive.getTransactionArchivePrincipalAmount());

        updateTotalsProcessed(transactionArchiveLossGain);
    } catch (Exception ex) {
        //write the error details to the exception report...
        statisticsDataRow.increaseNumberOfExceptionsCount();
        writeExceptionRecord(transactionArchive, ex.getMessage());
        success = false;
    }

    return success;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic sine./*from w w w . j a  v  a  2  s. co m*/
 *
 * @param x the argument.
 * @return the sinh(x) = (exp(x)-exp(-x))/2 .
 */
static public BigDecimal sinh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sinh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        if (x.doubleValue() > 2.4) {
            /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
             */
            BigDecimal two = new BigDecimal(2);
            BigDecimal xhalf = x.divide(two);

            BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two);
            /* The error in the result is set by the error in x itself.
             * The first derivative of sinh(x) is cosh(x), so the absolute error
             * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
             */

            double eps = Math.tanh(x.doubleValue());
            MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps));

            return resul.round(mc);

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */
            BigDecimal resul = xhighpr;
            /* x^i */
            BigDecimal xpowi = xhighpr;
            /* 2i+1 factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The error in the result is set by the error in x itself.
             */

            double xUlpDbl = x.ulp().doubleValue();
            /* The error in the result is set by the error in x itself.
             * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
             * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
             * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
             */

            int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2;
            MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i or 2*i+1 overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is set by the error in x itself.
              */
            MathContext mc = new MathContext(x.precision());

            return resul.round(mc);

        }
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Trigonometric sine./*from w w  w .  j  av  a  2s  . c o m*/
 *
 * @param x The argument in radians.
 * @return sin(x) in the range -1 to 1.
 */
static public BigDecimal sin(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sin(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* reduce modulo 2pi
         */
        BigDecimal res = mod2pi(x);
        double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
        int val = 2 + err2prec(FastMath.PI, errpi);
        MathContext mc = new MathContext(val);
        BigDecimal p = pi(mc);
        mc = new MathContext(x.precision());
        if (res.compareTo(p) > 0) {
            /* pi<x<=2pi: sin(x)= - sin(x-pi)
             */
            return sin(subtractRound(res, p)).negate();
        } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) {
            /* pi/2<x<=pi: sin(x)= sin(pi-x)
             */
            return sin(subtractRound(p, res));
        } else {
            /* for the range 0<=x<Pi/2 one could use sin(2x)=2sin(x)cos(x)
             * to split this further. Here, use the sine up to pi/4 and the cosine higher up.
             */
            if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) {
                /* x>pi/4: sin(x) = cos(pi/2-x)
                 */
                return cos(subtractRound(p.divide(new BigDecimal("2")), res));
            } else {
                /* Simple Taylor expansion, sum_{i=1..infinity} (-1)^(..)res^(2i+1)/(2i+1)! */
                BigDecimal resul = res;
                /* x^i */
                BigDecimal xpowi = res;
                /* 2i+1 factorial */
                BigInteger ifac = BigInteger.ONE;
                /* The error in the result is set by the error in x itself.
                 */
                double xUlpDbl = res.ulp().doubleValue();
                /* The error in the result is set by the error in x itself.
                 * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
                 * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
                 * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
                 */
                int k = (int) (res.precision() / Math.log10(1.0 / res.doubleValue())) / 2;
                MathContext mcTay = new MathContext(err2prec(res.doubleValue(), xUlpDbl / k));
                for (int i = 1;; i++) {
                    /* TBD: at which precision will 2*i or 2*i+1 overflow?
                     */
                    ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                    ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                    xpowi = xpowi.multiply(res).multiply(res).negate();
                    BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                    resul = resul.add(corr);
                    if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                        break;
                    }
                }
                /* The error in the result is set by the error in x itself.
                 */
                mc = new MathContext(res.precision());
                return resul.round(mc);
            }
        }
    } /* sin */
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Trigonometric cosine./*  w  w  w .  j  a v  a  2 s  . c o m*/
 *
 * @param x The argument in radians.
 * @return cos(x) in the range -1 to 1.
 */
static public BigDecimal cos(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cos(x.negate());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ONE;
    } else {
        /* reduce modulo 2pi
         */
        BigDecimal res = mod2pi(x);
        double errpi = 0.5 * Math.abs(x.ulp().doubleValue());
        int val = +err2prec(FastMath.PI, errpi);
        MathContext mc = new MathContext(val);
        BigDecimal p = pi(mc);
        mc = new MathContext(x.precision());
        if (res.compareTo(p) > 0) {
            /* pi<x<=2pi: cos(x)= - cos(x-pi)
             */
            return cos(subtractRound(res, p)).negate();
        } else if (res.multiply(new BigDecimal("2")).compareTo(p) > 0) {
            /* pi/2<x<=pi: cos(x)= -cos(pi-x)
             */
            return cos(subtractRound(p, res)).negate();
        } else {
            /* for the range 0<=x<Pi/2 one could use cos(2x)= 1-2*sin^2(x)
             * to split this further, or use the cos up to pi/4 and the sine higher up.
            throw new ProviderException("Unimplemented cosine ") ;
             */
            if (res.multiply(new BigDecimal("4")).compareTo(p) > 0) {
                /* x>pi/4: cos(x) = sin(pi/2-x)
                 */
                return sin(subtractRound(p.divide(new BigDecimal("2")), res));
            } else {
                /* Simple Taylor expansion, sum_{i=0..infinity} (-1)^(..)res^(2i)/(2i)! */
                BigDecimal resul = BigDecimal.ONE;
                /* x^i */
                BigDecimal xpowi = BigDecimal.ONE;
                /* 2i factorial */
                BigInteger ifac = BigInteger.ONE;
                /* The absolute error in the result is the error in x^2/2 which is x times the error in x.
                 */
                double xUlpDbl = 0.5 * res.ulp().doubleValue() * res.doubleValue();
                /* The error in the result is set by the error in x^2/2 itself, xUlpDbl.
                 * We need at most k terms to push x^(2k+1)/(2k+1)! below this value.
                 * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl);
                 */
                int k = (int) (Math.log(xUlpDbl) / Math.log(res.doubleValue())) / 2;
                MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k));
                for (int i = 1;; i++) {
                    /* TBD: at which precision will 2*i-1 or 2*i overflow?
                     */
                    ifac = ifac.multiply(new BigInteger("" + (2 * i - 1)));
                    ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                    xpowi = xpowi.multiply(res).multiply(res).negate();
                    BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                    resul = resul.add(corr);
                    if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                        break;
                    }
                }
                /* The error in the result is governed by the error in x itself.
                 */
                mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl));
                return resul.round(mc);
            }
        }
    }
}

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

/**
 * Create and convert Fact Line using a specified conversion date. Used to create a DR and/or CR
 * entry//from   ww w  .j ava 2s. c  om
 * 
 * @param docLine
 *          the document line or null
 * @param account
 *          if null, line is not created
 * @param C_Currency_ID
 *          the currency
 * @param debitAmt
 *          debit amount, can be null
 * @param creditAmt
 *          credit amount, can be null
 * @param Fact_Acct_Group_ID
 * 
 * @param SeqNo
 * 
 * @param DocBaseType
 * 
 * @param conversionDate
 *          Date to convert currencies if required
 * @param conversionRate
 *          The rate to use to convert from source amount to account amount. May be null
 * @return Fact Line
 */
public FactLine createLine(DocLine docLine, Account account, String C_Currency_ID, String debitAmt,
        String creditAmt, String Fact_Acct_Group_ID, String SeqNo, String DocBaseType, String conversionDate,
        BigDecimal conversionRate, ConnectionProvider conn) {

    String strNegate = "";
    try {
        strNegate = AcctServerData.selectNegate(conn, m_acctSchema.m_C_AcctSchema_ID, DocBaseType);
        if (strNegate.equals(""))
            strNegate = AcctServerData.selectDefaultNegate(conn, m_acctSchema.m_C_AcctSchema_ID);
    } catch (ServletException e) {
    }
    if (strNegate.equals(""))
        strNegate = "Y";
    BigDecimal DebitAmt = new BigDecimal(debitAmt.equals("") ? "0.00" : debitAmt);
    BigDecimal CreditAmt = new BigDecimal(creditAmt.equals("") ? "0.00" : creditAmt);
    if (DebitAmt.compareTo(BigDecimal.ZERO) == 0 && CreditAmt.compareTo(BigDecimal.ZERO) == 0) {
        return null;
    }
    if (strNegate.equals("N") && (DebitAmt.compareTo(ZERO) < 0 || CreditAmt.compareTo(ZERO) < 0)) {
        BigDecimal convertedDebitAmt = StringUtils.isBlank(docLine.m_AmtAcctDr) ? ZERO
                : new BigDecimal(docLine.m_AmtAcctDr);
        BigDecimal convertedCreditAmt = StringUtils.isBlank(docLine.m_AmtAcctCr) ? ZERO
                : new BigDecimal(docLine.m_AmtAcctCr);

        if (DebitAmt.compareTo(ZERO) < 0) {
            CreditAmt = CreditAmt.add(DebitAmt.abs());
            creditAmt = CreditAmt.toString();
            DebitAmt = BigDecimal.ZERO;
            debitAmt = DebitAmt.toString();
            convertedCreditAmt = convertedCreditAmt.add(convertedDebitAmt.abs());
            convertedDebitAmt = BigDecimal.ZERO;
        }
        if (CreditAmt.compareTo(ZERO) < 0) {
            DebitAmt = DebitAmt.add(CreditAmt.abs());
            debitAmt = DebitAmt.toString();
            CreditAmt = BigDecimal.ZERO;
            creditAmt = CreditAmt.toString();
            convertedDebitAmt = convertedDebitAmt.add(convertedCreditAmt.abs());
            convertedCreditAmt = BigDecimal.ZERO;
        }

        // If this is a manual entry then we need to recompute Amounts which were set in loadLines for
        // GL Journal Document
        if ("GLJ".equals(DocBaseType)) {
            docLine.setConvertedAmt(docLine.m_C_AcctSchema_ID, convertedDebitAmt.toString(),
                    convertedCreditAmt.toString());
        }

        if (strNegate.equals("N") && (DebitAmt.compareTo(ZERO) < 0 || CreditAmt.compareTo(ZERO) < 0)) {
            return createLine(docLine, account, C_Currency_ID, CreditAmt.abs().toString(),
                    DebitAmt.abs().toString(), Fact_Acct_Group_ID, SeqNo, DocBaseType, conn);
        }
    }

    log4jFact.debug("createLine - " + account + " - Dr=" + debitAmt + ", Cr=" + creditAmt);
    log4jFact.debug("Starting createline");
    // Data Check
    if (account == null) {
        log4jFact.debug("end of create line");
        m_doc.setStatus(AcctServer.STATUS_InvalidAccount);
        return null;
    }
    //
    log4jFact.debug("createLine - Fact_Acct_Group_ID = " + Fact_Acct_Group_ID);
    FactLine line = new FactLine(m_doc.AD_Table_ID, m_doc.Record_ID,
            docLine == null ? "" : docLine.m_TrxLine_ID, Fact_Acct_Group_ID, SeqNo, DocBaseType);
    log4jFact.debug("createLine - line.m_Fact_Acct_Group_ID = " + line.m_Fact_Acct_Group_ID);
    log4jFact.debug("Object created");
    line.setDocumentInfo(m_doc, docLine);
    line.setAD_Org_ID(m_doc.AD_Org_ID);
    // if (docLine!=null) line.setAD_Org_ID(docLine.m_AD_Org_ID);
    log4jFact.debug("document info set");
    line.setAccount(m_acctSchema, account);
    log4jFact.debug("account set");

    log4jFact.debug(
            "C_Currency_ID: " + C_Currency_ID + " - debitAmt: " + debitAmt + " - creditAmt: " + creditAmt);
    // Amounts - one needs to be both not zero
    if (!line.setAmtSource(C_Currency_ID, debitAmt, creditAmt))
        return null;
    if (conversionDate == null || conversionDate.isEmpty()) {
        conversionDate = m_doc.DateAcct;
    }
    log4jFact.debug("C_Currency_ID: " + m_acctSchema.getC_Currency_ID() + " - ConversionDate: " + conversionDate
            + " - CurrencyRateType: " + m_acctSchema.getCurrencyRateType());
    // Convert
    if (conversionRate != null) {
        line.convertByRate(m_acctSchema.getC_Currency_ID(), conversionRate);
    } else {
        line.convert(m_acctSchema.getC_Currency_ID(), conversionDate, m_acctSchema.getCurrencyRateType(), conn);
    }
    // Optionally overwrite Acct Amount
    if (docLine != null && !docLine.m_AmtAcctDr.equals("") && !docLine.m_AmtAcctCr.equals(""))
        line.setAmtAcct(docLine.m_AmtAcctDr, docLine.m_AmtAcctCr);
    // Info
    line.setJournalInfo(m_doc.GL_Category_ID);
    line.setPostingType(m_postingType);
    // Set Info
    line.setDocumentInfo(m_doc, docLine);
    //
    log4jFact.debug("createLine - " + m_doc.DocumentNo);
    log4jFact.debug("********************* Fact - createLine - DocumentNo - " + m_doc.DocumentNo
            + " -  m_lines.size() - " + m_lines.size());

    line.roundToCurrencyPrecision();

    m_lines.add(line);
    return line;
}