Example usage for java.text NumberFormat setParseIntegerOnly

List of usage examples for java.text NumberFormat setParseIntegerOnly

Introduction

In this page you can find the example usage for java.text NumberFormat setParseIntegerOnly.

Prototype

public void setParseIntegerOnly(boolean value) 

Source Link

Document

Sets whether or not numbers should be parsed as integers only.

Usage

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to an int primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)/*from   w w  w.  j  av  a 2 s.co m*/
 *@return the converted Integer value.
 */
public static Integer formatInt(String value, Locale locale) {
    Integer result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a long primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)//from w w  w . j av  a  2 s  .c  o m
 *@return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = new Long(num.longValue());
            }
        }
    }

    return result;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a byte primitive.
 * //from www.j  a v  a 2s .  co m
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Byte value.
 */
public static Byte formatByte(String value, Locale locale) {
    Byte result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Byte.MIN_VALUE && num.doubleValue() <= Byte.MAX_VALUE) {
                result = new Byte(num.byteValue());
            }
        }
    }

    return result;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a short primitive.
 * /*from   w  w  w.  j a  v  a 2s .c om*/
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)vv
 * @return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to an int primitive.
 * //from   www  . j  ava 2 s.  c  om
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Integer value.
 */
public static Integer formatInt(String value, Locale locale) {
    Integer result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a long primitive.
 * /*from  w  w  w. j  av a 2s  . co  m*/
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = new Long(num.longValue());
            }
        }
    }

    return result;
}

From source file:com.haulmont.chile.core.datatypes.impl.IntegerDatatype.java

@Override
protected Number parse(String value, NumberFormat format) throws ParseException {
    format.setParseIntegerOnly(true);

    Number result = super.parse(value, format);
    if (!hasValidIntegerRange(result)) {
        throw new ParseException(String.format("Integer range exceeded: \"%s\"", value), 0);
    }//from   w ww.ja  va2 s  . c o  m
    return result;
}

From source file:com.haulmont.chile.core.datatypes.impl.LongDatatype.java

@Override
protected Number parse(String value, NumberFormat format) throws ParseException {
    format.setParseIntegerOnly(true);

    Number result = super.parse(value, format);
    if (!hasValidLongRange(result)) {
        throw new ParseException(String.format("Integer range exceeded: \"%s\"", value), 0);
    }//from ww  w .  j  ava  2  s  .c  o m
    return result;
}

From source file:org.dataone.proto.trove.mn.rest.v1.ExceptionController.java

@RequestMapping(value = "/{errorId}", method = RequestMethod.GET)
public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable String errorId)
        throws NotFound, ServiceFailure, NotImplemented, InvalidRequest, InvalidCredentials, NotAuthorized,
        AuthenticationTimeout, InsufficientResources {

    int status = 500;
    log.info("received error of " + errorId);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setParseIntegerOnly(true);
    try {//from w  w w .  j  a  va  2s. c o m
        Number nstatus = nf.parse(errorId);
        status = nstatus.intValue();
    } catch (ParseException ex) {
        throw new ServiceFailure("500", "Could not determine the server error thrown");
    }
    response.setStatus(status);
    switch (status) {
    case 400: {
        throw new InvalidRequest("400",
                "Bad Request: The request could not be understood by the server due to malformed syntax.");
    }
    case 401: {
        throw new InvalidCredentials("401", "Unauthorized: The request requires user authentication.");
    }
    case 403: {
        throw new NotAuthorized("403",
                "Forbidden: The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.");
    }
    case 404: {
        throw new NotFound("404", "Not Found: The server has not found anything matching the Request-URI.");
    }
    case 405: {
        throw new InvalidRequest("405",
                "Method Not Allowed: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.");
    }
    case 406: {
        throw new InvalidRequest("406",
                "Not Acceptable: The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.");
    }
    case 407: {
        throw new NotAuthorized("407",
                "Proxy Authentication Required: The client must first authenticate itself with the proxy.");
    }
    case 408: {
        throw new AuthenticationTimeout("408",
                "Request Timeout: The client did not produce a request within the time that the server was prepared to wait.");
    }
    case 409: {
        throw new InvalidRequest("409",
                "Conflict: The request could not be completed due to a conflict with the current state of the resource.");
    }
    case 410: {
        throw new NotFound("410",
                "Gone: The requested resource is no longer available at the server and no forwarding address is known.");
    }
    case 411: {
        throw new InvalidRequest("411",
                "Length Required: The server refuses to accept the request without a defined Content-Length.");
    }
    case 412: {
        throw new InvalidRequest("412",
                "Precondition Failed: The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.");
    }
    case 413: {
        throw new InsufficientResources("413",
                "Request Entity Too Large: The server is refusing to process a request because the request entity is larger than the server is willing or able to process.");
    }
    case 414: {
        throw new InvalidRequest("414",
                "Request-URI Too Long: The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret.");
    }
    case 415: {
        throw new InvalidRequest("415",
                "Unsupported Media Type: The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.");
    }
    case 416: {
        throw new InvalidRequest("416",
                "Requested Range Not Satisfiable: A server SHOULD return a response with this status code if a request included a Range request-header field.");
    }
    case 417: {
        throw new InvalidRequest("417",
                "Expectation Failed: The expectation given in an Expect request-header field could not be met by this server.");
    }
    case 500: {
        throw new ServiceFailure("500",
                "Internal Server Error: The server encountered an unexpected condition which prevented it from fulfilling the request.");
    }
    case 501: {
        throw new NotImplemented("501",
                "Not Implemented: The server does not support the functionality required to fulfill the request.");
    }
    case 502: {
        throw new ServiceFailure("502",
                "Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.");
    }
    case 503: {
        throw new ServiceFailure("503",
                "Service Unavailable: The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.");
    }
    case 504: {
        throw new ServiceFailure("504",
                "Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.");
    }
    case 505: {
        throw new ServiceFailure("505",
                "HTTP Version Not Supported: The server does not support, or refuses to support, the HTTP protocol version that was used in the request message.");
    }
    default: {
        throw new ServiceFailure("500", "Could not determine the server error thrown");
    }
    }

    //            this.writeToResponse(errorXml.getInputStream(), response.getOutputStream());
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

/**
 * Converts the input as a number using java's number formatter to a string output.
 *///from  w w  w  .j  av a 2s  .  c o m
private String doConvertFromNumberToString(Map<String, Object> context, Object value, Class toType) {
    // XW-409: If the input is a Number we should format it to a string using the choosen locale and use java's numberformatter
    if (Number.class.isAssignableFrom(toType)) {
        NumberFormat numFormat = NumberFormat.getInstance(getLocale(context));
        if (isIntegerType(toType)) {
            numFormat.setParseIntegerOnly(true);
        }
        numFormat.setGroupingUsed(true);
        numFormat.setMaximumFractionDigits(99); // to be sure we include all digits after decimal seperator, otherwise some of the fractions can be chopped

        String number = numFormat.format(value);
        if (number != null) {
            return number;
        }
    }

    return null; // no number
}