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:net.stuxcrystal.simpledev.commands.arguments.ArgumentList.java

/**
 * Returns the converted argument at the given index.<p />
 *
 * The index argument has some additional features: If the index is greater or equals 0 the default
 * Java&trade;-Indexing of Arrays. If the index is under zero, the index is counted from
 * the last item on.<p />//from   w w w. j a  va 2 s. c o m
 *
 * If the given argument was not found or couldn't be converted, null will be returned. If the
 * given class is the Class-instance for a primitive type, a NumberFormatException will be thrown
 * if the number couldn't be parsed.
 *
 * @param index The index of the argument.
 * @param cls   The type of the argument.
 * @return The argument passed to the command.
 * @throws NumberFormatException          If the parsing of the argument failed.
 * @throws IllegalArgumentException       The given type is not supported.
 * @throws ArrayIndexOutOfBoundsException If the index is invalid.
 */
@Override
@SuppressWarnings("unchecked")
public <T> T get(int index, Class<? extends T> cls) {
    Class<?> clazz = cls;

    int preIndex = index;
    index = this.getRealIndex(index);
    if (index == -1)
        throw new IndexOutOfBoundsException(this.outOfBoundsMsg(preIndex));

    // Make the Class-Instance the Class-Reference to the Wrapper-Type.
    if (clazz.isPrimitive()) {
        clazz = PrimitiveType.wrap((Class<?>) cls);
    }

    // Use the current argument handler.
    ArgumentHandler handler = this.handler.getArgumentHandler();

    // Make sure the handler supports the given type.
    if (!handler.supportsType(clazz)) {
        throw new NumberFormatException("Unsupported type: " + cls);
    }

    // Convert and return the specified result.
    return (T) handler.convertType(arguments[index], clazz, this.executor, this.handler.getServerBackend());
}

From source file:org.osaf.cosmo.eim.schema.text.TriageStatusFormat.java

public Object parseObject(String source, ParsePosition pos) {
    if (pos.getIndex() > 0)
        return null;

    int index = 0;

    String[] chunks = source.split(" ", 3);
    if (chunks.length != 3) {
        parseException = new ParseException("Incorrect number of chunks: " + chunks.length, 0);
        pos.setErrorIndex(index);//from w  w  w  . j a va2  s.c  om
        return null;
    }

    TriageStatus ts = entityFactory.createTriageStatus();

    try {
        pos.setIndex(index);
        Integer code = new Integer(chunks[0]);
        // validate the code as being known
        TriageStatusUtil.label(code);
        ts.setCode(code);
        index += chunks[0].length() + 1;
    } catch (Exception e) {
        parseException = new ParseException(e.getMessage(), 0);
        pos.setErrorIndex(index);
        return null;
    }

    try {
        pos.setIndex(index);
        BigDecimal rank = new BigDecimal(chunks[1]);
        if (rank.scale() != 2)
            throw new NumberFormatException("Invalid rank value " + chunks[1]);
        ts.setRank(rank);
        index += chunks[1].length() + 1;
    } catch (NumberFormatException e) {
        parseException = new ParseException(e.getMessage(), 0);
        pos.setErrorIndex(index);
        return null;
    }

    if (chunks[2].equals(AUTOTRIAGE_ON))
        ts.setAutoTriage(Boolean.TRUE);
    else if (chunks[2].equals(AUTOTRIAGE_OFF))
        ts.setAutoTriage(Boolean.FALSE);
    else {
        parseException = new ParseException("Invalid autotriage value " + chunks[2], 0);
        pos.setErrorIndex(index);
        return null;
    }
    index += chunks[2].length();

    pos.setIndex(index);

    return ts;
}

From source file:org.rapidpm.microservice.optionals.service.ServiceWrapper.java

private static String getRestPortFromFile() throws IOException {
    List<String> lines = Files.readAllLines(MICROSERVICE_REST_FILE, Charset.defaultCharset());
    if (lines.size() != 1) {
        throw new NumberFormatException("File does not contain a number. It is empty");
    }/*from  w ww  . j a v a2  s. co  m*/
    return lines.get(0);
}

From source file:DateTime.java

/**
 * Parses an RFC 3339 date/time value./*from   ww  w.  j av a2  s .c o m*/
 */
public static DateTime parseRfc3339(String str) throws NumberFormatException {
    try {
        Calendar dateTime = new GregorianCalendar(GMT);
        int year = Integer.parseInt(str.substring(0, 4));
        int month = Integer.parseInt(str.substring(5, 7)) - 1;
        int day = Integer.parseInt(str.substring(8, 10));
        int tzIndex;
        int length = str.length();
        boolean dateOnly = length <= 10 || Character.toUpperCase(str.charAt(10)) != 'T';
        if (dateOnly) {
            dateTime.set(year, month, day);
            tzIndex = 10;
        } else {
            int hourOfDay = Integer.parseInt(str.substring(11, 13));
            int minute = Integer.parseInt(str.substring(14, 16));
            int second = Integer.parseInt(str.substring(17, 19));
            dateTime.set(year, month, day, hourOfDay, minute, second);
            if (str.charAt(19) == '.') {
                int milliseconds = Integer.parseInt(str.substring(20, 23));
                dateTime.set(Calendar.MILLISECOND, milliseconds);
                tzIndex = 23;
            } else {
                tzIndex = 19;
            }
        }
        Integer tzShiftInteger = null;
        long value = dateTime.getTimeInMillis();
        if (length > tzIndex) {
            int tzShift;
            if (Character.toUpperCase(str.charAt(tzIndex)) == 'Z') {
                tzShift = 0;
            } else {
                tzShift = Integer.parseInt(str.substring(tzIndex + 1, tzIndex + 3)) * 60
                        + Integer.parseInt(str.substring(tzIndex + 4, tzIndex + 6));
                if (str.charAt(tzIndex) == '-') {
                    tzShift = -tzShift;
                }
                value -= tzShift * 60000;
            }
            tzShiftInteger = tzShift;
        }
        return new DateTime(dateOnly, value, tzShiftInteger);
    } catch (StringIndexOutOfBoundsException e) {
        throw new NumberFormatException("Invalid date/time format.");
    }
}

From source file:org.openmrs.module.hospitalcore.web.controller.PatientSearchController.java

private List<Patient> filterPatients(HttpServletRequest request, List<Patient> patients)
        throws NumberFormatException, ParseException {

    List<Patient> filteredPatients = patients;

    // filter using gender
    String genderCriterion = request.getParameter("gender");
    if (!StringUtils.isBlank(genderCriterion)) {
        filteredPatients = select(filteredPatients, new GenderMatcher(new String(genderCriterion)));
    }/*from   w ww  .ja va2  s  .  c om*/

    // filter using age criteria
    String ageCriterion = request.getParameter("age");
    if (!StringUtils.isBlank(ageCriterion)) {
        String ageRange = request.getParameter("ageRange");
        try {
            filteredPatients = select(filteredPatients,
                    new AgeMatcher(new Integer(ageCriterion), new Integer(ageRange)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new NumberFormatException("advancesearch.error.age");
        }
    }

    // filter using relative name
    String relativeNameCriterion = request.getParameter("relativeName");
    if (!StringUtils.isBlank(relativeNameCriterion)) {
        filteredPatients = select(filteredPatients, new RelativeNameMatcher(relativeNameCriterion));
    }

    // filter using date of visit
    String dateCriterion = request.getParameter("date");
    if (!StringUtils.isBlank(dateCriterion)) {
        try {
            String dateRange = request.getParameter("dateRange");
            filteredPatients = select(filteredPatients, new DateMatcher(dateCriterion, new Integer(dateRange)));
        } catch (Exception e) {
            e.printStackTrace();
            throw new NumberFormatException("advancesearch.error.date");
        }
    }

    return filteredPatients;
}

From source file:org.duracloud.durastore.rest.StorageStatsRest.java

protected Date toDateFromMs(String endMs) throws NumberFormatException {
    try {/*from ww w . ja va2  s  . com*/
        return new Date(Long.parseLong(endMs));
    } catch (NumberFormatException ex) {
        throw new NumberFormatException(
                "Unable to parse date: " + endMs + ". Input value must be in epoch milliseconds.");
    }
}

From source file:de.inpiraten.jdemocrator.TAN.generator.TANGenerator.java

public void generateMasterTANs() throws IOException {
    //Read seed from System.in
    System.out.println("You will be asked to specify a random seed. Please enter a number of random");
    System.out.println("characters to your liking. This will help to seed a secure random number");
    System.out.println("generator which will generate the master TANs for every vote and derive the");
    System.out.println("TANs. The longer your seed the stronger your master TANs.");
    System.out.print("\nEnter the seed for the TAN generator.\n> ");
    String seed = commandLineInput.readLine();
    SecureRandom random = new SecureRandom(
            ArrayUtils.addAll(seed.getBytes(), ("" + System.currentTimeMillis()).getBytes()));

    //Get length of master TANs
    int masterTANlength = -1;
    while (masterTANlength < 6) {
        System.out.print("\nPlease enter the length of the master TANs in bytes. (Standard: 18)\n>");
        int input;
        try {// ww w  . j  a va2  s . c  o m
            input = inputInteger();
            if (input > 5) {
                masterTANlength = input;
            } else if (input > 0) {
                System.out
                        .println("Lengths shorter than 6 byte are too insecure. Please chose another length.");
            } else if (input == 0) {
                masterTANlength = 18; //standard option
            } else
                throw new NumberFormatException("Length of master TAN must be positive");
        } catch (NumberFormatException e) {
            System.out.println("Invalid input. Please try again.");
        }
    }

    this.masterTAN = new String[this.event.numberOfElections];
    byte[] rawTAN = new byte[masterTANlength];
    for (int i = 0; i < this.masterTAN.length; i++) {
        random.nextBytes(rawTAN);
        this.masterTAN[i] = Base64.encodeBase64String(rawTAN);
    }
}

From source file:com.github.ikidou.handler.BlogHandler.java

public long getId(Request request) {
    String id = request.params("id");
    String idInQueryString = request.queryParams("id");

    if (id == null && idInQueryString == null) {
        return -1;
    } else if (id == null) {
        id = idInQueryString;//ww  w  .j a  va 2 s . c  om
    }
    try {
        return Long.parseLong(id);
    } catch (NumberFormatException e) {
        throw new NumberFormatException("bad id:`" + id + "`");
    }
}

From source file:UUID.java

/**
 * Constructor for creating UUIDs from the canonical string representation
 * /*www. j a  v a2 s. c o  m*/
 * Note that implementation is optimized for speed, not necessarily code
 * clarity... Also, since what we get might not be 100% canonical (see
 * below), let's not yet populate mDesc here.
 * 
 * @param id
 *            String that contains the canonical representation of the UUID
 *            to build; 36-char string (see UUID specs for details).
 *            Hex-chars may be in upper-case too; UUID class will always
 *            output them in lowercase.
 */
public UUID(String id) throws NumberFormatException {
    if (id == null) {
        throw new NullPointerException();
    }
    if (id.length() != 36) {
        throw new NumberFormatException("UUID has to be represented by the standard 36-char representation");
    }

    for (int i = 0, j = 0; i < 36; ++j) {
        // Need to bypass hyphens:
        switch (i) {
        case 8:
        case 13:
        case 18:
        case 23:
            if (id.charAt(i) != '-') {
                throw new NumberFormatException(
                        "UUID has to be represented by the standard 36-char representation");
            }
            ++i;
        }
        char c = id.charAt(i);

        if (c >= '0' && c <= '9') {
            mId[j] = (byte) ((c - '0') << 4);
        } else if (c >= 'a' && c <= 'f') {
            mId[j] = (byte) ((c - 'a' + 10) << 4);
        } else if (c >= 'A' && c <= 'F') {
            mId[j] = (byte) ((c - 'A' + 10) << 4);
        } else {
            throw new NumberFormatException("Non-hex character '" + c + "'");
        }

        c = id.charAt(++i);

        if (c >= '0' && c <= '9') {
            mId[j] |= (byte) (c - '0');
        } else if (c >= 'a' && c <= 'f') {
            mId[j] |= (byte) (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
            mId[j] |= (byte) (c - 'A' + 10);
        } else {
            throw new NumberFormatException("Non-hex character '" + c + "'");
        }
        ++i;
    }
}

From source file:com.alibaba.napoli.metamorphosis.utils.DiamondUtils.java

/**
 * ?brokerId0:num0;brokerId1:num1;...?partition list
 * *//*www  .  ja v  a  2  s .com*/
static List<Partition> parsePartitions(final String value) {
    final String[] brokerNums = StringUtils.split(value, ";");

    if (brokerNums == null || brokerNums.length == 0) {
        return Collections.emptyList();
    }

    final List<Partition> ret = new LinkedList<Partition>();
    for (String brokerNum : brokerNums) {
        brokerNum = trim(brokerNum, ";", 0);
        final int index = brokerNum.indexOf(":");
        if (index < 0) {
            throw new NumberFormatException("?,config string=" + value);
        }
        final int brokerId = Integer.parseInt(brokerNum.substring(0, index));
        final int num = Integer.parseInt(brokerNum.substring(index + 1));
        if (num <= 0) {
            throw new NumberFormatException("0,config string=" + value);
        }
        for (int i = 0; i < num; i++) {
            ret.add(new Partition(brokerId, i));
        }
    }
    Collections.sort(ret);
    return ret;
}