List of usage examples for java.lang NumberFormatException NumberFormatException
public NumberFormatException(String s)
NumberFormatException
with the specified detail message. From source file:org.apache.ws.security.util.XmlSchemaDateFormat.java
/** * This method was snarfed from <tt>org.apache.axis.encoding.ser.CalendarDeserializer</tt>, * which was written by Sam Ruby (rubys@us.ibm.com) and Rich Scheuerle (scheu@us.ibm.com). * Better error reporting was added./* ww w . ja v a2 s. c om*/ * * @see DateFormat#parse(java.lang.String) */ public Date parse(String src, ParsePosition parse_pos) { Date date; // validate fixed portion of format int index = 0; try { if (src != null) { if ((src.charAt(0) == '+') || (src.charAt(0) == '-')) { src = src.substring(1); } if (src.length() < 19) { parse_pos.setIndex(src.length() - 1); handleParseError(parse_pos, "TOO_FEW_CHARS"); } validateChar(src, parse_pos, index = 4, '-', "EXPECTED_DASH"); validateChar(src, parse_pos, index = 7, '-', "EXPECTED_DASH"); validateChar(src, parse_pos, index = 10, 'T', "EXPECTED_CAPITAL_T"); validateChar(src, parse_pos, index = 13, ':', "EXPECTED_COLON_IN_TIME"); validateChar(src, parse_pos, index = 16, ':', "EXPECTED_COLON_IN_TIME"); } // convert what we have validated so far try { synchronized (DATEFORMAT_XSD_ZULU) { date = DATEFORMAT_XSD_ZULU.parse((src == null) ? null : (src.substring(0, 19) + ".000Z")); } } catch (Exception e) { throw new NumberFormatException(e.toString()); } index = 19; // parse optional milliseconds if (src != null) { if ((index < src.length()) && (src.charAt(index) == '.')) { int milliseconds = 0; int start = ++index; while ((index < src.length()) && Character.isDigit(src.charAt(index))) { index++; } String decimal = src.substring(start, index); if (decimal.length() == 3) { milliseconds = Integer.parseInt(decimal); } else if (decimal.length() < 3) { milliseconds = Integer.parseInt((decimal + "000").substring(0, 3)); } else { milliseconds = Integer.parseInt(decimal.substring(0, 3)); if (decimal.charAt(3) >= '5') { ++milliseconds; } } // add milliseconds to the current date date.setTime(date.getTime() + milliseconds); } // parse optional timezone if (((index + 5) < src.length()) && ((src.charAt(index) == '+') || (src.charAt(index) == '-'))) { validateCharIsDigit(src, parse_pos, index + 1, "EXPECTED_NUMERAL"); validateCharIsDigit(src, parse_pos, index + 2, "EXPECTED_NUMERAL"); validateChar(src, parse_pos, index + 3, ':', "EXPECTED_COLON_IN_TIMEZONE"); validateCharIsDigit(src, parse_pos, index + 4, "EXPECTED_NUMERAL"); validateCharIsDigit(src, parse_pos, index + 5, "EXPECTED_NUMERAL"); final int hours = (((src.charAt(index + 1) - '0') * 10) + src.charAt(index + 2)) - '0'; final int mins = (((src.charAt(index + 4) - '0') * 10) + src.charAt(index + 5)) - '0'; int millisecs = ((hours * 60) + mins) * 60 * 1000; // subtract millisecs from current date to obtain GMT if (src.charAt(index) == '+') { millisecs = -millisecs; } date.setTime(date.getTime() + millisecs); index += 6; } if ((index < src.length()) && (src.charAt(index) == 'Z')) { index++; } if (index < src.length()) { handleParseError(parse_pos, "TOO_MANY_CHARS"); } } } catch (ParseException pe) { log.error(pe.toString(), pe); index = 0; // IMPORTANT: this tells DateFormat.parse() to throw a ParseException parse_pos.setErrorIndex(index); date = null; } parse_pos.setIndex(index); return (date); }
From source file:org.openestate.io.core.NumberUtils.java
/** * Convert a string value into a number. * * @param value//from w ww . j a v a2s . c o m * the string value to convert * * @param integerOnly * wether only the integer part of the value is parsed * * @param locales * locales, against which the value is parsed * * @return * numeric value for the string * * @throws NumberFormatException * if the string is not a valid number */ public static Number parseNumber(String value, boolean integerOnly, Locale... locales) throws NumberFormatException { value = StringUtils.trimToNull(value); if (value == null) return null; // ignore leading plus sign if (value.startsWith("+")) value = StringUtils.trimToNull(value.substring(1)); // remove any spaces value = StringUtils.replace(value, StringUtils.SPACE, StringUtils.EMPTY); if (ArrayUtils.isEmpty(locales)) locales = new Locale[] { Locale.getDefault() }; for (Locale locale : locales) { // check, if the value is completely numeric for the locale if (!isNumeric(value, locale)) continue; try { NumberFormat format = NumberFormat.getNumberInstance(locale); format.setMinimumFractionDigits(0); format.setGroupingUsed(false); format.setParseIntegerOnly(integerOnly); return format.parse(value); } catch (ParseException ex) { } } throw new NumberFormatException("The provided value '" + value + "' is not numeric!"); }
From source file:org.intermine.bio.util.OrganismRepository.java
/** * Return an OrganismRepository created from a properties file in the class path. * @return the OrganismRepository/*from www . ja v a2 s . c om*/ */ @SuppressWarnings("unchecked") public static OrganismRepository getOrganismRepository() { if (or == null) { Properties props = new Properties(); try { InputStream propsResource = OrganismRepository.class.getClassLoader() .getResourceAsStream(PROP_FILE); if (propsResource == null) { throw new RuntimeException("can't find " + PROP_FILE + " in class path"); } props.load(propsResource); } catch (IOException e) { throw new RuntimeException("Problem loading properties '" + PROP_FILE + "'", e); } or = new OrganismRepository(); Enumeration<String> propNames = (Enumeration<String>) props.propertyNames(); Pattern pattern = Pattern.compile(REGULAR_EXPRESSION); while (propNames.hasMoreElements()) { String name = propNames.nextElement(); if (name.startsWith(PREFIX)) { Matcher matcher = pattern.matcher(name); if (matcher.matches()) { String taxonIdString = matcher.group(1); int taxonId = Integer.valueOf(taxonIdString).intValue(); String fieldName = matcher.group(2); OrganismData od = or.getOrganismDataByTaxonInternal(taxonId); final String attributeValue = props.getProperty(name); if (fieldName.equals(ABBREVIATION)) { od.setAbbreviation(attributeValue); or.abbreviationMap.put(attributeValue.toLowerCase(), od); } else if (fieldName.equals(STRAINS)) { String[] strains = attributeValue.split(" "); for (String strain : strains) { try { or.strains.put(Integer.valueOf(strain), od); or.organismsWithStrains.put(taxonIdString, strain); } catch (NumberFormatException e) { throw new NumberFormatException("taxon ID must be a number"); } } } else if (fieldName.equals(ENSEMBL)) { od.setEnsemblPrefix(attributeValue); } else if (fieldName.equals(UNIPROT)) { od.setUniprot(attributeValue); uniprotToTaxon.put(attributeValue, od); } else { if (fieldName.equals(SPECIES)) { od.setSpecies(attributeValue); } else { if (fieldName.equals(GENUS)) { od.setGenus(attributeValue); } else { throw new RuntimeException("internal error didn't match: " + fieldName); } } } } else { throw new RuntimeException("unable to parse organism property key: " + name); } } else { throw new RuntimeException("properties in " + PROP_FILE + " must start with " + PREFIX + "."); } } for (OrganismData od : or.taxonMap.values()) { or.genusSpeciesMap.put(new MultiKey(od.getGenus(), od.getSpecies()), od); // we have some organisms from uniprot that don't have a short name if (od.getShortName() != null) { or.shortNameMap.put(od.getShortName(), od); } } } return or; }
From source file:jnode.net.VMInetAddress.java
/** * Parse a string that is supported to b an unsigned byte. * @param str//from w w w. jav a 2 s .c o m * @throws NumberFormatException * @return */ private static byte parseUnsignedByte(String str) { final int v = Integer.parseInt(str); if ((v >= 0) && (v < 256)) { return (byte) v; } else { throw new NumberFormatException(str); } }
From source file:org.cesecore.util.TimeUnitFormat.java
/** * Parses a formatted time string.// w ww . j av a 2 s.c o m * * @param formatted * time string, i.e '1y-2mo10d'. * @return the milliseconds as long value from 0. * @throws ParseException * if the string cannot be parsed, i.e. it contains units not * listed or other illegal characters or forms. */ public long parseMillis(String formattedString) throws NumberFormatException { NumberFormatException exception = null; long result = 0; if (StringUtils.isNotBlank(formattedString)) { formattedString = formattedString.trim(); final Matcher matcher = pattern.matcher(formattedString); long parsedValue; String unit = null; int start = 0, end = 0; while (matcher.find()) { start = matcher.start(); if (start != end) { exception = new NumberFormatException(EXCEPTION_MESSAGE_ILLEGAL_CHARACTERS); break; } end = matcher.end(); for (int i = 0; i < matcher.groupCount(); i = i + 3) { parsedValue = Long.parseLong(matcher.group(i + 2)); unit = matcher.group(i + 3).toLowerCase(); result += factors.get(unit) * parsedValue; } } if (end != formattedString.length()) { exception = new NumberFormatException(EXCEPTION_MESSAGE_ILLEGAL_CHARACTERS); } } else { exception = new NumberFormatException(EXCEPTION_MESSAGE_BLANK_STRING); } if (null != exception) { throw exception; } return result; }
From source file:co.cask.cdap.gateway.util.Util.java
/** * Convert a hexadecimal character into a byte. * * @param hex The character to convert/*from www . ja v a 2 s. co m*/ * @return the byte value of the character * @throws NumberFormatException if the character is not hexadecimal */ public static byte hexValue(char hex) { if (hex >= '0' && hex <= '9') { return (byte) (hex - '0'); } else if (hex >= 'a' && hex <= 'f') { return (byte) (hex - 'a' + 10); } else if (hex >= 'A' && hex <= 'F') { return (byte) (hex - 'A' + 10); } else { throw new NumberFormatException("'" + hex + "' is not a hexadecimal character."); } }
From source file:com.doctoror.fuckoffmusicplayer.data.media.session.MediaSessionCallback.java
private long mediaIdToLong(@NonNull final String mediaId) { try {//from ww w . jav a 2 s. c o m return Long.parseLong(mediaId); } catch (NumberFormatException e) { throw new NumberFormatException("Media id is not a number, is " + mediaId); } }
From source file:occi.infrastructure.Compute.java
public Compute(Architecture architecture, int cores, String hostname, float speed, float memory, State state, Set<String> attributes) throws URISyntaxException, NumberFormatException, IllegalArgumentException, NamingException { super("Compute", links, attributes); this.architecture = architecture; this.cores = cores; this.hostname = hostname; this.speed = speed; this.memory = memory; this.state = state; generateActionNames();// ww w . j av a 2s . c o m // check if all attributes are correct if ((cores < 1)) { throw new NumberFormatException("Number of cores is negative!"); } else if (speed <= 1) { throw new NumberFormatException("Number of speed is negative!"); } else if (memory <= 1) { throw new NumberFormatException("Number of memory is negative!"); } // check if there is a hostname if (hostname.length() == 0) { throw new NamingException("Name of the Compute resource can not be null"); } /* * set Category */ setKind(new Kind(actionSet, null, null, null, "compute", "Compute", OcciConfig.getInstance().config.getString("occi.scheme") + "/infrastructure#", attributes)); getKind().setActionNames(actionNames); // set uuid for the resource uuid = UUID.randomUUID(); setId(new URI(uuid.toString())); // put resource into compute list computeList.put(uuid, this); // Generate attribute list generateAttributeList(); }
From source file:com.webarch.common.lang.StringSeriesTools.java
/** * ?double/*from w w w . j a va 2s . co m*/ * * @return */ public static double str2double(final String str) throws NumberFormatException { if ("".equals(str) || str.isEmpty()) { throw new NumberFormatException("NULL??"); } int dotIndex = str.indexOf("."); if (dotIndex <= 0) { return intStr2double(str); } else { String intStr = str.substring(0, dotIndex); String dotStr = str.substring(dotIndex + 1, str.length()); return intStr2double(intStr) + dotStr2dot(dotStr); } }
From source file:org.guicerecipes.spring.testbeans.TestBean.java
public void setTouchy(String touchy) throws Exception { if (touchy.indexOf('.') != -1) { throw new Exception("Can't contain a ."); }// www . ja v a 2 s . com if (touchy.indexOf(',') != -1) { throw new NumberFormatException("Number format exception: contains a ,"); } this.touchy = touchy; }