View Javadoc

1   /*
2   Copyright (C) 2004 Grid Systems, S.A.
3   
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License, version 2, as
6   published by the Free Software Foundation.
7   
8   This program is distributed in the hope that it will be useful,
9   but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12  
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  */
17  package com.gridsystems.beanfilter;
18  
19  import java.util.regex.Matcher;
20  import java.util.regex.Pattern;
21  
22  /**
23   * FilterParser facade. Necessary because the class generated by JavaCC is not public.
24   *
25   * @author Rodrigo Ruiz
26   * @version 1.0
27   */
28  public final class Parser {
29  
30    /**
31     * Hidden constructor.
32     */
33    private Parser() { }
34  
35    /**
36     * Parses the specified string as an expression to evaluate on object of class 'c'.
37     *
38     * @param s  An expression to parse
39     * @param c  The class to evaluate
40     * @return The evaluation tree
41     * @throws EvalException  FTR000: Parse exception
42     */
43    public static EvalNode parse(String s, Class<?> c) throws EvalException {
44      FilterParser parser = new FilterParser(s, c);
45      try {
46        return parser.compile();
47      } catch (ParseException e) {
48        //e.printStackTrace();
49        Object[] eparams = {
50          e.currentToken.next.beginLine,
51          e.currentToken.next.beginColumn,
52          null
53        };
54        String code = "FTR000";
55        if (e.specialConstructor && e.tokenImage == null) {
56          // This exception has been thrown from the FieldValue constructor
57          code = "FTR005";
58          eparams[1] = e.currentToken.image;
59        }
60        throw new EvalException(e, code, eparams);
61      } catch (TokenMgrError e) {
62        String msg = e.getMessage();
63        int pos = msg.indexOf('.');
64        if (pos != -1) {
65          final String pattern = "Lexical error at line ([0-9]+), column ([0-9]+)";
66          Pattern p = Pattern.compile(pattern);
67          Matcher m = p.matcher(msg.substring(0, pos));
68          if (m.matches()) {
69            Object[] eparams = { new Integer(m.group(1)), new Integer(m.group(2)) };
70            throw new EvalException(e, "FTR000", eparams);
71          }
72        }
73        throw new EvalException(e, "FTR000", 0, 0);
74      }
75    }
76  }