List of usage examples for java.text ParseException ParseException
public ParseException(String s, int errorOffset)
From source file:com.quancheng.saluki.core.grpc.router.internal.ConditionRouter.java
private Map<String, MatchPair> doParseRule(String rule) throws ParseException { Map<String, MatchPair> condition = new HashMap<String, MatchPair>(); if (StringUtils.isBlank(rule)) { return condition; }/*from w ww. j a va 2 s . com*/ // ???Key-Value MatchPair pair = null; // Value Set<String> values = null; final Matcher matcher = ROUTE_PATTERN.matcher(rule); while (matcher.find()) { // ?? String separator = matcher.group(1); String content = matcher.group(2); // ? if (separator == null || separator.length() == 0) { pair = new MatchPair(); condition.put(content, pair); } // KV else if ("&".equals(separator)) { if (condition.get(content) == null) { pair = new MatchPair(); condition.put(content, pair); } else { condition.put(content, pair); } } // KVValue else if ("=".equals(separator)) { if (pair == null) throw new ParseException("Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index " + matcher.start() + " before \"" + content + "\".", matcher.start()); values = pair.matches; values.add(content); } // KVValue else if ("!=".equals(separator)) { if (pair == null) throw new ParseException("Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index " + matcher.start() + " before \"" + content + "\".", matcher.start()); values = pair.mismatches; values.add(content); } // KVValue? else if (",".equals(separator)) { // ? if (values == null || values.size() == 0) throw new ParseException("Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index " + matcher.start() + " before \"" + content + "\".", matcher.start()); values.add(content); } else { throw new ParseException("Illegal route rule \"" + rule + "\", The error char '" + separator + "' at index " + matcher.start() + " before \"" + content + "\".", matcher.start()); } } return condition; }
From source file:com.calc.BracerParser.java
/** * Parses the math expression (complicated formula) and stores the result * * @param expression <code>String</code> input expression (math formula) * @throws <code>ParseException</code> if the input expression is not * correct * @since 3.0// w w w. j av a 2 s . com */ public void parse(String expression) throws ParseException { /* cleaning stacks */ stackOperations.clear(); stackRPN.clear(); /* * Faz algumas preparaes na String */ expression = expression.replace(" ", "").replace("(-", "(0-").replace(",-", ",0-").replace("(+", "(0+") .replace(",+", ",0+"); if (expression.charAt(0) == '-' || expression.charAt(0) == '+') { expression = "0" + expression; } /* Separa a expresso em tokens */ StringTokenizer stringTokenizer = new StringTokenizer(expression, OPERATORS + SEPARATOR + "()", true); /* shunting-yard algorithm */ while (stringTokenizer.hasMoreTokens()) { String token = stringTokenizer.nextToken(); if (isOpenBracket(token)) { //Se ( stackOperations.push(token); } else if (isCloseBracket(token)) { //Se ) while (!stackOperations.empty() && !isOpenBracket(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } stackOperations.pop(); if (!stackOperations.empty() && isFunction(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } } else if (isNumber(token)) { if (token.equals(IMAGINARY)) { stackRPN.push(complexFormat.format(new Complex(0, 1))); } else if (token.contains(IMAGINARY)) { stackRPN.push(complexFormat.format(complexFormat.parse("0+" + token))); } else { stackRPN.push(token); } } else if (isOperator(token)) { while (!stackOperations.empty() && isOperator(stackOperations.lastElement()) && getPrecedence(token) <= getPrecedence(stackOperations.lastElement())) { stackRPN.push(stackOperations.pop()); } stackOperations.push(token); } else if (isFunction(token)) { stackOperations.push(token); } else { throw new ParseException("Unrecognized token: " + token, 0); } } while (!stackOperations.empty()) { stackRPN.push(stackOperations.pop()); } /* reverse stack */ Collections.reverse(stackRPN); }
From source file:org.geotools.geometry.jts.spatialschema.geometry.GeometryTestParser.java
/** * parse a single test case// w w w. j a v a 2 s. com * * From looking at various JTS test cases and seeing how their * testbuilder program works, I think its safe to assume that * there will always be just one or two objects, named a and * b. * * @param testCaseNode * @return */ private GeometryTestCase readTestCase(Node testCaseNode) throws ParseException { Node child = testCaseNode.getFirstChild(); GeometryTestOperation operation = null; GeometryTestCase testCase = new GeometryTestCase(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { String name = child.getNodeName(); if (name.equalsIgnoreCase("test")) { testCase.addTestOperation(loadTestOperation(child)); } else if (name.equalsIgnoreCase("a")) { testCase.setGeometryA(loadTestGeometry(child)); } else if (name.equalsIgnoreCase("b")) { testCase.setGeometryB(loadTestGeometry(child)); } else if (name.equalsIgnoreCase("desc")) { testCase.setDescription(getNodeText(child)); } else { throw new ParseException("Unexpected: " + name, 0); } } child = child.getNextSibling(); } return testCase; }
From source file:com.jkoolcloud.tnt4j.streams.utils.TimestampFormatter.java
/** * Parses the value into a timestamp with microsecond accuracy based on the timestamp pattern supported by this * parser.//from w w w . j a v a 2 s . c om * * @param value * value to convert * @return formatted value of timestamp * @throws ParseException * if an error parsing the specified value based timestamp pattern supported by this parser; * @see #parse(TimeUnit, Object) */ public UsecTimestamp parse(Object value) throws ParseException { if (value instanceof UsecTimestamp) { return (UsecTimestamp) value; } if (value instanceof Date) { return new UsecTimestamp((Date) value); } if (value instanceof Calendar) { return new UsecTimestamp(((Calendar) value).getTimeInMillis(), 0); } if (value instanceof String || value instanceof Number) { if (units != null) { return parse(units, value); } else if (pattern != null) { return parse(pattern, value, timeZone, locale); } } throw new ParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "TimestampFormatter.unsupported.pattern", (value == null ? "null" : value.getClass().getName()), units, pattern, locale), 0); }
From source file:com.blackberry.logdriver.timestamp.Rfc5424TimestampParser.java
@Override public long parseTimestatmp(String timestamp) throws ParseException { try {/*w ww. j a v a 2 s . co m*/ // Parse the easy part of the string String firstPart = timestamp.substring(0, 19); Long time; time = dateCache.get(firstPart); if (time == null) { time = dateFormat.parse(firstPart).getTime(); dateCache.put(firstPart, time); } int currentIndex = 19; char c = timestamp.charAt(currentIndex); // Check for fractional seconds to add. We only record up to millisecond // precision, so only grab up to three digits. if (timestamp.charAt(currentIndex) == '.') { // There are fractional seconds, so grab up to 3. // The first digit is guaranteed by the spec. After that, we need to // check if we still have digits. // The spec requires a timezone, so we can't run out of digits // before we run out of string. currentIndex++; c = timestamp.charAt(currentIndex); time += 100 * Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); if (Character.isDigit(c)) { time += 10 * Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); if (Character.isDigit(c)) { time += Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); // Now just go through the digits until we're done. while (Character.isDigit(c)) { currentIndex++; c = timestamp.charAt(currentIndex); } } } } // Now adjust for timezone offset. either Z or +/-00:00 boolean positiveTimeZone = true; if (c == 'Z') { // That's fine. No adjustment. } else { if (c == '+') { positiveTimeZone = true; } else if (c == '-') { positiveTimeZone = false; } else { throw new IllegalArgumentException("Malformed date:" + timestamp); } // Grab the next 2 for hour. Then skip the colon and grab the next // 2. currentIndex++; int hour = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2)); currentIndex += 2; c = timestamp.charAt(currentIndex); if (c != ':') { throw new IllegalArgumentException("Malformed date:" + timestamp); } currentIndex++; int minute = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2)); int offset = (60 * hour + minute) * 60 * 1000; if (positiveTimeZone) { time -= offset; } else { time += offset; } } // If we support daylight savings, then we need to keep checking if we're // in // daylight savings or not. if (daylightSavings) { time += tz.getOffset(time); } else { time += tzOffset; } return time; } catch (ParseException e) { throw e; } catch (Throwable t) { ParseException e = new ParseException("Unexpected Exception", 0); e.initCause(t); throw e; } }
From source file:edu.cornell.kfs.fp.businessobject.USBankRecordFieldUtils.java
/** * Extracts a KualiDecimal representing dollars and cents from a substring less any ending whitespace * for a given beginning and ending position. * /*from w ww . j a v a 2 s . co m*/ * @param line Superstring * @param begin Beginning index * @param end Ending index * @param lineCount The current line number * @return The KualiDecimal parsed from the trimmed substring * @throws ParseException When unable to parse the KualiDecimal */ public static KualiDecimal extractDecimalWithCents(String line, int begin, int end, int lineCount) throws ParseException { KualiDecimal theDecimal; KualiDecimal theCents; try { String sanitized = line.substring(begin, end - 2); sanitized = StringUtils.remove(sanitized, '-'); sanitized = StringUtils.remove(sanitized, '+'); theDecimal = new KualiDecimal(sanitized); theCents = new KualiDecimal(line.substring(end - 2, end)); theCents = theCents.multiply(new KualiDecimal("0.01")); theDecimal = theDecimal.add(theCents); } catch (StringIndexOutOfBoundsException | IllegalArgumentException e) { // May encounter a StringIndexOutOfBoundsException if the string bounds do not match or // an IllegalArgumentException if the Decimal or Cents do not parse correctly throw new ParseException( "Unable to parse " + line.substring(begin, end) + " into a decimal value on line " + lineCount, lineCount); } return theDecimal; }
From source file:at.bitfire.davdroid.DateUtils.java
/** * Takes a formatted string as provided by the Android calendar provider and returns a DateListProperty * constructed from these values.//from www.j a va 2 s . c o m * @param dbStr formatted string from Android calendar provider (RDATE/EXDATE field) * expected format: "[TZID;]date1,date2,date3" where date is "yyyymmddThhmmss[Z]" * @param type subclass of DateListProperty, e.g. RDate or ExDate * @param allDay true: list will contain DATE values; false: list will contain DATE_TIME values * @return instance of "type" containing the parsed dates/times from the string */ public static DateListProperty androidStringToRecurrenceSet(String dbStr, Class<? extends DateListProperty> type, boolean allDay) throws ParseException { // 1. split string into time zone and actual dates TimeZone timeZone; String datesStr; final int limiter = dbStr.indexOf(';'); if (limiter != -1) { // TZID given timeZone = DateUtils.tzRegistry.getTimeZone(dbStr.substring(0, limiter)); datesStr = dbStr.substring(limiter + 1); } else { timeZone = null; datesStr = dbStr; } // 2. process date string and generate list of DATEs or DATE-TIMEs DateList dateList; if (allDay) { dateList = new DateList(Value.DATE); for (String s : StringUtils.split(datesStr, ',')) dateList.add(new Date(new DateTime(s))); } else { dateList = new DateList(datesStr, Value.DATE_TIME, timeZone); if (timeZone == null) dateList.setUtc(true); } // 3. generate requested DateListProperty (RDate/ExDate) from list of DATEs or DATE-TIMEs DateListProperty list; try { list = (DateListProperty) type.getDeclaredConstructor(new Class[] { DateList.class }) .newInstance(dateList); if (dateList.getTimeZone() != null) list.setTimeZone(dateList.getTimeZone()); } catch (Exception e) { throw new ParseException("Couldn't create date/time list by reflection", -1); } return list; }
From source file:org.elasticwarehouse.core.graphite.RRDManager.java
private void initDataSources(List<String> sources, boolean cutSourcesto20chars) throws ParseException { for (String source : sources) { if (source.length() > MAXDATASOURCENAMELEN && cutSourcesto20chars == false) throw new ParseException("Datasource name [" + source + "] too long (" + source.length() + " chars found, only " + MAXDATASOURCENAMELEN + " allowed", 0); String transformedsource = transformSourceName(source); LOGGER.debug("source=" + source + ", transformedsource=" + transformedsource); this.sources_.add(transformedsource); }//from w w w. j a v a 2 s . c o m }
From source file:com.ettrema.zsync.Upload.java
/** * Parses the InputStream into an Upload object.<p/> * //from www. ja v a 2s .com * The method initially parses the headers from the InputStream by reading the sequence of keys (the String preceding the first colon in each line) * and values ( the String following the colon and terminated by the LF character ) and invoking {@link #parseParam} on each key value pair. * If the key is RELOCATE, then the value is not read, but is copied into a BufferingOutputStream and stored in the relocStream field. Parsing of headers * continues until a "blank" line is reached, ie a line that is null or contains only whitespace, which indicates the beginning of the data section. * A reference to the remaining InputStream is then stored in the dataStream field.<p/> * * @param in The InputStream containing the ZSync upload * @return A filled in Upload object */ public static Upload parse(InputStream in) { Upload um = new Upload(); int bytesRead = 0; //Enables a ParseException to specify the offset try { //Maximum number of bytes to search for delimiters int MAX_SEARCH = 1024; String key; //Parse headers until a null/all-whitespace line is encountered while (!StringUtils.isBlank((key = readKey(in, MAX_SEARCH)))) { /* * Add one to bytesRead since the delimiter was read but omitted from the String. * The final value of bytesRead may end up off by one if the end of input is reached, since no * delimiter is read in that case. */ bytesRead += key.length() + 1; key = key.trim(); if (key.equalsIgnoreCase(RELOCATE)) { /* * Copies the Relocate values to a BufferingOutputStream */ BufferingOutputStream relocOut = new BufferingOutputStream(16384); bytesRead += copyLine(in, 1024 * 1024 * 64, relocOut); relocOut.close(); um.setRelocStream(relocOut.getInputStream()); } else { /* * Key is not "Relocate", so parse header */ String value = readValue(in, MAX_SEARCH); bytesRead += value.length() + 1; value = value.trim(); um.parseParam(key, value); } } /* * A blank line has been read, indicating the end of the headers, so the unread * portion of the InputStream is the byte range section. */ um.setDataStream(in); } catch (IOException e) { throw new RuntimeException("Couldn't parse upload, IOException.", e); } catch (ParseException e) { //Set the offset of the ParseException to bytesRead ParseException ex = new ParseException(e.getMessage(), bytesRead); throw new RuntimeException(ex); } return um; }
From source file:com.jkoolcloud.tnt4j.streams.utils.NumericFormatter.java
/** * Formats the specified object using the defined pattern, or using the default numeric formatting if no pattern was * defined./*from w ww . j a v a 2 s .com*/ * * @param formatter * formatter object to apply to value * @param radix * the radix to use while parsing numeric strings * @param value * value to convert * @param scale * value to multiply the formatted value by * * @return formatted value of field in required internal data type * * @throws ParseException * if an error parsing the specified value based on the field definition (e.g. does not match defined * pattern, etc.) */ private static Number parse(DecimalFormat formatter, int radix, Object value, Number scale) throws ParseException { if (value == null) { return null; } if (scale == null) { scale = 1.0; } try { Number numValue = null; if (formatter == null && value instanceof String) { String strValue = (String) value; if (strValue.startsWith("0x") || strValue.startsWith("0X")) { // NON-NLS numValue = Long.parseLong(strValue.substring(2), 16); } } if (numValue == null) { if (formatter != null) { numValue = formatter.parse(value.toString()); } else if (radix != 10) { numValue = Long.parseLong(value.toString(), radix); } else { numValue = value instanceof Number ? (Number) value : Double.valueOf(value.toString()); } } Number scaledValue = numValue.doubleValue() * scale.doubleValue(); return Utils.castNumber(scaledValue, numValue.getClass()); } catch (NumberFormatException nfe) { throw new ParseException(nfe.getLocalizedMessage(), 0); } }