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.dashbuilder.dataprovider.backend.csv.CSVParser.java

protected Object parseValue(DataColumn column, String value) throws Exception {
    ColumnType type = column.getColumnType();
    try {//from  www . ja v a  2  s .  co  m
        if (type.equals(ColumnType.DATE)) {
            DateFormat dateFormat = getDateFormat(column.getId());
            return dateFormat.parse(value);
        } else if (type.equals(ColumnType.NUMBER)) {
            DecimalFormat numberFormat = getNumberFormat(column.getId());
            return numberFormat.parse(value).doubleValue();
        } else {
            return value;
        }
    } catch (ParseException e) {
        String msg = "Error parsing value: " + value + ", " + e.getMessage()
                + ". Check column\u0027s data type consistency!";
        throw new Exception(msg);
    }
}

From source file:org.dashbuilder.dataprovider.csv.CSVParser.java

protected ColumnType calculateType(String columnId, String value) {
    DataColumnDef column = dataSetDef.getColumnById(columnId);
    if (column != null)
        return column.getColumnType();

    try {//from   w  w w  . ja  v  a 2s  . c om
        DateFormat dateFormat = getDateFormat(columnId);
        dateFormat.parse(value);
        return ColumnType.DATE;
    } catch (Exception e) {
        try {
            DecimalFormat numberFormat = getNumberFormat(columnId);
            numberFormat.parse(value);
            return ColumnType.NUMBER;
        } catch (Exception ee) {
            return ColumnType.LABEL;
        }
    }
}

From source file:org.dashbuilder.dataprovider.csv.CSVParser.java

protected Object parseValue(DataColumn column, String value) throws Exception {
    ColumnType type = column.getColumnType();
    try {/*from w  w w . j  a v a 2  s .  c  o m*/
        if (type.equals(ColumnType.DATE)) {
            String pattern = dataSetDef.getPattern(column.getId());
            // Handle special date pattern "epoch"
            if (pattern != null && DATE_FORMAT_EPOCH.equalsIgnoreCase(pattern)) {
                Double _epoch = Double.parseDouble(value);
                return new Date(_epoch.longValue() * 1000);
            } else {
                DateFormat dateFormat = getDateFormat(column.getId());
                return dateFormat.parse(value);
            }
        } else if (type.equals(ColumnType.NUMBER)) {
            DecimalFormat numberFormat = getNumberFormat(column.getId());
            return numberFormat.parse(value).doubleValue();
        } else {
            return value;
        }
    } catch (ParseException e) {
        String msg = "Error parsing value: " + value + ", " + e.getMessage()
                + ". Check column\u0027s data type consistency!";
        throw new Exception(msg);
    }
}

From source file:thymeleafsandbox.springjsp.web.conversion.NumberFormatter.java

public Number parse(final String text, final Locale locale) throws ParseException {
    final DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance();
    final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
    symbols.setGroupingSeparator('*');
    numberFormat.setDecimalFormatSymbols(symbols);
    return numberFormat.parse(text);
}

From source file:br.com.webbudget.domain.misc.filter.MovementFilter.java

/**
 * Metodo para fazer o parse da nossa criteria em um numero decimal para
 * satisfazer a busca por valor/*from ww  w.  j  ava 2 s .  c o  m*/
 *
 * @return o valor formatador em bigdecimal
 *
 * @throws ParseException se houver algum erro na hora do parse
 */
public BigDecimal criteriaToBigDecimal() throws ParseException {

    final DecimalFormatSymbols symbols = new DecimalFormatSymbols();

    symbols.setGroupingSeparator('.');
    symbols.setDecimalSeparator(',');

    DecimalFormat decimalFormat = new DecimalFormat("#,##0.0#", symbols);
    decimalFormat.setParseBigDecimal(true);

    return (BigDecimal) decimalFormat.parse(this.criteria);
}

From source file:CommonServlets.EditUser.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = null, userName = null, job = null, address = null, password = null, img = null, role = null;
    BigDecimal creditLimit = new BigDecimal(0);

    try {// w  w  w . j  av  a  2 s. c  o  m
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                //processFormField(item);
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equalsIgnoreCase("email")) {
                    email = value;
                } else if (name.equalsIgnoreCase("userName")) {
                    userName = value;
                } else if (name.equalsIgnoreCase("creditLimit")) {
                    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                    symbols.setGroupingSeparator(',');
                    symbols.setDecimalSeparator('.');
                    String pattern = "#,##0.0#";
                    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
                    decimalFormat.setParseBigDecimal(true);
                    creditLimit = (BigDecimal) decimalFormat.parse(value);
                } else if (name.equalsIgnoreCase("job")) {
                    job = value;

                } else if (name.equalsIgnoreCase("address")) {
                    address = value;
                } else if (name.equalsIgnoreCase("password")) {
                    password = value;
                }
            } else if (!item.isFormField() && !item.getName().equals("")) {
                System.out.println(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                item.write(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                img = item.getName();
            }
        }

        User u = new User(email, userName, password, creditLimit, job, address, img, role);
        controlServlet.editUserDate(u);
        HttpSession session = request.getSession(true);
        session.setAttribute("done", "1");
        ControlServlet c = new ControlServlet();
        User myUser = c.getUser(userName);
        session.setAttribute("user", myUser);
        response.sendRedirect("UserHome.jsp");

    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldDefaultValue.java

/**
 * Validate the arguments to the constructor.
 * @return true, if arguments are valid; false otherwise.
 *///from ww  w.java 2s.c om
private boolean validate() {
    boolean isValid = false;
    switch (datatype) {
    case ExtendedFieldDataTypes.STRING:
        isValid = true; // Any kind of string currently accepted.
        break;
    case ExtendedFieldDataTypes.BOOLEAN:
        if (value != null) { // null is never a valid boolean!
            isValid = checkBoolean(value);
        }
        break;
    case ExtendedFieldDataTypes.NUMBER:
        if (value == null || value.length() == 0) { // no value no format check
            isValid = true;
            break;
        }

        if (format != null) {
            if (format.length() == 0) {
                isValid = true;
                break;
            }

            DecimalFormat decimalFormat = new DecimalFormat(format);
            try {
                decimalFormat.parse(value);
                isValid = true;
            } catch (ParseException e) {
                log.debug("Invalid NUMBER: " + value);
            }
        } else {
            isValid = true;
        }
        break;
    case ExtendedFieldDataTypes.TIMESTAMP:
    case ExtendedFieldDataTypes.JSCALENDAR:
        if (value == null || value.length() == 0) { // no value no format check
            isValid = true;
            break;
        }

        if (format != null) {
            if (format.length() == 0) {
                isValid = true;
                break;
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            try {
                dateFormat.parse(value);
                isValid = true;
            } catch (ParseException e) {
                log.debug("Invalid TIMESTAMP: " + value);
            }
        } else {
            isValid = true;
        }
        break;
    case ExtendedFieldDataTypes.NOTE:
        isValid = true; // Any kind of NOTE value currently accepted.
        break;
    case ExtendedFieldDataTypes.SELECT:
        isValid = true; // Any kind of SELECT value currently accepted.
        break;
    default:
        throw new ArgumentNotValid("Unable to validate unknown datatype: " + datatype);
    }

    return isValid;
}

From source file:no.abmu.questionnaire.domain.data.BigDecimalFieldData.java

@Transient
private void setValueAsString(String value) {
    //        logger.debug("Executing setValueAsString as String code=[" +  getCode() + "] value=[" + value + "]");
    if (value == null) {
        if (this.bigDecimalValue != null) {
            this.bigDecimalValue = null;
        }/*from w  w  w .  ja  v a  2s  .  c  om*/
        return;
    }
    String trimmedStringValue = value.trim();
    if (trimmedStringValue.isEmpty()) {
        if (this.bigDecimalValue != null) {
            this.bigDecimalValue = null;
        }
        return;
    }

    if (trimmedStringValue.contains(".")) {
        throw new NumberFormatException("Not valid number, use ',' not '.'");
    }

    DecimalFormat formatter = getNumberFormat();

    BigDecimal newBigDecimal;
    try {
        newBigDecimal = (BigDecimal) formatter.parse(trimmedStringValue);
    } catch (NumberFormatException e) {
        logger.error("Error on converting string value=[" + value + "]", e);
        throw new NumberFormatException(e.toString());
    } catch (ParseException e) {
        logger.error("Error on converting string value=[" + value + "]", e);
        throw new NumberFormatException(e.toString());
    }
    setBigDecimalValue(bigDecimalWithCorrectScaling(newBigDecimal));
}

From source file:de.hybris.platform.acceleratorservices.payment.cybersource.strategies.impl.DefaultCreateSubscriptionRequestStrategy.java

/**
 * Gets the CyberSource setup fee, currently populated by a config value.
 * //from   w  ww.  ja  v  a  2  s . co m
 * @return the CyberSource setup fee amount
 */
protected BigDecimal getSetupFeeAmount() {
    final String configSetupFee = getSiteConfigProperty(CyberSourceConstants.HopProperties.HOP_SETUP_FEE);
    if (configSetupFee != null && !configSetupFee.isEmpty()) {
        try {
            final DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance();
            formatter.setParseBigDecimal(true);
            return (BigDecimal) formatter.parse(configSetupFee);
        } catch (final Exception e) {
            LOG.debug("Error converting to BigDecimal of String value: " + configSetupFee, e);
        }
    }
    return null;
}

From source file:net.sf.webissues.core.WebIssuesTaskDataHandler.java

public static Set<TaskAttribute> updateTaskData(Set<TaskAttribute> changedAttributes, WebIssuesClient client,
        TaskRepository repository, TaskData data, IssueDetails issue, IProgressMonitor monitor)
        throws HttpException, ProtocolException, IOException {
    doDateAttribute(TaskAttribute.DATE_CREATION, data, changedAttributes, issue.getIssue().getCreatedDate());
    doDateAttribute(TaskAttribute.DATE_MODIFICATION, data, changedAttributes,
            issue.getIssue().getModifiedDate());

    IEnvironment environment = WebIssuesCorePlugin.getDefault().getConnector().getClientManager()
            .getClient(repository, monitor).getEnvironment();
    Folder folder = issue.getIssue().getFolder();
    IssueType type = folder.getType();/*  w ww  .ja  va2s.c o  m*/

    // Set the project and folder attributes
    TaskAttribute projectAttribute = data.getRoot().getAttribute(WebIssuesAttribute.PROJECT.getTaskKey());
    TaskAttribute folderAttribute = data.getRoot().getAttribute(WebIssuesAttribute.FOLDER.getTaskKey());
    projectAttribute.setValue(String.valueOf(folder.getProject().getId()));
    rebuildFolders(environment, projectAttribute, data, folderAttribute,
            issue.getIssue().getFolder().getType());
    folderAttribute.setValue(String.valueOf(folder.getId()));

    // Remove all webissues attributes exception project and folder
    for (Iterator<TaskAttribute> attributeIterator = data.getRoot().getAttributes().values()
            .iterator(); attributeIterator.hasNext();) {
        TaskAttribute attr = attributeIterator.next();
        if (attr.getId().startsWith(WEBISSUES_ATTRIBUTE_KEY_PREFIX)) {
            attributeIterator.remove();
        }
    }

    // We might already have a priority attribute
    TaskAttribute priorityAttribute = data.getRoot().getAttribute(TaskAttribute.PRIORITY);

    for (Attribute attr : type.values()) {
        if (!attr.isBuiltIn() && (priorityAttribute == null || !attr.getName().equals("Priority"))) {
            String defaultValue = attr.getDefaultValue();
            String attributeId = WEBISSUES_ATTRIBUTE_KEY_PREFIX + attr.getId();

            // Set as default if nothing set
            String value = issue.getIssue().get(attr);
            if (Util.isNullOrBlank(value)) {
                value = defaultValue;
            }

            // Set up the task attribute
            TaskAttribute taskAttr = data.getRoot().createAttribute(attributeId);
            TaskAttributeMetaData metaData = taskAttr.getMetaData();
            metaData.setKind(TaskAttribute.KIND_DEFAULT);
            switch (attr.getAttributeType()) {
            case DATETIME:
                if (attr.isDateOnly()) {
                    metaData.setType(TaskAttribute.TYPE_DATE);
                } else {
                    metaData.setType(TaskAttribute.TYPE_DATETIME);
                }
                break;
            case TEXT:
                metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
                break;
            case NUMERIC:
                metaData.setType(TaskAttribute.TYPE_SHORT_TEXT);
                break;
            case USER:
                metaData.setType(TaskAttribute.TYPE_PERSON);
                metaData.setKind(TaskAttribute.KIND_PEOPLE);
                metaData.putValue("membersOnly", String.valueOf(attr.isMembersOnly()));
                if ("[Me]".equals(value)) {
                    value = type.getTypes().getEnvironment().getOwnerUser().getName();
                }
                break;
            case ENUM:
                metaData.setType(TaskAttribute.TYPE_SINGLE_SELECT);
                taskAttr.clearOptions();
                if (!attr.isRequired()) {
                    taskAttr.putOption("", "");
                }
                for (String option : attr.getOptions()) {
                    taskAttr.putOption(option, option);
                }
                break;
            }

            // Format the value if it is numeric
            if (attr.getType().equals(Attribute.AttributeType.NUMERIC) && attr.getDecimalPlaces() > 0) {
                DecimalFormat fmt = new DecimalFormat();
                fmt.setMinimumFractionDigits(attr.getDecimalPlaces());
                fmt.setMaximumFractionDigits(attr.getDecimalPlaces());
                taskAttr.setValue(fmt.format(Util.isNullOrBlank(value) ? 0d : Double.parseDouble(value)));
            } else if (attr.getType().equals(Attribute.AttributeType.DATETIME)) {
                DateFormat fmt = new SimpleDateFormat(
                        attr.isDateOnly() ? Client.DATEONLY_FORMAT : Client.DATETIME_FORMAT);
                try {
                    taskAttr.setValue(value == null ? "" : String.valueOf(fmt.parse(value).getTime()));
                } catch (ParseException e) {
                    taskAttr.setValue("");
                }
            } else {
                taskAttr.setValue(Util.nonNull(value));
            }

            metaData.setLabel(attr.getName());
        }
    }

    // Comments
    Collection<Comment> comments = issue.getComments();
    if (comments != null) {
        int count = 1;
        for (Comment comment : comments) {
            String plainText = comment.getText();
            if (Util.isNullOrBlank(plainText)) {
                continue;
            }
            TaskCommentMapper mapper = new TaskCommentMapper();
            User owner = comment.getCreatedUser();
            if (owner != null) {
                mapper.setAuthor(repository.createPerson(owner.getName()));
            }
            mapper.setCreationDate(comment.getCreatedDate().getTime());
            mapper.setText(plainText);
            mapper.setNumber(count);
            TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_COMMENT + count);
            mapper.applyTo(attribute);
            count++;
        }
    }

    Collection<Attachment> attachments = issue.getAttachments();
    int count = 1;
    for (Attachment attachment : attachments) {
        TaskAttachmentMapper mapper = new TaskAttachmentMapper();
        mapper.setAuthor(repository.createPerson(attachment.getCreatedUser().getName()));
        mapper.setDescription(attachment.getDescription());
        mapper.setCreationDate(attachment.getCreatedDate().getTime());
        mapper.setAttachmentId(String.valueOf(attachment.getId()));
        mapper.setFileName(attachment.getName());
        mapper.setUrl(Util.concatenateUri(repository.getRepositoryUrl(), "attachments",
                String.valueOf(attachment.getId())));
        mapper.setLength(Long.valueOf(attachment.getSize()));
        TaskAttribute attribute = data.getRoot().createAttribute(TaskAttribute.PREFIX_ATTACHMENT + count);
        mapper.applyTo(attribute);
        count++;
    }

    count = 1;
    for (Change change : issue.getChanges()) {
        WebIssuesChangeMapper mapper = new WebIssuesChangeMapper();
        mapper.setChangeId(String.valueOf(count));
        mapper.setUser(repository.createPerson(change.getModifiedUser().getName()));
        mapper.setAttributeName(change.getAttribute() == null ? "Name" : change.getAttribute().getName());
        mapper.setType(change.getType());
        mapper.setOldValue(change.getOldValue());
        mapper.setNewValue(change.getNewValue());
        mapper.setDate(change.getModifiedDate());
        TaskAttribute attribute = data.getRoot()
                .createAttribute(WebIssuesChangeMapper.PREFIX_CHANGE + String.valueOf(count));
        mapper.applyTo(attribute);
        count++;
    }

    return changedAttributes;
}