Example usage for java.text DecimalFormat setParseBigDecimal

List of usage examples for java.text DecimalFormat setParseBigDecimal

Introduction

In this page you can find the example usage for java.text DecimalFormat setParseBigDecimal.

Prototype

public void setParseBigDecimal(boolean newValue) 

Source Link

Document

Sets whether the #parse(java.lang.String,java.text.ParsePosition) method returns BigDecimal .

Usage

From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java

@Override
public BigDecimal getBigDecimalFromField(final Object value, final Locale locale) {
    try {//from   w ww.  jav a2s  .c  o  m
        DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
        format.setParseBigDecimal(true);
        return new BigDecimal(format.parse(value.toString()).doubleValue());
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.ohmage.domain.campaign.prompt.BoundedPrompt.java

/**
 * Verifies that the value of the condition is not outside the bounds of
 * the prompt.//  w w  w. ja  v  a  2 s  . co  m
 * 
 * @param pair The condition-value pair to validate.
 * 
 * @throws DomainException The value was not a number or was outside the
 *                      predefined bounds.
 */
@Override
public void validateConditionValuePair(final ConditionValuePair pair) throws DomainException {

    try {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setParseBigDecimal(true);
        BigDecimal value = (BigDecimal) decimalFormat.parse(pair.getValue());

        // Verify that the default is not less than the minimum.
        if (value.compareTo(getMin()) < 0) {
            throw new DomainException("The value of the condition is less than the " + "minimum allowed value ("
                    + getMin() + "): " + pair.getValue());
        }
        // Verify that the default is not greater than the maximum.
        else if (value.compareTo(getMax()) > 0) {
            throw new DomainException("The value of the condition is greater than the "
                    + "maximum allowed value (" + getMax() + "): " + pair.getValue());
        }
        // Verify that the condition is a whole number if the response
        // must be a whole number
        else if (mustBeWholeNumber() && !isWholeNumber(value)) {
            throw new DomainException("The value of the condition is a decimal, but the "
                    + "flag indicatest that only whole numbers are " + "possible.");
        }
    } catch (ParseException e) {
        throw new DomainException("The value of the condition is not a number: " + pair.getValue(), e);
    }
}

From source file:org.ohmage.domain.campaign.prompt.BoundedPrompt.java

/**
 * Validates that a given value is valid and, if so, converts it into an 
 * appropriate object./* ww  w.  j  a  va 2  s.c om*/
 * 
 * @param value The value to be validated. This must be one of the  
 *             following:<br />
 *             <ul>
 *             <li>{@link NoResponse}</li>
 *             <li>{@link AtomicInteger}</li>
 *             <li>{@link AtomicLong}</li>
 *             <li>{@link BigInteger}</li>
 *             <li>{@link Integer}</li>
 *             <li>{@link Long}</li>
 *             <li>{@link Short}</li>
 *             <li>{@link String} that represents:</li>
 *               <ul>
 *                 <li>{@link NoResponse}</li>
 *                 <li>A whole number.</li>
 *               <ul>
 *             </ul>
 * 
 * @return A {@link Number} object or a {@link NoResponse} object.
 * 
 * @throws DomainException The value is invalid.
 */
@Override
public Object validateValue(final Object value) throws DomainException {
    BigDecimal result;

    // If it's already a NoResponse value, then return make sure that if it
    // was skipped that it as skippable.
    if (value instanceof NoResponse) {
        if (NoResponse.SKIPPED.equals(value) && (!skippable())) {
            throw new DomainException("The prompt, '" + getId() + "', was skipped, but it is not skippable.");
        }

        return value;
    }
    // If it's already a number, be sure it is a whole number, if required.
    else if (value instanceof Number) {
        result = new BigDecimal(value.toString());
        if (mustBeWholeNumber() && (!isWholeNumber(result))) {
            throw new DomainException("The value cannot be a decimal: " + value);
        }
    }
    // If it is a string, parse it to check if it's a NoResponse value and,
    // if not, parse it as a long. If that does not work either, throw an
    // exception.
    else if (value instanceof String) {
        String stringValue = (String) value;

        try {
            //throw new NoResponseException(NoResponse.valueOf(stringValue));
            return NoResponse.valueOf(stringValue);
        } catch (IllegalArgumentException iae) {
            // Parse it.
            try {
                DecimalFormat format = new DecimalFormat();
                format.setParseBigDecimal(true);
                result = (BigDecimal) format.parse(stringValue);
            } catch (ParseException e) {
                throw new DomainException("The value could not be decoded as a number: " + stringValue, e);
            }
        }

        // Validate it.
        if (mustBeWholeNumber() && (!isWholeNumber(result))) {
            throw new DomainException("The value cannot be a decimal: " + value);
        }
    }
    // Finally, if its type is unknown, throw an exception.
    else {
        throw new DomainException(
                "The value is not decodable as a response value for " + "prompt '" + getId() + "'.");
    }

    // Now that we have a Number value, verify that it is within bounds.
    if (min.compareTo(result) > 0) {
        throw new DomainException("The value is less than the lower bound (" + min + ") for the prompt, '"
                + getId() + "': " + result);
    } else if (max.compareTo(result) < 0) {
        throw new DomainException("The value is greater than the upper bound (" + max + ") for the prompt, '"
                + getId() + "': " + result);
    }

    return result;
}

From source file:br.msf.commons.util.CharSequenceUtils.java

public static boolean isNumber(final CharSequence sequence, final Locale locale) {
    if (sequence == null) {
        return false;
    }/*from  w w w. j a  v a  2s  .c om*/
    try {
        DecimalFormat formater = (DecimalFormat) DecimalFormat
                .getInstance(LocaleUtils.getNullSafeLocale(locale));
        formater.setParseBigDecimal(true);
        formater.parse(sequence.toString());
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

From source file:org.totschnig.myexpenses.util.Utils.java

/**
 * <a href="http://www.ibm.com/developerworks/java/library/j-numberformat/">
 * http://www.ibm.com/developerworks/java/library/j-numberformat/</a>
 *
 * @param strFloat/* w w  w . j  a  v a  2s  .c o m*/
 *          parsed as float with the number format defined in the locale
 * @return the float retrieved from the string or null if parse did not
 *         succeed
 */
public static BigDecimal validateNumber(DecimalFormat df, String strFloat) {
    ParsePosition pp;
    pp = new ParsePosition(0);
    pp.setIndex(0);
    df.setParseBigDecimal(true);
    BigDecimal n = (BigDecimal) df.parse(strFloat, pp);
    if (strFloat.length() != pp.getIndex() || n == null) {
        return null;
    } else {
        return n;
    }
}

From source file:com.qcadoo.mes.productionScheduling.listeners.OrderTimePredictionListeners.java

@Transactional
public void changeRealizationTime(final ViewDefinitionState view, final ComponentState state,
        final String[] args) {
    FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM);

    FieldComponent technologyLookup = (FieldComponent) view.getComponentByReference(OrderFields.TECHNOLOGY);
    FieldComponent plannedQuantityField = (FieldComponent) view
            .getComponentByReference(OrderFields.PLANNED_QUANTITY);
    FieldComponent dateFromField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_FROM);
    FieldComponent dateToField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_TO);
    FieldComponent productionLineLookup = (FieldComponent) view
            .getComponentByReference(OrderFields.PRODUCTION_LINE);

    boolean isGenerated = false;

    if (technologyLookup.getFieldValue() == null) {
        technologyLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;/* w  ww  . j  a  v  a2s  .c o m*/
    }

    if (!StringUtils.hasText((String) dateFromField.getFieldValue())) {
        dateFromField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    if (!StringUtils.hasText((String) plannedQuantityField.getFieldValue())) {
        plannedQuantityField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    if (productionLineLookup.getFieldValue() == null) {
        productionLineLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    BigDecimal quantity = null;
    Object value = plannedQuantityField.getFieldValue();

    if (value instanceof BigDecimal) {
        quantity = (BigDecimal) value;
    } else {
        try {
            ParsePosition parsePosition = new ParsePosition(0);
            String trimedValue = value.toString().replaceAll(" ", "");
            DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(view.getLocale());
            formatter.setParseBigDecimal(true);
            quantity = new BigDecimal(String.valueOf(formatter.parseObject(trimedValue, parsePosition)));
        } catch (NumberFormatException e) {
            plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidNumericFormat",
                    MessageType.FAILURE);

            return;
        }
    }

    int scale = quantity.scale();

    if (MAX != null && scale > MAX) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidScale.max", MessageType.FAILURE,
                MAX.toString());
        return;
    }

    int presicion = quantity.precision() - scale;

    if (MAX != null && presicion > MAX) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidPrecision.max",
                MessageType.FAILURE, MAX.toString());
        return;
    }

    if (BigDecimal.ZERO.compareTo(quantity) >= 0) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.outOfRange.toSmall",
                MessageType.FAILURE);
        return;
    }

    int maxPathTime = 0;

    Entity technology = dataDefinitionService
            .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY)
            .get((Long) technologyLookup.getFieldValue());
    Validate.notNull(technology, "technology is null");

    if (technology.getStringField(TechnologyFields.STATE).equals(TechnologyState.DRAFT.getStringValue())
            || technology.getStringField(TechnologyFields.STATE)
                    .equals(TechnologyState.OUTDATED.getStringValue())) {
        technologyLookup.addMessage("productionScheduling.technology.incorrectState", MessageType.FAILURE);

        return;
    }

    FieldComponent laborWorkTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.LABOR_WORK_TIME);
    FieldComponent machineWorkTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.MACHINE_WORK_TIME);
    FieldComponent includeTpzField = (FieldComponent) view.getComponentByReference(OrderFieldsPS.INCLUDE_TPZ);
    FieldComponent includeAdditionalTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.INCLUDE_ADDITIONAL_TIME);

    Boolean includeTpz = "1".equals(includeTpzField.getFieldValue());
    Boolean includeAdditionalTime = "1".equals(includeAdditionalTimeField.getFieldValue());

    Entity productionLine = dataDefinitionService
            .get(ProductionLinesConstants.PLUGIN_IDENTIFIER, ProductionLinesConstants.MODEL_PRODUCTION_LINE)
            .get((Long) productionLineLookup.getFieldValue());

    final Map<Long, BigDecimal> operationRuns = Maps.newHashMap();

    productQuantitiesService.getProductComponentQuantities(technology, quantity, operationRuns);

    OperationWorkTime workTime = operationWorkTimeService.estimateTotalWorkTimeForTechnology(technology,
            operationRuns, includeTpz, includeAdditionalTime, productionLine, true);

    laborWorkTimeField.setFieldValue(workTime.getLaborWorkTime());
    machineWorkTimeField.setFieldValue(workTime.getMachineWorkTime());

    maxPathTime = orderRealizationTimeService.estimateOperationTimeConsumption(
            technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS).getRoot(), quantity, includeTpz,
            includeAdditionalTime, productionLine);

    if (maxPathTime > OrderRealizationTimeService.MAX_REALIZATION_TIME) {
        state.addMessage("orders.validate.global.error.RealizationTimeIsToLong", MessageType.FAILURE);

        dateToField.setFieldValue(null);
    } else {
        Date startTime = DateUtils.parseDate(dateFromField.getFieldValue());

        if (startTime == null) {
            dateFromField.addMessage("orders.validate.global.error.dateFromIsNull", MessageType.FAILURE);
        } else {
            Date stopTime = shiftsService.findDateToForOrder(startTime, maxPathTime);

            if (stopTime == null) {
                orderForm.addMessage("productionScheduling.timenorms.isZero", MessageType.FAILURE, false);

                dateToField.setFieldValue(null);
            } else {
                dateToField.setFieldValue(orderRealizationTimeService.setDateToField(stopTime));

                startTime = shiftsService.findDateFromForOrder(stopTime, maxPathTime);

                scheduleOperationComponents(technology.getId(), startTime);

                isGenerated = true;
            }

            if (startTime != null) {
                orderForm.addMessage("orders.dateFrom.info.dateFromSetToFirstPossible", MessageType.INFO,
                        false);
            }
        }
    }

    laborWorkTimeField.requestComponentUpdateState();
    machineWorkTimeField.requestComponentUpdateState();
    dateFromField.requestComponentUpdateState();
    dateToField.requestComponentUpdateState();

    orderForm.setEntity(orderForm.getEntity());

    state.performEvent(view, "refresh", new String[0]);

    if (isGenerated) {
        orderForm.addMessage("productionScheduling.info.calculationGenerated", MessageType.SUCCESS);
    }
}

From source file:com.qcadoo.mes.deliveries.DeliveriesServiceImpl.java

@Override
public BigDecimal getBigDecimalFromField(final FieldComponent fieldComponent, final Locale locale) {
    Object value = fieldComponent.getFieldValue();

    try {//w ww . j  a v a  2 s. c o m
        DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(locale);
        format.setParseBigDecimal(true);

        return new BigDecimal(format.parse(value.toString()).doubleValue());
    } catch (ParseException e) {
        return null;
    }
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();//from   www  .j  av a 2 s .c  o  m
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java

protected List<Document> checkAccounts(final Parameter _parameter, final File _file,
        final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse)
        throws IOException, EFapsException {
    final List<Document> ret = new ArrayList<>();
    final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8"));
    final List<String[]> entries = reader.readAll();
    reader.close();// ww w . jav  a  2 s .c o m
    entries.remove(0);
    int i = 1;
    final Map<String, Document> map = new HashMap<>();
    for (final String[] row : entries) {
        i++;
        final String docNumber = row[0];
        final String ruc = row[1];
        final String dateStr = row[2];
        final String accountStr = row[5];
        final String accountDesc = row[4];
        final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
        formater.setParseBigDecimal(true);
        final String amountMEStr = row[6];
        final String amountMNStr = row[7];

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract);
        queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim());
        final InstanceQuery query = queryBldr.getQuery();
        query.executeWithoutAccessCheck();
        if (query.next()) {
            ImportDetails.LOG.info("Found account: '{}' ", accountStr);
            final String[] docSplit = docNumber.split("-");
            if (docSplit.length != 2 && _docMap != null) {
                ImportDetails.LOG.warn(
                        "Document '{}'  - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber,
                        i);
            } else {
                try {
                    final Formatter criteria = new Formatter();
                    String name = docNumber;
                    if (_docMap != null) {
                        final String serialNo = docSplit[0];
                        final String docNo = docSplit[1];
                        final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", ""));
                        final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", ""));
                        criteria.format("%03d-%06d", serial, no);
                        name = criteria.toString();
                    }

                    Document doc;
                    if (map.containsKey(name)) {
                        doc = map.get(name);
                    } else {
                        if (_docMap != null && _docMap.containsKey(name)) {
                            doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc);
                        } else {
                            doc = new Document(name, null, ruc, dateStr, accountDesc);
                        }
                    }

                    BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr);
                    BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr);

                    if (_inverse) {
                        amountME = amountME.negate();
                        amountMN = amountMN.negate();
                    }

                    if (amountMN.compareTo(BigDecimal.ZERO) >= 0) {
                        doc.addAmountMECredit(amountME);
                        doc.addAmountMNCredit(amountMN);
                    } else {
                        doc.addAmountMEDebit(amountME);
                        doc.addAmountMNDebit(amountMN);
                    }

                    final Map<String, Account> accounts = doc.getAccounts();
                    Account acc;
                    if (accounts.containsKey(accountStr)) {
                        acc = accounts.get(accountStr);
                    } else {
                        acc = new Account(accountStr, accountDesc);
                        accounts.put(accountStr, acc);
                    }
                    acc.addAmountME(amountME);
                    acc.addAmountMN(amountMN);
                    acc.setInstance(query.getCurrentValue());

                    map.put(name, doc);

                    criteria.close();
                } catch (final NumberFormatException e) {
                    ImportDetails.LOG.error("wrong format for document '{}'", docNumber);
                } catch (final ParseException e) {
                    ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr);
                }
            }
        } else {
            ImportDetails.LOG.error("Not found account: {}", accountStr);
        }
    }

    final Instance periodInst = getPeriodInstance();
    for (final Document doc : map.values()) {
        final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountMN = amountCreditMN.add(amountDebitMN);
        final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit()
                : BigDecimal.ZERO;
        final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit()
                : BigDecimal.ZERO;
        final BigDecimal amountME = amountCreditME.add(amountDebitME);
        if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) {
            ImportDetails.LOG.info(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)",
                    doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN);
        } else {
            ImportDetails.LOG.error(
                    "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'",
                    doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN,
                    amountMN);
        }

        final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance);
        insert.add(CIAccounting.TransactionOpeningBalance.Date, _date);
        final StringBuilder descBldr = new StringBuilder()
                .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento")
                .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ")
                .append(doc.getDate()).append(" - ").append(doc.getDesc());

        insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString());
        insert.add(CIAccounting.TransactionOpeningBalance.Status,
                Status.find(CIAccounting.TransactionStatus.Open));
        insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst);
        insert.executeWithoutAccessCheck();

        if (_docMap != null) {
            final Instance instance = insert.getInstance();
            new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance());
        }

        final Map<String, Account> accounts = doc.getAccounts();
        final Instance basCur = Currency.getBaseCurrency();
        for (final Account acc : accounts.values()) {
            final Insert insertpos = new Insert(
                    acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit
                            : CIAccounting.TransactionPositionDebit);
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }

        if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) {
            Insert insertpos = null;
            Account acc = null;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT);
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT);
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0
                && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) {
            Insert insertpos = null;
            final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT);
            ;
            if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) {
                acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate());
                acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate());
                insertpos = new Insert(CIAccounting.TransactionPositionDebit);
            } else {
                acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN));
                acc.addAmountME(amountDebitME.abs().subtract(amountCreditME));
                insertpos = new Insert(CIAccounting.TransactionPositionCredit);
            }
            insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance());
            insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN());
            insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur);
            insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME());
            insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1);
            insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance());
            insertpos.executeWithoutAccessCheck();
        }
    }

    return ret;
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();/*w w  w . ja  v  a 2s .c o m*/
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}