KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jicengine > expression > CompositeParser


1 package org.jicengine.expression;
2
3 import org.jicengine.operation.Operation;
4
5 /**
6  *
7  *
8  * <p>
9  * Copyright (C) 2004 Timo Laitinen
10  * </p>
11  * @author Timo Laitinen
12  * @created 2004-09-20
13  * @since JICE-0.10
14  *
15  */

16
17 public class CompositeParser implements Parser {
18
19     private Parser[] parsers;
20     private boolean unparsedExpressionIsError = true;
21
22     public CompositeParser(Parser[] parsers)
23     {
24         this.parsers = parsers;
25     }
26
27     public Operation parse(String JavaDoc expression) throws SyntaxException {
28         if( expression == null ){
29             throw new SyntaxException("Expression was null");
30         }
31
32         expression = expression.trim();
33         if( expression.length() == 0){
34             throw new SyntaxException("Empty expression can't be evaluated.");
35         }
36
37         // try the parsers one at a time.
38
// we assume that the first parser to return a non-null value
39
// was the right parser.
40
Parser parser;
41         Operation result = null;
42         for (int i = 0; i < parsers.length; i++) {
43             parser = parsers[i];
44             try {
45                 result = parser.parse(expression);
46                 if( result != null ){
47                     // ok
48
break;
49                 }
50             } catch (SyntaxException e){
51                 throw e;
52             } catch (Exception JavaDoc e2){
53                 throw new SyntaxException("Problems parsing '" + expression + "' with parser " + parser, e2);
54             }
55         }
56
57         if( result == null ){
58             if( this.unparsedExpressionIsError ){
59                 throw new SyntaxException("Illegal expression: '" + expression + "'");
60             }
61             else {
62                 return null;
63             }
64         }
65         else {
66             return result;
67         }
68
69     }
70 }
71
Popular Tags