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: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 om
    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;
    }//ww  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."
                        + " 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:thesis.Ontology_System.java

public String commaMaker(String price) {

    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    String pattern = "#,##0.0#";
    DecimalFormat df = new DecimalFormat(pattern, symbols);
    df.setParseBigDecimal(true);

    /*price = proposed.replaceAll(Pattern.quote(","),"");
    equi = equi.replaceAll(Pattern.quote(","),"");
    other = other.replaceAll(Pattern.quote(","),"");
            /*from  ww w  . ja v a  2s . c  om*/
    if("".equals(proposed)){proposed = "0";}
    if("".equals(equi)){equi = "0";}
    if("".equals(other)){other = "0";}*/

    BigDecimal price_i = new BigDecimal(price);

    /*      BigDecimal equi_i = new BigDecimal(equi);
    BigDecimal other_i = new BigDecimal(other);
    BigDecimal total = new BigDecimal("0");
            
    total = total.add(proposed_i);
    total = total.add(equi_i);
    total = total.add(other_i);
    */
    return df.format(price_i);

}

From source file:net.pms.util.Rational.java

/**
 * Parses the specified {@link String} and returns a {@link BigDecimal}
 * using the specified {@link DecimalFormat}. {@code value} is expected to
 * be without leading or trailing whitespace. If {@code value} is blank,
 * {@code null} will be returned.//from ww w  .  j  a v a2 s.co  m
 *
 * @param value the {@link String} to parse.
 * @param decimalFormat the {@link DecimalFormat} to use when parsing.
 * @return The resulting {@link BigDecimal}.
 * @throws NumberFormatException If {@code value} cannot be parsed.
 */
@Nullable
public static BigDecimal parseBigDecimal(@Nullable String value, @Nullable DecimalFormat decimalFormat) {
    if (StringUtils.isBlank(value)) {
        return null;
    }

    if (decimalFormat != null) {
        decimalFormat.setParseBigDecimal(true);
        try {
            return (BigDecimal) decimalFormat.parseObject(value);
        } catch (ParseException e) {
            throw new NumberFormatException("Unable to parse \"" + value + "\": " + e.getMessage());
        }
    }
    return new BigDecimal(value);
}

From source file:org.ohmage.domain.campaign.Campaign.java

/**
 * Processes a hours-before-now prompt and returns a HoursBeforeNowPrompt
 * object./*from ww w  .ja v  a  2 s .  c o m*/
 * 
 * @param id The prompt's unique identifier.
 * 
 * @param condition The condition value.
 * 
 * @param unit The prompt's visualization unit.
 * 
 * @param text The prompt's text value.
 * 
 * @param explanationText The prompt's explanation text value.
 * 
 * @param skippable Whether or not this prompt is skippable.
 * 
 * @param skipLabel The label to show to skip this prompt.
 * 
 * @param displayLabel The label for this display type.
 * 
 * @param defaultValue The default value given in the XML.
 * 
 * @param properties The properties defined in the XML for this prompt.
 * 
 * @param index The index of this prompt in its collection of survey items.
 * 
 * @return A HoursBeforeNowPrompt object.
 * 
 * @throws DomainException Thrown if the required properties are missing or
 *                      if any of the parameters are invalid.
 */
private static HoursBeforeNowPrompt processHoursBeforeNow(final String id, final String condition,
        final String unit, final String text, final String explanationText, final boolean skippable,
        final String skipLabel, final String displayLabel, final String defaultValue,
        final Map<String, LabelValuePair> properties, final int index) throws DomainException {

    // Create the decimal parser.
    DecimalFormat format = new DecimalFormat();
    format.setParseBigDecimal(true);

    BigDecimal min;
    try {
        LabelValuePair minVlp = properties.get(HoursBeforeNowPrompt.XML_KEY_MIN);

        if (minVlp == null) {
            throw new DomainException("Missing the '" + HoursBeforeNowPrompt.XML_KEY_MIN + "' property: " + id);
        }

        min = (BigDecimal) format.parse(minVlp.getLabel());
    } catch (ParseException e) {
        throw new DomainException(
                "The '" + HoursBeforeNowPrompt.XML_KEY_MIN + "' property is not a valid number: " + id, e);
    }

    BigDecimal max;
    try {
        LabelValuePair maxVlp = properties.get(HoursBeforeNowPrompt.XML_KEY_MAX);

        if (maxVlp == null) {
            throw new DomainException("Missing the '" + HoursBeforeNowPrompt.XML_KEY_MAX + "' property: " + id);
        }

        max = (BigDecimal) format.parse(maxVlp.getLabel());
    } catch (ParseException e) {
        throw new DomainException(
                "The '" + HoursBeforeNowPrompt.XML_KEY_MAX + "' property is not valid number: " + id, e);
    }

    BigDecimal parsedDefaultValue = null;
    try {
        if (defaultValue != null) {
            parsedDefaultValue = (BigDecimal) format.parse(defaultValue);
        }
    } catch (ParseException e) {
        throw new DomainException("The default value is not a valid number: " + id);
    }

    return new HoursBeforeNowPrompt(id, condition, unit, text, explanationText, skippable, skipLabel,
            displayLabel, min, max, parsedDefaultValue, index);
}

From source file:org.ohmage.domain.campaign.Campaign.java

/**
 * Processes a number prompt and returns a NumberPrompt object.
 * /*  w  w w  . j  av  a  2  s  .c o m*/
 * @param id The prompt's unique identifier.
 * 
 * @param condition The condition value.
 * 
 * @param unit The prompt's visualization unit.
 * 
 * @param text The prompt's text value.
 * 
 * @param explanationText The prompt's explanation text value.
 * 
 * @param skippable Whether or not this prompt is skippable.
 * 
 * @param skipLabel The label to show to skip this prompt.
 * 
 * @param displayLabel The label for this display type.
 * 
 * @param defaultValue The default value given in the XML.
 * 
 * @param properties The properties defined in the XML for this prompt.
 * 
 * @param index The index of this prompt in its collection of survey items.
 * 
 * @return A NumberPrompt object.
 * 
 * @throws DomainException Thrown if the required properties are missing or
 *                      if any of the parameters are invalid.
 */
private static NumberPrompt processNumber(final String id, final String condition, final String unit,
        final String text, final String explanationText, final boolean skippable, final String skipLabel,
        final String displayLabel, final String defaultValue, final Map<String, LabelValuePair> properties,
        final int index) throws DomainException {

    // Create the decimal parser.
    DecimalFormat format = new DecimalFormat();
    format.setParseBigDecimal(true);

    BigDecimal min;
    try {
        LabelValuePair minVlp = properties.get(NumberPrompt.XML_KEY_MIN);

        if (minVlp == null) {
            throw new DomainException("Missing the '" + NumberPrompt.XML_KEY_MIN + "' property: " + id);
        }

        min = (BigDecimal) format.parse(minVlp.getLabel());
    } catch (ParseException e) {
        throw new DomainException(
                "The '" + NumberPrompt.XML_KEY_MIN + "' property is not a valid number: " + id, e);
    }

    BigDecimal max;
    try {
        LabelValuePair maxVlp = properties.get(NumberPrompt.XML_KEY_MAX);

        if (maxVlp == null) {
            throw new DomainException("Missing the '" + NumberPrompt.XML_KEY_MAX + "' property: " + id);
        }

        max = (BigDecimal) format.parse(maxVlp.getLabel());
    } catch (ParseException e) {
        throw new DomainException("The '" + NumberPrompt.XML_KEY_MAX + "' property is not valid number: " + id,
                e);
    }

    BigDecimal parsedDefaultValue = null;
    try {
        if (defaultValue != null) {
            parsedDefaultValue = (BigDecimal) format.parse(defaultValue);
        }
    } catch (ParseException e) {
        throw new DomainException("The default value is not a valid number: " + id);
    }

    Boolean wholeNumber = null;
    LabelValuePair wholeNumberVlp = properties.get(NumberPrompt.XML_KEY_WHOLE_NUMBER);

    if (wholeNumberVlp != null) {
        wholeNumber = StringUtils.decodeBoolean(wholeNumberVlp.getLabel());
        if (wholeNumber == null) {
            throw new DomainException(
                    "The '" + NumberPrompt.XML_KEY_WHOLE_NUMBER + "' property is not a valid boolean: " + id);
        }
    }

    return new NumberPrompt(id, condition, unit, text, explanationText, skippable, skipLabel, displayLabel, min,
            max, parsedDefaultValue, index, wholeNumber);
}

From source file:org.nd4j.linalg.factory.Nd4j.java

/**
 * Read line via input streams/*from w  w w.ja  v a  2  s.  c  om*/
 *
 * @param ndarray the input stream ndarray
 * @param  sep character, defaults to ","
 * @return NDArray
 */
public static INDArray readTxtString(InputStream ndarray, String sep) {
    /*
     We could dump an ndarray to a file with the tostring (since that is valid json) and use put/get to parse it as json
            
     But here we leverage our information of the tostring method to be more efficient
     With our current toString format we use tads along dimension (rank-1,rank-2) to write to the array in two dimensional chunks at a time.
     This is more efficient than setting each value at a time with putScalar.
     This also means we can read the file one line at a time instead of loading the whole thing into memory
            
     Future work involves enhancing the write json method to provide more features to make the load more efficient
    */
    int lineNum = 0;
    int rowNum = 0;
    int tensorNum = 0;
    char theOrder = 'c';
    int[] theShape = { 1, 1 };
    int rank = 0;
    double[][] subsetArr = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    INDArray newArr = Nd4j.zeros(2, 2);
    BufferedReader reader = new BufferedReader(new InputStreamReader(ndarray));
    LineIterator it = IOUtils.lineIterator(reader);
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    format.setParseBigDecimal(true);
    try {
        while (it.hasNext()) {
            String line = it.nextLine();
            lineNum++;
            line = line.replaceAll("\\s", "");
            if (line.equals("") || line.equals("}"))
                continue;
            // is it from dl4j?
            if (lineNum == 2) {
                String[] lineArr = line.split(":");
                String fileSource = lineArr[1].replaceAll("\\W", "");
                if (!fileSource.equals("dl4j"))
                    return null;
            }
            // parse ordering
            if (lineNum == 3) {
                String[] lineArr = line.split(":");
                theOrder = lineArr[1].replaceAll("\\W", "").charAt(0);
                continue;
            }
            // parse shape
            if (lineNum == 4) {
                String[] lineArr = line.split(":");
                String dropJsonComma = lineArr[1].split("]")[0];
                String[] shapeString = dropJsonComma.replace("[", "").split(",");
                rank = shapeString.length;
                theShape = new int[rank];
                for (int i = 0; i < rank; i++) {
                    try {
                        theShape[i] = Integer.parseInt(shapeString[i]);
                    } catch (NumberFormatException nfe) {
                    }
                    ;
                }
                subsetArr = new double[theShape[rank - 2]][theShape[rank - 1]];
                newArr = Nd4j.zeros(theShape, theOrder);
                continue;
            }
            //parse data
            if (lineNum > 5) {
                String[] entries = line.replace("\\],", "").replaceAll("\\[", "").replaceAll("\\],", "")
                        .replaceAll("\\]", "").split(sep);
                for (int i = 0; i < theShape[rank - 1]; i++) {
                    try {
                        BigDecimal number = (BigDecimal) format.parse(entries[i]);
                        subsetArr[rowNum][i] = number.doubleValue();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                rowNum++;
                if (rowNum == theShape[rank - 2]) {
                    INDArray subTensor = Nd4j.create(subsetArr);
                    newArr.tensorAlongDimension(tensorNum, rank - 1, rank - 2).addi(subTensor);
                    rowNum = 0;
                    tensorNum++;
                }
            }
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
    return newArr;
}