1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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. import java.io.StringReader;
  18. import org.apache.commons.jxpath.JXPathException;
  19. import org.apache.commons.jxpath.ri.parser.ParseException;
  20. import org.apache.commons.jxpath.ri.parser.TokenMgrError;
  21. import org.apache.commons.jxpath.ri.parser.XPathParser;
  22. /**
  23. * XPath parser
  24. *
  25. * @author Dmitri Plotnikov
  26. * @version $Revision: 1.8 $ $Date: 2004/02/29 14:17:45 $
  27. */
  28. public class Parser {
  29. private static XPathParser parser = new XPathParser(new StringReader(""));
  30. /**
  31. * Parses the XPath expression. Throws a JXPathException in case
  32. * of a syntax error.
  33. */
  34. public static Object parseExpression(
  35. String expression,
  36. Compiler compiler)
  37. {
  38. synchronized (parser) {
  39. parser.setCompiler(compiler);
  40. Object expr = null;
  41. try {
  42. parser.ReInit(new StringReader(expression));
  43. expr = parser.parseExpression();
  44. }
  45. catch (TokenMgrError e) {
  46. throw new JXPathException(
  47. "Invalid XPath: '"
  48. + addEscapes(expression)
  49. + "'. Invalid symbol '"
  50. + addEscapes(String.valueOf(e.getCharacter()))
  51. + "' "
  52. + describePosition(expression, e.getPosition()));
  53. }
  54. catch (ParseException e) {
  55. throw new JXPathException(
  56. "Invalid XPath: '"
  57. + addEscapes(expression)
  58. + "'. Syntax error "
  59. + describePosition(
  60. expression,
  61. e.currentToken.beginColumn));
  62. }
  63. return expr;
  64. }
  65. }
  66. private static String describePosition(String expression, int position) {
  67. if (position <= 0) {
  68. return "at the beginning of the expression";
  69. }
  70. else if (position >= expression.length()) {
  71. return "- expression incomplete";
  72. }
  73. else {
  74. return "after: '"
  75. + addEscapes(expression.substring(0, position)) + "'";
  76. }
  77. }
  78. private static String addEscapes(String string) {
  79. // Piggy-back on the code generated by JavaCC
  80. return TokenMgrError.addEscapes(string);
  81. }
  82. }