List of usage examples for java.text ParseException ParseException
public ParseException(String s, int errorOffset)
From source file:com.jkoolcloud.tnt4j.core.UsecTimestamp.java
/** * <p>Creates UsecTimestamp from string representation of timestamp in the * specified format.</p>/*from w ww. j a v a 2s . c o m*/ * <p>This is based on {@link SimpleDateFormat}, but extends its support to * recognize microsecond fractional seconds. If number of fractional second * characters is greater than 3, then it's assumed to be microseconds. * Otherwise, it's assumed to be milliseconds (as this is the behavior of * {@link SimpleDateFormat}. * * @param timeStampStr timestamp string * @param formatStr format specification for timestamp string * @param timeZone time zone that timeStampStr represents. This is only needed when formatStr does not include * time zone specification and timeStampStr does not represent a string in local time zone. * @param locale locale for date format to use. * @throws NullPointerException if timeStampStr is {@code null} * @throws IllegalArgumentException if timeStampStr is not in the correct format * @throws ParseException if failed to parse string based on specified format * @see java.util.TimeZone */ public UsecTimestamp(String timeStampStr, String formatStr, TimeZone timeZone, String locale) throws ParseException { if (timeStampStr == null) throw new NullPointerException("timeStampStr must be non-null"); int usecs = 0; SimpleDateFormat dateFormat; if (StringUtils.isEmpty(formatStr)) { dateFormat = new SimpleDateFormat(); } else { // Java date formatter cannot deal with usecs, so we need to extract those ourselves int fmtPos = formatStr.indexOf('S'); if (fmtPos > 0) { int endFmtPos = formatStr.lastIndexOf('S'); int fmtFracSecLen = endFmtPos - fmtPos + 1; if (fmtFracSecLen > 6) throw new ParseException( "Date format containing more than 6 significant digits for fractional seconds is not supported", 0); StringBuilder sb = new StringBuilder(); int usecPos = timeStampStr.lastIndexOf('.') + 1; int usecEndPos; if (usecPos > 2) { for (usecEndPos = usecPos; usecEndPos < timeStampStr.length(); usecEndPos++) { if (!StringUtils.containsAny("0123456789", timeStampStr.charAt(usecEndPos))) break; } if (fmtFracSecLen > 3) { // format specification represents more than milliseconds, assume microseconds String usecStr = String.format("%s", timeStampStr.substring(usecPos, usecEndPos)); if (usecStr.length() < fmtFracSecLen) usecStr = StringUtils.rightPad(usecStr, fmtFracSecLen, '0'); else if (usecStr.length() > fmtFracSecLen) usecStr = usecStr.substring(0, fmtFracSecLen); usecs = Integer.parseInt(usecStr); // trim off fractional part < microseconds from both timestamp and format strings sb.append(timeStampStr); sb.delete(usecPos - 1, usecEndPos); timeStampStr = sb.toString(); sb.setLength(0); sb.append(formatStr); sb.delete(fmtPos - 1, endFmtPos + 1); formatStr = sb.toString(); } else if ((usecEndPos - usecPos) < 3) { // pad msec value in date string with 0's so that it is 3 digits long sb.append(timeStampStr); while ((usecEndPos - usecPos) < 3) { sb.insert(usecEndPos, '0'); usecEndPos++; } timeStampStr = sb.toString(); } } } dateFormat = StringUtils.isEmpty(locale) ? new SimpleDateFormat(formatStr) : new SimpleDateFormat(formatStr, Utils.getLocale(locale)); } dateFormat.setLenient(true); if (timeZone != null) dateFormat.setTimeZone(timeZone); Date date = dateFormat.parse(timeStampStr); setTimestampValues(date.getTime(), 0, 0); add(0, usecs); }
From source file:org.pentaho.reporting.platform.plugin.ReportContentUtil.java
private static Date parseDate(final ParameterDefinitionEntry parameterEntry, final ParameterContext context, final String value) throws ParseException { try {/*w ww.java2 s . c o m*/ return parseDateStrict(parameterEntry, context, value); } catch (ParseException pe) { // } try { // parse the legacy format that we used in 3.5.0-GA. final Long dateAsLong = Long.parseLong(value); return new Date(dateAsLong); } catch (NumberFormatException nfe) { // ignored } try { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // NON-NLS return simpleDateFormat.parse(value); } catch (ParseException pe) { // } throw new ParseException("Unable to parse Date", 0); }
From source file:com.adobe.ags.curly.controller.ActionRunner.java
private boolean parseCmdParam(char command, String param, int offset) throws ParseException { switch (command) { case 'F': httpMethod = HttpMethod.POST;// w ww . j av a2s. c o m httpMethodExplicitlySet = true; case 'd': Map<String, List<String>> vars = postVariables; if (!httpMethodExplicitlySet) { httpMethod = HttpMethod.POST; } else if (httpMethod != HttpMethod.POST) { vars = getVariables; } int equals = param.indexOf('='); if (equals > -1) { String fieldName = detokenizeParameters(param.substring(0, equals)); String value = equals < param.length() - 1 ? detokenizeParameters(param.substring(equals + 1)) : null; if (command == 'F' && value != null && value.startsWith("@")) { httpMethod = HttpMethod.POST; multipart = true; } if (!vars.containsKey(fieldName)) { vars.put(fieldName, new ArrayList<>()); } vars.get(fieldName).add(value); } else { throw new ParseException(ApplicationState.getMessage(MISSING_NVP_FORM_ERROR), offset + 1); } return true; case 'T': httpMethod = HttpMethod.PUT; multipart = false; putFile = detokenizeParameters(param); return true; case 'X': try { httpMethod = HttpMethod.valueOf(param.toUpperCase()); } catch (IllegalArgumentException ex) { throw new ParseException(ApplicationState.getMessage(UNKNOWN_METHOD_ERROR) + " " + param, offset + 1); } return true; case 'h': String[] nvp = param.split(":\\s*"); if (nvp.length != 2) { throw new ParseException(ApplicationState.getMessage(MISSING_NVP_HEADER_ERROR), offset + 1); } requestHeaders.put(detokenizeParameters(nvp[0]), detokenizeParameters(nvp[1])); return true; case 'e': requestHeaders.put("referer", detokenizeParameters(param)); return true; case 'u': // ignored parameterized options return true; case 'G': httpMethodExplicitlySet = true; httpMethod = HttpMethod.GET; case 'S': case '#': case 'v': //ignored no-parameter flags return false; default: throw new ParseException(ApplicationState.getMessage(UNKNOWN_PARAMETER) + ": " + command, offset); } }
From source file:org.alfresco.util.CachingDateFormat.java
public static Pair<Date, Integer> lenientParse(String text, int minimumResolution) throws ParseException { DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); try {/*from w ww . j av a 2s . c o m*/ Date parsed = fmt.parseDateTime(text).toDate(); return new Pair<Date, Integer>(parsed, Calendar.MILLISECOND); } catch (IllegalArgumentException e) { } SimpleDateFormatAndResolution[] formatters = getLenientFormatters(); for (SimpleDateFormatAndResolution formatter : formatters) { if (formatter.resolution >= minimumResolution) { ParsePosition pp = new ParsePosition(0); Date parsed = formatter.simpleDateFormat.parse(text, pp); if ((pp.getIndex() < text.length()) || (parsed == null)) { continue; } return new Pair<Date, Integer>(parsed, formatter.resolution); } } throw new ParseException("Unknown date format", 0); }
From source file:org.pentaho.di.core.util.DateDetector.java
/** * //from w w w.j av a2 s . c om * @param dateString * date string for parse * @return {@link java.util.Date} converted from dateString by detected format * @throws ParseException * - if we can not detect date format for string or we can not parse date string */ public static Date getDateFromString(String dateString, String locale) throws ParseException { String dateFormat = detectDateFormat(dateString, locale); if (dateFormat == null) { throw new ParseException("Unknown date format.", 0); } return getDateFromStringByFormat(dateString, dateFormat); }
From source file:com.autsia.bracer.BracerParser.java
/** * Evaluates once parsed math expression with "var" variable included * * @param variableValue User-specified <code>Double</code> value * @return <code>String</code> representation of the result * @throws <code>ParseException</code> if the input expression is not * correct * @since 3.0// w w w. j a v a 2 s. c o m */ public String evaluate(double variableValue) throws ParseException { /* check if is there something to evaluate */ if (stackRPN.empty()) { return ""; } /* clean answer stack */ stackAnswer.clear(); /* get the clone of the RPN stack for further evaluating */ @SuppressWarnings("unchecked") Stack<String> stackRPN = (Stack<String>) this.stackRPN.clone(); /* enroll the variable value into expression */ Collections.replaceAll(stackRPN, VARIABLE, Double.toString(variableValue)); /* evaluating the RPN expression */ while (!stackRPN.empty()) { String token = stackRPN.pop(); if (isNumber(token)) { stackAnswer.push(token); } else if (isOperator(token)) { Complex a = complexFormat.parse(stackAnswer.pop()); Complex b = complexFormat.parse(stackAnswer.pop()); boolean aBoolean = a.getReal() == 1.0; boolean bBoolean = b.getReal() == 1.0; switch (token) { case "+": stackAnswer.push(complexFormat.format(b.add(a))); break; case "-": stackAnswer.push(complexFormat.format(b.subtract(a))); break; case "*": stackAnswer.push(complexFormat.format(b.multiply(a))); break; case "/": stackAnswer.push(complexFormat.format(b.divide(a))); break; case "|": stackAnswer.push(String.valueOf(aBoolean || bBoolean ? "1" : "0")); break; case "&": stackAnswer.push(String.valueOf(aBoolean && bBoolean ? "1" : "0")); break; } } else if (isFunction(token)) { Complex a = complexFormat.parse(stackAnswer.pop()); boolean aBoolean = a.getReal() == 1.0; switch (token) { case "abs": stackAnswer.push(complexFormat.format(a.abs())); break; case "acos": stackAnswer.push(complexFormat.format(a.acos())); break; case "arg": stackAnswer.push(complexFormat.format(a.getArgument())); break; case "asin": stackAnswer.push(complexFormat.format(a.asin())); break; case "atan": stackAnswer.push(complexFormat.format(a.atan())); break; case "conj": stackAnswer.push(complexFormat.format(a.conjugate())); break; case "cos": stackAnswer.push(complexFormat.format(a.cos())); break; case "cosh": stackAnswer.push(complexFormat.format(a.cosh())); break; case "exp": stackAnswer.push(complexFormat.format(a.exp())); break; case "imag": stackAnswer.push(complexFormat.format(a.getImaginary())); break; case "log": stackAnswer.push(complexFormat.format(a.log())); break; case "neg": stackAnswer.push(complexFormat.format(a.negate())); break; case "real": stackAnswer.push(complexFormat.format(a.getReal())); break; case "sin": stackAnswer.push(complexFormat.format(a.sin())); break; case "sinh": stackAnswer.push(complexFormat.format(a.sinh())); break; case "sqrt": stackAnswer.push(complexFormat.format(a.sqrt())); break; case "tan": stackAnswer.push(complexFormat.format(a.tan())); break; case "tanh": stackAnswer.push(complexFormat.format(a.tanh())); break; case "pow": Complex b = complexFormat.parse(stackAnswer.pop()); stackAnswer.push(complexFormat.format(b.pow(a))); break; case "not": stackAnswer.push(String.valueOf(!aBoolean ? "1" : "0")); break; } } } if (stackAnswer.size() > 1) { throw new ParseException("Some operator is missing", 0); } return stackAnswer.pop(); }
From source file:com.netcrest.pado.tools.pado.command.put.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private Map getEntryMap(String fullPath, BufferInfo bufferInfo, List<String> list, boolean keyEnumerated, boolean valueEnumerated, int startIndex) throws Exception { String pairs = ""; for (int i = startIndex; i < list.size(); i++) { pairs += list.get(i) + " "; }//from ww w .j a v a 2 s .c o m Map<String, Method> keySetterMap = ReflectionUtil.getAllSettersMap(padoShell.getKeyClass()); Map<String, Method> valueSetterMap = ReflectionUtil.getAllSettersMap(padoShell.getValueClass()); String gridPath = GridUtil.getChildPath(fullPath); String gridId = SharedCache.getSharedCache().getGridId(fullPath); IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IGridMapBiz.class, gridPath); gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId); // (x='1,2,3' and y='2',a='hello, world' and b='test') HashMap map = new HashMap(); StringBuffer buffer = new StringBuffer(pairs); boolean keySearch = false; boolean fieldSearch = false; boolean openQuote = false; boolean delimiter = false; boolean quoted = false; String fieldString = ""; String valueString = ""; String and = ""; Object key = null; Object value = null; for (int i = 0; i < buffer.length(); i++) { char c = buffer.charAt(i); if (c == '(') { if (openQuote == false) { String function = null; String functionCall = null; String functionString = null; if (valueString.length() > 0) { functionString = valueString; } else if (fieldString.length() > 0) { functionString = fieldString; } if (functionString != null) { // it's a function // get enclosed parenthesis int enclosedIndex = getEnclosingParenthesis(buffer, i); function = functionString.toLowerCase(); if (enclosedIndex == -1) { throw new ParseException("Malformed function call: " + function, i); } functionCall = function + buffer.substring(i, enclosedIndex + 1); Logger.fine("functionCall = |" + functionCall + "|"); i = enclosedIndex; } if (functionCall != null) { if (valueString.length() > 0) { valueString = functionCall; } else if (fieldString.length() > 0) { fieldString = functionCall; } } else { key = null; value = null; keySearch = true; fieldSearch = true; fieldString = ""; valueString = ""; } quoted = false; continue; } } else if (c == '=') { if (keySearch && key == null && keyEnumerated == false) { key = padoShell.getKeyClass().newInstance(); } if (keySearch == false && value == null && valueEnumerated == false) { if (padoShell.getValueClass() == null) { throw new ClassNotFoundException( "Undefined value class. Use the 'value' command to set the class name"); } value = padoShell.getValueClass().newInstance(); } fieldSearch = false; continue; } else if (c == ')') { if (openQuote == false) { Logger.fine("v: field = " + fieldString); Logger.fine("v: value = " + valueString); Logger.fine(""); if (valueEnumerated) { Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1); if (k == null) { PadoShell.printlnError( "Error: value not found in the cache for the key number " + fieldString); PadoShell.println(" run 'key -l' to view the enumerated keys."); map.clear(); break; } value = gridMapBiz.get(k); if (key == null) { PadoShell.printlnError("Error: value not in the cache - " + fieldString); map.clear(); break; } Logger.fine("k = " + k); Logger.fine("key = " + key); Logger.fine("value = " + value); } else { if (valueString.length() == 0) { // primitive value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted); } else { updateObject(valueSetterMap, value, fieldString, valueString); } } map.put(key, value); fieldSearch = true; quoted = false; fieldString = ""; valueString = ""; key = null; and = ""; continue; } } else if (c == '\\') { // ignore and treat the next character as a character delimiter = true; continue; } else if (c == '\'') { if (delimiter) { delimiter = false; } else { if (openQuote) { quoted = true; } openQuote = !openQuote; continue; } } else if (c == ' ') { if (openQuote == false) { boolean andExpected = false; if (keySearch) { Logger.fine("k: field = " + fieldString); Logger.fine("k: value = " + valueString); Logger.fine(""); if (fieldString.length() > 0) { updateObject(keySetterMap, key, fieldString, valueString); andExpected = true; } } else { Logger.fine("v: field = " + fieldString); Logger.fine("v: value = " + valueString); Logger.fine(""); if (fieldString.length() > 0) { updateObject(valueSetterMap, value, fieldString, valueString); andExpected = true; } } if (andExpected) { and = ""; int index = -1; for (int j = i; j < buffer.length(); j++) { and += buffer.charAt(j); and = and.trim().toLowerCase(); if (and.equals("and")) { index = j; break; } else if (and.length() > 3) { break; } } if (index != -1) { i = index; } } fieldSearch = true; fieldString = ""; valueString = ""; and = ""; quoted = false; continue; } } if (c == ',') { // if ',' is not enclosed in quotes... if (openQuote == false) { fieldString = fieldString.trim(); valueString = valueString.trim(); // end of key Logger.fine("k: field = " + fieldString); Logger.fine("k: value = " + valueString); Logger.fine(""); if (keySearch) { if (keyEnumerated) { key = bufferInfo.getKey(Integer.parseInt(fieldString) - 1); if (key == null) { PadoShell.printlnError( "Error: value not found in the cache for the key number " + fieldString); PadoShell.println(" run 'key -l' to view the enumerated keys."); map.clear(); break; } } else { if (valueString.length() == 0) { key = ObjectUtil.getPrimitive(padoShell, fieldString, quoted); } else { updateObject(keySetterMap, key, fieldString, valueString); } } } else { if (valueEnumerated) { Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1); value = gridMapBiz.get(k); if (value == null) { PadoShell.printlnError("Error: undefined value num " + fieldString); map.clear(); break; } } else { if (valueString.length() == 0) { value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted); } else { updateObject(valueSetterMap, value, fieldString, valueString); } } } fieldSearch = true; keySearch = false; quoted = false; fieldString = ""; valueString = ""; and = ""; continue; } } if (fieldSearch) { fieldString += c; } else if (quoted == false) { valueString += c; } } return map; }
From source file:org.hypertable.hadoop.mapred.TextTableInputFormat.java
public void parseRowInterval(JobConf job) throws ParseException { String str = job.get(ROW_INTERVAL); if (str != null) { Date ts;//from w w w. j a v a 2 s . c o m long epoch_time; String[] parsedRelop = parseRelopSpec(str, "ROW"); RowInterval interval = new RowInterval(); if (parsedRelop == null) throw new ParseException("Invalid ROW interval: " + str, 0); if (parsedRelop[0] != null && parsedRelop[0].length() > 0) { interval.setStart_row(parsedRelop[0]); interval.setStart_rowIsSet(true); if (parsedRelop[1].equals("<")) interval.setStart_inclusive(false); else if (parsedRelop[1].equals("<=")) interval.setStart_inclusive(true); else throw new ParseException("Invalid ROW interval, bad RELOP (" + parsedRelop[1] + ")", 0); interval.setStart_inclusiveIsSet(true); } if (parsedRelop[4] != null && parsedRelop[4].length() > 0) { interval.setEnd_row(parsedRelop[4]); interval.setEnd_rowIsSet(true); if (parsedRelop[3].equals("<")) interval.setEnd_inclusive(false); else if (parsedRelop[3].equals("<=")) interval.setEnd_inclusive(true); else throw new ParseException("Invalid ROW interval, bad RELOP (" + parsedRelop[3] + ")", 0); interval.setEnd_inclusiveIsSet(true); } if (interval.isSetStart_row() || interval.isSetEnd_row()) { m_base_spec.addToRow_intervals(interval); m_base_spec.setRow_intervalsIsSet(true); } } }
From source file:Unsigned.java
/** * Parse a binary number into a Number object. If up to 8 bits are parsed, * returns a Byte. If more than 8 and up to 16 bits are parsed, return a * Short. If more than 16 and up to 32 bits are parsed, return an Integer. * If more than 32 and up to 64 bits are parsed, return a Long. * /*from w w w . j av a 2 s .com*/ * @param source * a binary number * @return return an integer form of Number object if parse is successful * @exception ParseException * thrown if source is cannot be converted to a Byte, Short, * Int, or Long. * * @since 1.0 */ public Number parse(String source) throws ParseException { int startIndex = 0; Number result; ParsePosition parsePosition = new ParsePosition(startIndex); result = parse(source, parsePosition); if (result == null) { throw new ParseException("Unable to parse " + source + " using BinaryFormat", parsePosition.getIndex()); } return (result); }
From source file:org.cipango.console.ApplicationManager.java
public Table getDarConfig() throws Exception { Table table = new Table(); table.setTitle("Configuration"); List<Header> headers = new ArrayList<Row.Header>(); headers.add(new Header("Method")); headers.add(new Header("Application name")); headers.add(new Header("Identity")); headers.add(new Header("Routing region")); headers.add(new Header("URI")); headers.add(new Header("Route modifier")); headers.add(new Header("State info")); table.setHeaders(headers);//w w w. j a v a 2s . co m String config = (String) _mbsc.getAttribute(DAR, "config"); InputStream is = new ByteArrayInputStream(config.getBytes()); Properties properties = new Properties(); properties.load(is); Enumeration<Object> e = properties.keys(); while (e.hasMoreElements()) { String method = e.nextElement().toString(); String infos = properties.get(method).toString().trim(); int li = infos.indexOf('('); while (li >= 0) { Row row = new Row(); List<Value> values = row.getValues(); Iterator<Header> headerIt = headers.iterator(); int ri = infos.indexOf(')', li); if (ri < 0) throw new ParseException(infos, li); values.add(new Value(method, headerIt.next())); String info = infos.substring(li + 1, ri); li = infos.indexOf('(', ri); InfoIterator it = new InfoIterator(info); while (it.hasNext()) values.add(new Value(it.next(), headerIt.next())); table.add(row); } } return table; }