01: /*
02: * Copyright 1999-2004 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.commons.jxpath.ri;
17:
18: import java.io.StringReader;
19:
20: import org.apache.commons.jxpath.JXPathException;
21: import org.apache.commons.jxpath.ri.parser.ParseException;
22: import org.apache.commons.jxpath.ri.parser.TokenMgrError;
23: import org.apache.commons.jxpath.ri.parser.XPathParser;
24:
25: /**
26: * XPath parser
27: *
28: * @author Dmitri Plotnikov
29: * @version $Revision: 1.8 $ $Date: 2004/02/29 14:17:45 $
30: */
31: public class Parser {
32:
33: private static XPathParser parser = new XPathParser(
34: new StringReader(""));
35:
36: /**
37: * Parses the XPath expression. Throws a JXPathException in case
38: * of a syntax error.
39: */
40: public static Object parseExpression(String expression,
41: Compiler compiler) {
42: synchronized (parser) {
43: parser.setCompiler(compiler);
44: Object expr = null;
45: try {
46: parser.ReInit(new StringReader(expression));
47: expr = parser.parseExpression();
48: } catch (TokenMgrError e) {
49: throw new JXPathException("Invalid XPath: '"
50: + addEscapes(expression)
51: + "'. Invalid symbol '"
52: + addEscapes(String.valueOf(e.getCharacter()))
53: + "' "
54: + describePosition(expression, e.getPosition()));
55: } catch (ParseException e) {
56: throw new JXPathException("Invalid XPath: '"
57: + addEscapes(expression)
58: + "'. Syntax error "
59: + describePosition(expression,
60: e.currentToken.beginColumn));
61: }
62: return expr;
63: }
64: }
65:
66: private static String describePosition(String expression,
67: int position) {
68: if (position <= 0) {
69: return "at the beginning of the expression";
70: } else if (position >= expression.length()) {
71: return "- expression incomplete";
72: } else {
73: return "after: '"
74: + addEscapes(expression.substring(0, position))
75: + "'";
76: }
77: }
78:
79: private static String addEscapes(String string) {
80: // Piggy-back on the code generated by JavaCC
81: return TokenMgrError.addEscapes(string);
82: }
83: }
|