Example usage for java.text DecimalFormat parse

List of usage examples for java.text DecimalFormat parse

Introduction

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

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a number.

Usage

From source file:org.efaps.esjp.accounting.transaction.FieldUpdate_Base.java

/**
 * Executed on update event of the currency field.
 * @param _parameter    parameter as passed from the eFaps API
 * @return  list of maps as needed by the update event
 * @throws EFapsException on error/*ww w .ja  v a2s  .co  m*/
 */
public Return update4Currency(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");

        final String[] currIds = _parameter.getParameterValues("rateCurrencyLink_" + postfix);
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);

        final int pos = getSelectedRow(_parameter);

        final ExchangeConfig exConf = getExchangeConfig(_parameter, null);
        final DateTime date;
        switch (exConf) {
        case DOCDATEPURCHASE:
        case DOCDATESALE:
            final Instance docInst = Instance.get(_parameter.getParameterValues("docLink_" + postfix)[pos]);
            if (InstanceUtils.isValid(docInst)) {
                final PrintQuery print = CachedPrintQuery.get4Request(docInst);
                print.addAttribute(CIERP.DocumentAbstract.Date);
                print.execute();
                date = print.getAttribute(CIERP.DocumentAbstract.Date);
            } else {
                final String dateStr = _parameter.getParameterValue("date_eFapsDate");
                date = DateUtil.getDateFromParameter(dateStr);
            }
            break;
        case TRANSDATESALE:
        case TRANSDATEPURCHASE:
        default:
            final String dateStr = _parameter.getParameterValue("date_eFapsDate");
            date = DateUtil.getDateFromParameter(dateStr);
            break;
        }

        final boolean sale = ExchangeConfig.TRANSDATESALE.equals(exConf)
                || ExchangeConfig.DOCDATESALE.equals(exConf);

        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);
        final RateInfo rate = evaluateRate(_parameter, periodInstance, date,
                Instance.get(CIERP.Currency.getType(), currIds[pos]));
        final DecimalFormat rateFormater = sale ? rate.getFormatter().getFrmt4SaleRateUI()
                : rate.getFormatter().getFrmt4RateUI();
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amountRate = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);

        final BigDecimal sum = getSum4UI(_parameter, postfix, pos, rate);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final List<Map<String, String>> list = new ArrayList<>();
        final Map<String, String> map = new HashMap<>();
        map.put("rate_" + postfix, sale ? rate.getSaleRateUIFrmt() : rate.getRateUIFrmt());
        map.put("rate_" + postfix + RateUI.INVERTEDSUFFIX, "" + rate.isInvert());
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix, formater.format(amountRate.setScale(12)
                .divide(sale ? rate.getSaleRate() : rate.getRate(), BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        ret.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:nl.nn.adapterframework.parameters.Parameter.java

public void configure() throws ConfigurationException {
    if (StringUtils.isNotEmpty(getXpathExpression()) || StringUtils.isNotEmpty(styleSheetName)) {
        if (paramList != null) {
            paramList.configure();//from w  w w  .jav  a  2s.c o  m
        }
        String outputType = TYPE_XML.equalsIgnoreCase(getType()) || TYPE_NODE.equalsIgnoreCase(getType())
                || TYPE_DOMDOC.equalsIgnoreCase(getType()) ? "xml" : "text";
        boolean includeXmlDeclaration = false;

        transformerPool = TransformerPool.configureTransformer0("Parameter [" + getName() + "] ", classLoader,
                getNamespaceDefs(), getXpathExpression(), styleSheetName, outputType, includeXmlDeclaration,
                paramList, isXslt2());
    } else {
        if (paramList != null && StringUtils.isEmpty(getXpathExpression())) {
            throw new ConfigurationException("Parameter [" + getName()
                    + "] can only have parameters itself if a styleSheetName or xpathExpression is specified");
        }
    }
    if (isRemoveNamespaces()) {
        String removeNamespaces_xslt = XmlUtils.makeRemoveNamespacesXslt(true, false);
        try {
            transformerPoolRemoveNamespaces = new TransformerPool(removeNamespaces_xslt);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException("Got error creating transformer from removeNamespaces", te);
        }
    }
    if (TYPE_DATE.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_DATE_PATTERN);
    }
    if (TYPE_DATETIME.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_DATETIME_PATTERN);
    }
    if (TYPE_TIMESTAMP.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_TIMESTAMP_PATTERN);
    }
    if (TYPE_TIME.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_TIME_PATTERN);
    }
    if (TYPE_NUMBER.equals(getType())) {
        decimalFormatSymbols = new DecimalFormatSymbols();
        if (StringUtils.isNotEmpty(getDecimalSeparator())) {
            decimalFormatSymbols.setDecimalSeparator(getDecimalSeparator().charAt(0));
        }
        if (StringUtils.isNotEmpty(getGroupingSeparator())) {
            decimalFormatSymbols.setGroupingSeparator(getGroupingSeparator().charAt(0));
        }
    }
    configured = true;

    if (getMinInclusive() != null || getMaxInclusive() != null) {
        if (!TYPE_NUMBER.equals(getType())) {
            throw new ConfigurationException(
                    "minInclusive and minInclusive only allowed in combination with type [" + TYPE_NUMBER
                            + "]");
        }
        if (getMinInclusive() != null) {
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                minInclusive = df.parse(getMinInclusive());
            } catch (ParseException e) {
                throw new ConfigurationException(
                        "Attribute [minInclusive] could not parse result [" + getMinInclusive()
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
        }
        if (getMaxInclusive() != null) {
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                maxInclusive = df.parse(getMaxInclusive());
            } catch (ParseException e) {
                throw new ConfigurationException(
                        "Attribute [maxInclusive] could not parse result [" + getMinInclusive()
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
        }
    }
}

From source file:org.sparkcommerce.openadmin.server.service.persistence.module.provider.BasicFieldPersistenceProvider.java

@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return FieldProviderResponse.NOT_HANDLED;
    }//from   w w w.j a v  a  2  s  .  c  o m
    boolean dirty = false;
    try {
        Property prop = populateValueRequest.getProperty();
        Object origValue = populateValueRequest.getFieldManager().getFieldValue(instance, prop.getName());
        switch (populateValueRequest.getMetadata().getFieldType()) {
        case BOOLEAN:
            boolean v = Boolean.valueOf(populateValueRequest.getRequestedValue());
            prop.setOriginalValue(String.valueOf(origValue));
            prop.setOriginalDisplayValue(prop.getOriginalValue());
            try {
                dirty = checkDirtyState(populateValueRequest, instance, v);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), v);
            } catch (IllegalArgumentException e) {
                char c = v ? 'Y' : 'N';
                dirty = checkDirtyState(populateValueRequest, instance, c);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), c);
            }
            break;
        case DATE:
            Date date = (Date) populateValueRequest.getFieldManager().getFieldValue(instance,
                    populateValueRequest.getProperty().getName());
            String oldValue = null;
            if (date != null) {
                oldValue = populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(date);
            }
            prop.setOriginalValue(oldValue);
            prop.setOriginalDisplayValue(prop.getOriginalValue());
            dirty = !StringUtils.equals(oldValue, populateValueRequest.getRequestedValue());
            populateValueRequest.getFieldManager().setFieldValue(instance,
                    populateValueRequest.getProperty().getName(), populateValueRequest.getDataFormatProvider()
                            .getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue()));
            break;
        case DECIMAL:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);

                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
                format.setParseBigDecimal(false);
            } else {
                Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter()
                        .parse(populateValueRequest.getRequestedValue()).doubleValue();
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
            }
            break;
        case MONEY:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
                format.setParseBigDecimal(true);
            } else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter()
                        .parse(populateValueRequest.getRequestedValue()).doubleValue();
                dirty = checkDirtyState(populateValueRequest, instance, val);
                LOG.warn("The requested Money field is of type double and could result in a loss of precision."
                        + " Spark recommends that the type of all Money fields are 'BigDecimal' in order to avoid"
                        + " this loss of precision that could occur.");
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
            } else {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), new Money(val));
                format.setParseBigDecimal(false);
            }
            break;
        case INTEGER:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (int.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Integer.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Integer.valueOf(populateValueRequest.getRequestedValue()));
            } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Byte.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Byte.valueOf(populateValueRequest.getRequestedValue()));
            } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Short.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Short.valueOf(populateValueRequest.getRequestedValue()));
            } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Long.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Long.valueOf(populateValueRequest.getRequestedValue()));
            }
            break;
        case CODE:
            // **NOTE** We want to fall through in this case, do not break.
            setNonDisplayableValues(populateValueRequest);
        case STRING:
        case HTML_BASIC:
        case HTML:
        case EMAIL:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
            populateValueRequest.getFieldManager().setFieldValue(instance,
                    populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
            break;
        case FOREIGN_KEY: {
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
            }
            Serializable foreignInstance;
            if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                foreignInstance = null;
            } else {
                if (SupportedFieldType.INTEGER.toString()
                        .equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    Long.valueOf(populateValueRequest.getRequestedValue()));
                } else {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    populateValueRequest.getRequestedValue());
                }
            }

            if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Collection collection;
                try {
                    collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance,
                            populateValueRequest.getProperty().getName());
                } catch (FieldNotAvailableException e) {
                    throw new IllegalArgumentException(e);
                }
                if (!collection.contains(foreignInstance)) {
                    collection.add(foreignInstance);
                    dirty = true;
                }
            } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), foreignInstance);
            }
            break;
        }
        case ADDITIONAL_FOREIGN_KEY: {
            Serializable foreignInstance;
            if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                foreignInstance = null;
            } else {
                if (SupportedFieldType.INTEGER.toString()
                        .equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    Long.valueOf(populateValueRequest.getRequestedValue()));
                } else {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    populateValueRequest.getRequestedValue());
                }
            }

            // Best guess at grabbing the original display value
            String fkProp = populateValueRequest.getMetadata().getForeignKeyDisplayValueProperty();
            Object origDispVal = null;
            if (origValue != null) {
                if (AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY.equals(fkProp)) {
                    if (origValue instanceof AdminMainEntity) {
                        origDispVal = ((AdminMainEntity) origValue).getMainEntityName();
                    }
                } else {
                    origDispVal = populateValueRequest.getFieldManager().getFieldValue(origValue, fkProp);
                }
            }
            if (origDispVal != null) {
                prop.setOriginalDisplayValue(String.valueOf(origDispVal));
                Session session = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                        .getStandardEntityManager().unwrap(Session.class);
                prop.setOriginalValue(String.valueOf(session.getIdentifier(foreignInstance)));
            }

            if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Collection collection;
                try {
                    collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance,
                            populateValueRequest.getProperty().getName());
                } catch (FieldNotAvailableException e) {
                    throw new IllegalArgumentException(e);
                }
                if (!collection.contains(foreignInstance)) {
                    collection.add(foreignInstance);
                    dirty = true;
                }
            } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), foreignInstance);
            }
            break;
        }
        case ID:
            if (populateValueRequest.getSetId()) {
                switch (populateValueRequest.getMetadata().getSecondaryType()) {
                case INTEGER:
                    dirty = checkDirtyState(populateValueRequest, instance,
                            Long.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance,
                            populateValueRequest.getProperty().getName(),
                            Long.valueOf(populateValueRequest.getRequestedValue()));
                    break;
                case STRING:
                    dirty = checkDirtyState(populateValueRequest, instance,
                            populateValueRequest.getRequestedValue());
                    populateValueRequest.getFieldManager().setFieldValue(instance,
                            populateValueRequest.getProperty().getName(),
                            populateValueRequest.getRequestedValue());
                    break;
                }
            }
            break;
        }
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return FieldProviderResponse.HANDLED;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.provider.BasicFieldPersistenceProvider.java

@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return FieldProviderResponse.NOT_HANDLED;
    }//from   ww w  . jav  a2  s. c o  m
    boolean dirty = false;
    try {
        Property prop = populateValueRequest.getProperty();
        Object origValue = populateValueRequest.getFieldManager().getFieldValue(instance, prop.getName());
        switch (populateValueRequest.getMetadata().getFieldType()) {
        case BOOLEAN:
            boolean v = Boolean.valueOf(populateValueRequest.getRequestedValue());
            prop.setOriginalValue(String.valueOf(origValue));
            prop.setOriginalDisplayValue(prop.getOriginalValue());
            try {
                dirty = checkDirtyState(populateValueRequest, instance, v);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), v);
            } catch (IllegalArgumentException e) {
                char c = v ? 'Y' : 'N';
                dirty = checkDirtyState(populateValueRequest, instance, c);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), c);
            }
            break;
        case DATE:
            Date date = (Date) populateValueRequest.getFieldManager().getFieldValue(instance,
                    populateValueRequest.getProperty().getName());
            String oldValue = null;
            if (date != null) {
                oldValue = populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().format(date);
            }
            prop.setOriginalValue(oldValue);
            prop.setOriginalDisplayValue(prop.getOriginalValue());
            dirty = !StringUtils.equals(oldValue, populateValueRequest.getRequestedValue());
            populateValueRequest.getFieldManager().setFieldValue(instance,
                    populateValueRequest.getProperty().getName(), populateValueRequest.getDataFormatProvider()
                            .getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue()));
            break;
        case DECIMAL:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);

                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
                format.setParseBigDecimal(false);
            } else {
                Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter()
                        .parse(populateValueRequest.getRequestedValue()).doubleValue();
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
            }
            break;
        case MONEY:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
                format.setParseBigDecimal(true);
            } else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Double val = populateValueRequest.getDataFormatProvider().getDecimalFormatter()
                        .parse(populateValueRequest.getRequestedValue()).doubleValue();
                dirty = checkDirtyState(populateValueRequest, instance, val);
                LOG.warn("The requested Money field is of type double and could result in a loss of precision."
                        + " Broadleaf recommends that the type of all Money fields are 'BigDecimal' in order to avoid"
                        + " this loss of precision that could occur.");
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), val);
            } else {
                DecimalFormat format = populateValueRequest.getDataFormatProvider().getDecimalFormatter();
                format.setParseBigDecimal(true);
                BigDecimal val = (BigDecimal) format.parse(populateValueRequest.getRequestedValue());
                dirty = checkDirtyState(populateValueRequest, instance, val);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), new Money(val));
                format.setParseBigDecimal(false);
            }
            break;
        case INTEGER:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            if (int.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Integer.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Integer.valueOf(populateValueRequest.getRequestedValue()));
            } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Byte.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Byte.valueOf(populateValueRequest.getRequestedValue()));
            } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Short.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Short.valueOf(populateValueRequest.getRequestedValue()));
            } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType())
                    || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                dirty = checkDirtyState(populateValueRequest, instance,
                        Long.valueOf(populateValueRequest.getRequestedValue()));
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(),
                        Long.valueOf(populateValueRequest.getRequestedValue()));
            }
            break;
        case CODE:
            // **NOTE** We want to fall through in this case, do not break.
            setNonDisplayableValues(populateValueRequest);
        case STRING:
        case HTML_BASIC:
        case HTML:
        case EMAIL:
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
                prop.setOriginalDisplayValue(prop.getOriginalValue());
            }
            dirty = checkDirtyState(populateValueRequest, instance, populateValueRequest.getRequestedValue());
            populateValueRequest.getFieldManager().setFieldValue(instance,
                    populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue());
            break;
        case FOREIGN_KEY: {
            if (origValue != null) {
                prop.setOriginalValue(String.valueOf(origValue));
            }
            Serializable foreignInstance;
            if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                foreignInstance = null;
            } else {
                if (SupportedFieldType.INTEGER.toString()
                        .equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    Long.valueOf(populateValueRequest.getRequestedValue()));
                } else {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    populateValueRequest.getRequestedValue());
                }
            }

            if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Collection collection;
                try {
                    collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance,
                            populateValueRequest.getProperty().getName());
                } catch (FieldNotAvailableException e) {
                    throw new IllegalArgumentException(e);
                }
                if (!collection.contains(foreignInstance)) {
                    collection.add(foreignInstance);
                    dirty = true;
                }
            } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), foreignInstance);
            }
            break;
        }
        case ADDITIONAL_FOREIGN_KEY: {
            Serializable foreignInstance;
            if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) {
                foreignInstance = null;
            } else {
                if (SupportedFieldType.INTEGER.toString()
                        .equals(populateValueRequest.getMetadata().getSecondaryType().toString())) {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    Long.valueOf(populateValueRequest.getRequestedValue()));
                } else {
                    foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                            .retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()),
                                    populateValueRequest.getRequestedValue());
                }
            }

            // Best guess at grabbing the original display value
            String fkProp = populateValueRequest.getMetadata().getForeignKeyDisplayValueProperty();
            Object origDispVal = null;
            if (origValue != null) {
                if (AdminMainEntity.MAIN_ENTITY_NAME_PROPERTY.equals(fkProp)) {
                    if (origValue instanceof AdminMainEntity) {
                        origDispVal = ((AdminMainEntity) origValue).getMainEntityName();
                    }
                } else {
                    origDispVal = populateValueRequest.getFieldManager().getFieldValue(origValue, fkProp);
                }
            }
            if (origDispVal != null) {
                prop.setOriginalDisplayValue(String.valueOf(origDispVal));
                Session session = populateValueRequest.getPersistenceManager().getDynamicEntityDao()
                        .getStandardEntityManager().unwrap(Session.class);
                prop.setOriginalValue(String.valueOf(session.getIdentifier(foreignInstance)));
            }

            if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                Collection collection;
                try {
                    collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance,
                            populateValueRequest.getProperty().getName());
                } catch (FieldNotAvailableException e) {
                    throw new IllegalArgumentException(e);
                }
                if (!collection.contains(foreignInstance)) {
                    collection.add(foreignInstance);
                    dirty = true;
                }
            } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) {
                throw new IllegalArgumentException("Map structures are not supported for foreign key fields.");
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, foreignInstance);
                populateValueRequest.getFieldManager().setFieldValue(instance,
                        populateValueRequest.getProperty().getName(), foreignInstance);
            }
            break;
        }
        case ID:
            if (populateValueRequest.getSetId()) {
                switch (populateValueRequest.getMetadata().getSecondaryType()) {
                case INTEGER:
                    dirty = checkDirtyState(populateValueRequest, instance,
                            Long.valueOf(populateValueRequest.getRequestedValue()));
                    populateValueRequest.getFieldManager().setFieldValue(instance,
                            populateValueRequest.getProperty().getName(),
                            Long.valueOf(populateValueRequest.getRequestedValue()));
                    break;
                case STRING:
                    dirty = checkDirtyState(populateValueRequest, instance,
                            populateValueRequest.getRequestedValue());
                    populateValueRequest.getFieldManager().setFieldValue(instance,
                            populateValueRequest.getProperty().getName(),
                            populateValueRequest.getRequestedValue());
                    break;
                }
            }
            break;
        }
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return FieldProviderResponse.HANDLED;
}

From source file:org.efaps.esjp.assets.LifecycleCostAbstract_Base.java

protected void createCost(final Parameter _parameter) throws EFapsException {
    // Sales-Configuration
    final Instance baseCurrInst = Currency.getBaseCurrency();

    final Instance rateCurrInst = _parameter.getParameterValue("rateCurrencyLink") == null ? baseCurrInst
            : Instance.get(CIERP.Currency.getType(), _parameter.getParameterValue("rateCurrencyLink"));

    final Object[] rateObj = new BigDecimal[] { BigDecimal.ONE, BigDecimal.ONE };
    final BigDecimal rate = ((BigDecimal) rateObj[0]).divide((BigDecimal) rateObj[1], 12,
            BigDecimal.ROUND_HALF_UP);

    final DecimalFormat format = getFormatInstance();
    final Insert insert = new Insert(getType4CostCreate(_parameter));
    insert.add(CIAssets.LifecycleCostAbstract.AssetLinkAbstract, _parameter.getInstance().getId());
    insert.add(CIAssets.LifecycleCostAbstract.RateCurrencyLink, rateCurrInst.getId());
    insert.add(CIAssets.LifecycleCostAbstract.CurrencyLink, baseCurrInst.getId());
    insert.add(CIAssets.LifecycleCostAbstract.Rate, rateObj);

    final String date = _parameter
            .getParameterValue(getFieldName4Attribute(_parameter, CIAssets.LifecycleCostAbstract.Date.name));
    if (date != null) {
        insert.add(CIAssets.LifecycleCostAbstract.Date, date);
    }/*w w  w. j  a v a  2 s.  co m*/

    final String rateAmountStr = _parameter.getParameterValue(
            getFieldName4Attribute(_parameter, CIAssets.LifecycleCostAbstract.RateAmount.name));
    if (rateAmountStr != null) {
        try {
            final BigDecimal rateAmount = (BigDecimal) format.parse(rateAmountStr);
            insert.add(CIAssets.LifecycleCostAbstract.RateAmount, rateAmount);
            insert.add(CIAssets.LifecycleCostAbstract.Amount,
                    rateAmount.setScale(8, BigDecimal.ROUND_HALF_UP).divide(rate, BigDecimal.ROUND_HALF_UP));
        } catch (final ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    insert.execute();
}

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  ww  w .j av a 2  s. c om
        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:com.brq.wallet.external.cashila.activity.CashilaNewFragment.java

private BigDecimal getAmount() {
    DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance(mbw.getLocale());
    BigDecimal amount;//from   w  w w.j av a 2  s  . com

    try {
        String amountText = etAmount.getText().toString();
        if (Strings.isNullOrEmpty(amountText)) {
            return null;
        }

        char decimalSeparator = numberFormat.getDecimalFormatSymbols().getDecimalSeparator();

        // the num entry on (some?) android defaults to "." as decimal separator, no matter
        // what locale the user has chosen
        if (decimalSeparator == '.') {
            amountText = amountText.replace(',', decimalSeparator);
        } else {
            amountText = amountText.replace('.', decimalSeparator);
        }

        amount = new BigDecimal(numberFormat.parse(amountText).doubleValue());
    } catch (ParseException e) {
        new Toaster(getActivity()).toast(getResources().getString(R.string.cashila_amount_not_valid), true);
        return null;
    }
    return amount;
}

From source file:org.efaps.esjp.accounting.transaction.Transaction_Base.java

/**
 * @param _parameter Parameter as passed from eFaps API
 * @param _instance insatcne to be checked
 * @param _amounts  amounts to be checked
 * @return true if valid else false//from w w w .java 2  s  .c  o  m
 * @throws EFapsException on error
 */
protected boolean validateAmounts4EditTransactionPos(final Parameter _parameter, final Instance _instance,
        final String... _amounts) throws EFapsException {
    final DecimalFormat formatter = NumberFormatter.get().getFormatter(null, 2);

    boolean ret = true;

    if (_amounts != null && _amounts.length > 0) {
        for (final String amountStr : _amounts) {
            try {
                final BigDecimal amount = (BigDecimal) formatter.parse(amountStr);
                if (CIAccounting.TransactionPositionCredit.getType().equals(_instance.getType())) {
                    if (amount.signum() < 0) {
                        ret = false;
                        break;
                    }
                } else if (CIAccounting.TransactionPositionDebit.getType().equals(_instance.getType())) {
                    if (amount.signum() > 0) {
                        ret = false;
                        break;
                    }
                }
            } catch (final ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    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.j a  va 2 s.  com
        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);
    }
}

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

protected List<Account> readAccounts4SaldoConcar(final File _file) throws IOException, ParseException {
    final List<Account> ret = new ArrayList<>();
    final BufferedReader in = new BufferedReader(new FileReader(_file));
    final CSVReader reader = new CSVReader(in);
    final List<String[]> rows = reader.readAll();
    reader.close();/*from   w w w .  j av  a 2  s . c o  m*/
    final Pattern accPattern = Pattern.compile("^[\\d ]*");
    final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
    formater.setParseBigDecimal(true);
    //        final DecimalFormatSymbols frmSym = DecimalFormatSymbols.getInstance();
    //        frmSym.setDecimalSeparator(",".toCharArray()[0]);
    //        frmSym.setPatternSeparator(".".toCharArray()[0]);
    //        formater.setDecimalFormatSymbols(frmSym);

    for (final String[] row : rows) {
        final String accStr = row[0];
        if (!accStr.isEmpty() && accPattern.matcher(accStr).matches()) {
            final Account acc = new Account();
            ret.add(acc);
            acc.setName(accStr.trim());
            final String amountMEDebit = row[10];
            final String amountMECredit = row[11];
            final String amountMNDebit = row[12];
            final String amountMNCredit = row[13];
            if (!amountMEDebit.isEmpty()) {
                acc.setAmountME(((BigDecimal) formater.parse(amountMEDebit)).negate());
            }
            if (!amountMECredit.isEmpty()) {
                acc.setAmountME((BigDecimal) formater.parse(amountMECredit));
            }
            if (!amountMNDebit.isEmpty()) {
                acc.setAmountMN(((BigDecimal) formater.parse(amountMNDebit)).negate());
            }
            if (!amountMNCredit.isEmpty()) {
                acc.setAmountMN((BigDecimal) formater.parse(amountMNCredit));
            }
            ConSis.LOG.info("Read Account {} - Rate: {}", acc, acc.getRate());
        }
    }
    return ret;
}