Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

In this page you can find the example usage for java.lang NumberFormatException NumberFormatException.

Prototype

public NumberFormatException(String s) 

Source Link

Document

Constructs a NumberFormatException with the specified detail message.

Usage

From source file:com.doitnext.http.router.responsehandlers.DefaultErrorHandlerTest.java

@Test
public void testHandleValidStatusCode() throws IOException {
    DefaultErrorHandler h = new DefaultErrorHandler();
    Exception responseData = new IllegalArgumentException("Hidey Ho!!", new NumberFormatException("3r3"));
    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setStatus(403);/*from   w w  w  . j a  va  2s .  co m*/
    boolean handled = h.handleResponse(null, null, response, responseData);
    Assert.assertTrue(handled);
    Assert.assertEquals(403, response.getStatus());
}

From source file:de.codesourcery.eve.skills.ui.components.impl.PriceInfoComponent.java

protected double getValue(JTextField input) throws NumberFormatException {
    final String value = input.getText();
    if (StringUtils.isBlank(value)) {
        throw new NumberFormatException("You need to enter a positive number");
    }/*  w  w w.jav  a  2 s. com*/

    final double val = Double.parseDouble(value);
    if (val < 0) {
        throw new NumberFormatException("You need to enter a positive number");
    }
    return val;

}

From source file:org.diorite.utils.math.RomanNumeral.java

public RomanNumeral(final int arabic, final boolean valid) {
    if (valid && (arabic < 0)) {
        throw new NumberFormatException("Value of RomanNumeral must be positive.");
    }/*from   ww w .  j  a v  a2s .  co m*/
    if (valid && (arabic > 3999)) {
        throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
    }
    this.num = arabic;
}

From source file:org.diorite.commons.math.RomanNumeral.java

public RomanNumeral(int arabic, boolean valid) {
    if (valid && (arabic < 0)) {
        throw new NumberFormatException("Value of RomanNumeral must be positive.");
    }//  w w  w. ja v  a2s  .  c  om
    if (valid && (arabic > 3999)) {
        throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
    }
    this.num = arabic;
}

From source file:Main.java

/**
 * Parse an integer located between 2 given offsets in a string
 *
 * @param value      the string to parse
 * @param beginIndex the start index for the integer in the string
 * @param endIndex   the end index for the integer in the string
 * @return the int//w  ww  . j  a  va2 s. c o  m
 * @throws NumberFormatException if the value is not a number
 */
private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
    if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
        throw new NumberFormatException(value);
    }
    // use same logic as in Integer.parseInt() but less generic we're not supporting negative values
    int i = beginIndex;
    int result = 0;
    int digit;
    if (i < endIndex) {
        digit = Character.digit(value.charAt(i++), 10);
        if (digit < 0) {
            throw new NumberFormatException("Invalid number: " + value);
        }
        result = -digit;
    }
    while (i < endIndex) {
        digit = Character.digit(value.charAt(i++), 10);
        if (digit < 0) {
            throw new NumberFormatException("Invalid number: " + value);
        }
        result *= 10;
        result -= digit;
    }
    return -result;
}

From source file:org.openhab.binding.isy.ISYActiveBindingConfig.java

/**
 * Creates a new instance of the Active Binding configuration for work with
 * a ISY unit.//from   w  w  w.  j  a  va 2s .c  o m
 *
 * @param config
 *            map of configuration items.
 */
public ISYActiveBindingConfig(Map<Object, Object> config) {

    this.logger.info(
            "openHAB Binding Configuration(refresh='{}',upnp='{}',uuid='{}',ip='{}',port='{}',user='{}')",
            config.get("refresh"), config.get("upnp"), config.get("uuid"), config.get("ip"), config.get("port"),
            config.get("user"));

    if (isNotBlank((String) config.get("refresh"))) {
        refreshInterval = Long.parseLong((String) config.get("refresh"));
    }

    if (isNotBlank((String) config.get("user")) && isNotBlank((String) config.get("password"))) {
        this.user = (String) config.get("user");
        this.password = (String) config.get("password");
    } else {
        this.logger.warn("No user/password specified");
    }

    if (isNotBlank((String) config.get("upnp"))) {
        useUpnp = Boolean.parseBoolean((String) config.get("upnp"));
    }

    if (!useUpnp && isNotBlank((String) config.get("uuid")) && isNotBlank((String) config.get("ip"))
            && isNotBlank((String) config.get("port"))) {

        this.uuid = (String) config.get("uuid");
        this.ipAddress = (String) config.get("ip");

        try {
            this.port = Integer.parseInt((String) config.get("port"));
        } catch (NumberFormatException ne) {
            this.logger.warn("Not a valid port number");
            throw new RuntimeException("Not a valid port number", ne);
        }

        if (this.port < 0 || this.port > 65535) {
            this.logger.warn("Port out of range (0-65535)");
            throw new NumberFormatException("Invalid port");
        }

    } else {
        this.logger.info("Using UPNP for ISY connection.");
    }
}

From source file:Main.java

/**
 * <p>Turns a string value into a java.lang.Number.</p>
 *
 * <p>First, the value is examined for a type qualifier on the end
 * (<code>'f','F','d','D','l','L'</code>).  If it is found, it starts 
 * trying to create successively larger types from the type specified
 * until one is found that can hold the value.</p>
 *
 * <p>If a type specifier is not found, it will check for a decimal point
 * and then try successively larger types from <code>Integer</code> to
 * <code>BigInteger</code> and from <code>Float</code> to
 * <code>BigDecimal</code>.</p>
 *
 * <p>If the string starts with <code>0x</code> or <code>-0x</code>, it
 * will be interpreted as a hexadecimal integer.  Values with leading
 * <code>0</code>'s will not be interpreted as octal.</p>
 *
 * @param val String containing a number
 * @return Number created from the string
 * @throws NumberFormatException if the value cannot be converted
 *///from  w w  w . ja  v a  2 s .  c  o m
public static Number createNumber(String val) throws NumberFormatException {
    if (val == null) {
        return null;
    }
    if (val.length() == 0) {
        throw new NumberFormatException("\"\" is not a valid number.");
    }
    if (val.startsWith("--")) {
        // this is protection for poorness in java.lang.BigDecimal.
        // it accepts this as a legal value, but it does not appear 
        // to be in specification of class. OS X Java parses it to 
        // a wrong value.
        return null;
    }
    if (val.startsWith("0x") || val.startsWith("-0x")) {
        return createInteger(val);
    }
    char lastChar = val.charAt(val.length() - 1);
    String mant;
    String dec;
    String exp;
    int decPos = val.indexOf('.');
    int expPos = val.indexOf('e') + val.indexOf('E') + 1;

    if (decPos > -1) {

        if (expPos > -1) {
            if (expPos < decPos) {
                throw new NumberFormatException(val + " is not a valid number.");
            }
            dec = val.substring(decPos + 1, expPos);
        } else {
            dec = val.substring(decPos + 1);
        }
        mant = val.substring(0, decPos);
    } else {
        if (expPos > -1) {
            mant = val.substring(0, expPos);
        } else {
            mant = val;
        }
        dec = null;
    }
    if (!Character.isDigit(lastChar)) {
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length() - 1);
        } else {
            exp = null;
        }
        //Requesting a specific type..
        String numeric = val.substring(0, val.length() - 1);
        boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
        switch (lastChar) {
        case 'l':
        case 'L':
            if (dec == null && exp == null
                    && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
                try {
                    return createLong(numeric);
                } catch (NumberFormatException nfe) {
                    //Too big for a long
                }
                return createBigInteger(numeric);

            }
            throw new NumberFormatException(val + " is not a valid number.");
        case 'f':
        case 'F':
            try {
                Float f = createFloat(numeric);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    //If it's too big for a float or the float value = 0 and the string
                    //has non-zeros in it, then float does not have the precision we want
                    return f;
                }

            } catch (NumberFormatException e) {
                // ignore the bad number
            }
            //Fall through
        case 'd':
        case 'D':
            try {
                Double d = createDouble(numeric);
                if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createBigDecimal(numeric);
            } catch (NumberFormatException e) {
                // empty catch
            }
            //Fall through
        default:
            throw new NumberFormatException(val + " is not a valid number.");

        }
    } else {
        //User doesn't have a preference on the return type, so let's start
        //small and go from there...
        if (expPos > -1 && expPos < val.length() - 1) {
            exp = val.substring(expPos + 1, val.length());
        } else {
            exp = null;
        }
        if (dec == null && exp == null) {
            //Must be an int,long,bigint
            try {
                return createInteger(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                return createLong(val);
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            return createBigInteger(val);

        } else {
            //Must be a float,double,BigDec
            boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
            try {
                Float f = createFloat(val);
                if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {
                    return f;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }
            try {
                Double d = createDouble(val);
                if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {
                    return d;
                }
            } catch (NumberFormatException nfe) {
                // empty catch
            }

            return createBigDecimal(val);

        }

    }
}

From source file:co.cask.cdap.gateway.util.Util.java

/**
 * Convert a hexadecimal string into a byte array.
 *
 * @param hex The string to convert/*from   w w  w. j a  v  a2  s .  c o m*/
 * @return the byte array value of the String
 * @throws NumberFormatException if the string is ill-formed
 */
public static byte[] hexValue(String hex) {
    // verify the length of the string
    if (hex.length() % 2 != 0) {
        throw new NumberFormatException("Hex string must have even length.");
    }
    byte[] bytes = new byte[hex.length() / 2];
    for (int i = 0; i < bytes.length; ++i) {
        byte hi = hexValue(hex.charAt(2 * i));
        byte lo = hexValue(hex.charAt(2 * i + 1));
        bytes[i] = (byte) (((hi << 4) & 0xF0) | lo);
    }
    return bytes;
}

From source file:org.apache.nifi.cluster.coordination.node.LeaderElectionNodeProtocolSender.java

@Override
protected InetSocketAddress getServiceAddress() throws IOException {
    final String address = electionManager.getLeader(ClusterRoles.CLUSTER_COORDINATOR);

    if (StringUtils.isEmpty(address)) {
        throw new NoClusterCoordinatorException(
                "No node has yet been elected Cluster Coordinator. Cannot establish connection to cluster yet.");
    }/* w  w w  .j  a  v  a  2  s.c  o  m*/

    final String[] splits = address.split(":");
    if (splits.length != 2) {
        final String message = String.format(
                "Attempted to determine Cluster Coordinator address. Zookeeper indicates "
                        + "that address is %s, but this is not in the expected format of <hostname>:<port>",
                address);
        logger.error(message);
        throw new ProtocolException(message);
    }

    logger.info(
            "Determined that Cluster Coordinator is located at {}; will use this address for sending heartbeat messages",
            address);

    final String hostname = splits[0];
    final int port;
    try {
        port = Integer.parseInt(splits[1]);
        if (port < 1 || port > 65535) {
            throw new NumberFormatException("Port must be in the range of 1 - 65535 but got " + port);
        }
    } catch (final NumberFormatException nfe) {
        final String message = String
                .format("Attempted to determine Cluster Coordinator address. Zookeeper indicates "
                        + "that address is %s, but the port is not a valid port number", address);
        logger.error(message);
        throw new ProtocolException(message);
    }

    final InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(hostname, port);
    return socketAddress;
}

From source file:moe.encode.airblock.commands.arguments.types.PrimitiveParser.java

@Override
public Object convert(Executor executor, ArgumentConverter parser, Type type, String value) {
    Class<?> cls = ReflectionUtils.toClass(type);
    if (ClassUtils.isPrimitiveWrapper(cls))
        cls = ClassUtils.wrapperToPrimitive(cls);

    if (cls.equals(boolean.class))
        return this.isTrue(executor, value);
    else if (cls.equals(char.class)) {
        if (value.length() > 0)
            throw new NumberFormatException("Character arguments cannot be longer than one characters");
        return value.charAt(0);
    }//from w w w.j av a 2  s.  co m

    // Get the locale of the user and get a number-format according to it.
    LocaleResolver resolver = TranslationManager.getResolver(executor);
    Locale locale;
    if (resolver != null)
        locale = resolver.getLocale();
    else
        locale = Locale.ENGLISH;

    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    nf.setGroupingUsed(true);

    // Parse the value.
    Number result;
    try {
        result = nf.parse(value);
    } catch (ParseException e) {
        NumberFormatException nfe = new NumberFormatException("Invalid number");
        nfe.initCause(e);
        throw nfe;
    }

    // Returns the value in the correct type.
    if (cls.equals(int.class))
        return result.intValue();
    else if (cls.equals(float.class))
        return result.floatValue();
    else if (cls.equals(double.class))
        return result.doubleValue();
    else if (cls.equals(byte.class))
        return result.byteValue();
    else if (cls.equals(short.class))
        return result.shortValue();
    else if (cls.equals(long.class))
        return result.longValue();

    throw new NumberFormatException("Unknown primitive type.");
}