1
2
3
4
5
6
7
8
9
10
11
12
13
14
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(new StringReader(""));
34
35 /***
36 * Parses the XPath expression. Throws a JXPathException in case
37 * of a syntax error.
38 */
39 public static Object parseExpression(
40 String expression,
41 Compiler compiler)
42 {
43 synchronized (parser) {
44 parser.setCompiler(compiler);
45 Object expr = null;
46 try {
47 parser.ReInit(new StringReader(expression));
48 expr = parser.parseExpression();
49 }
50 catch (TokenMgrError e) {
51 throw new JXPathException(
52 "Invalid XPath: '"
53 + addEscapes(expression)
54 + "'. Invalid symbol '"
55 + addEscapes(String.valueOf(e.getCharacter()))
56 + "' "
57 + describePosition(expression, e.getPosition()));
58 }
59 catch (ParseException e) {
60 throw new JXPathException(
61 "Invalid XPath: '"
62 + addEscapes(expression)
63 + "'. Syntax error "
64 + describePosition(
65 expression,
66 e.currentToken.beginColumn));
67 }
68 return expr;
69 }
70 }
71
72 private static String describePosition(String expression, int position) {
73 if (position <= 0) {
74 return "at the beginning of the expression";
75 }
76 else if (position >= expression.length()) {
77 return "- expression incomplete";
78 }
79 else {
80 return "after: '"
81 + addEscapes(expression.substring(0, position)) + "'";
82 }
83 }
84
85 private static String addEscapes(String string) {
86
87 return TokenMgrError.addEscapes(string);
88 }
89 }