KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > query > parser > SpeedoQLAbstractVisitor


1 /**
2  * Speedo: an implementation of JDO compliant personality on top of JORM generic
3  * I/O sub-system.
4  * Copyright (C) 2001-2004 France Telecom R&D
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  *
21  *
22  * Contact: speedo@objectweb.org
23  *
24  * Authors: S. Chassande-Barrioz
25  *
26  */

27
28 package org.objectweb.speedo.query.parser;
29
30 import org.objectweb.medor.api.Field;
31 import org.objectweb.medor.api.MedorException;
32 import org.objectweb.medor.query.api.QueryTree;
33 import org.objectweb.util.monolog.api.Logger;
34 import org.objectweb.util.monolog.api.LoggerFactory;
35 import org.objectweb.jorm.util.api.Loggable;
36 import org.objectweb.speedo.query.parser.ASTPrimary;
37 import org.objectweb.speedo.query.parser.ASTType;
38 import org.objectweb.speedo.query.parser.ASTAdditiveExpression;
39 import org.objectweb.speedo.query.parser.ASTLiteral;
40 import org.objectweb.speedo.query.parser.ASTQualifiedName;
41 import org.objectweb.speedo.query.parser.ASTCastExpression;
42 import org.objectweb.speedo.query.parser.ASTRelationalExpression;
43 import org.objectweb.speedo.query.parser.SpeedoQLVisitor;
44 import org.objectweb.speedo.query.parser.ParseException;
45 import org.objectweb.speedo.query.parser.SimpleNode;
46
47 import java.util.ArrayList JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Stack JavaDoc;
50 import java.util.StringTokenizer JavaDoc;
51
52 /**
53  * Base class with visitor utility class and default implementation of
54  * visit methods
55  */

56 public class SpeedoQLAbstractVisitor implements SpeedoQLVisitor, Loggable {
57
58
59     public final static String JavaDoc[] METHODS_OPERATOR = {
60         "matches", //0
61
"startsWith", //1
62
"endsWith", //2
63
"equals", //3
64
"equalsIgnoreCase", //4
65
"toUpperCase", //5
66
"toLowerCase", //6
67
"length", //7
68
"substring", //8
69
"contains", //9
70
"isEmpty" //10
71
};
72     public final static int MATCHES_OPERATOR = 0;
73     public final static int STARTS_WITH_OPERATOR = 1;
74     public final static int ENDS_WITH_OPERATOR = 2;
75     public final static int EQUALS_OPERATOR = 3;
76     public final static int EQUALS_IGNORE_CASE_OPERATOR = 4;
77     public final static int TO_UPPER_OPERATOR = 5;
78     public final static int TO_LOWER_OPERATOR = 6;
79     public final static int LENGTH_OPERATOR = 7;
80     public final static int SUBSTRING_OPERATOR = 8;
81     public final static int CONTAINS_OPERATOR = 9;
82     public final static int IS_EMPTY_OPERATOR = 10;
83
84     public final static Byte JavaDoc STR_OPERAND_SUBSTRING = new Byte JavaDoc((byte) 0);
85     public final static Byte JavaDoc BEGIN_OPERAND_SUBSTRING = new Byte JavaDoc((byte) 1);
86     public final static Byte JavaDoc LENGTH_OPERAND_SUBSTRING = new Byte JavaDoc((byte) 2);
87
88     /**
89      * params is an hashtable to store the parameters.
90      * key: name of the parameter
91      * value: a BasicFieldOperand
92      */

93     protected Map JavaDoc params = null;
94
95     /**
96      * vars is an hashtable to store the variables.
97      * key: name of the variable
98      * value: the PType of the variable (from the declaration)
99      */

100     protected Map JavaDoc vars = null;
101
102     /**
103      * the name of the current class
104      */

105     protected String JavaDoc curClass = null;
106
107     /**
108      * int value to define the type of the IdValue object
109      * UNDEFINED : in case we don't know (default)
110      * JORM_NAME : jorm name (end point of the recursivity)
111      * NAVIGATION : the object is field to a field ...
112      * CONTAINS_IN : the id is a variable and used in a contains method
113      * CONTAINS_MEMBEROF : the id is a parameter and used in a contains method
114      */

115     public final static int UNDEFINED = 0;
116     public final static int EXTENT = 1;
117     public final static int NAVIGATION = 2;
118     public final static int IN_COLLECTION = 3;
119     public final static int MEMBEROF = 4;
120     public final static int IS_EMPTY = 5;
121     public final static int IS_NOT_EMPTY = 6;
122
123     public final static String JavaDoc operationToString(int oc) {
124         switch(oc) {
125         case EXTENT: return "EXTENT";
126         case NAVIGATION: return "NAVIGATION";
127         case IN_COLLECTION: return "IN_COLLECTION";
128         case MEMBEROF: return "MEMBEROF";
129         case IS_EMPTY: return "IS_EMPTY";
130         case IS_NOT_EMPTY: return "IS_NOT_EMPTY";
131         case UNDEFINED:
132         default: return "UNDEFINED";
133         }
134     }
135
136     /** Logger for monolog.
137      */

138     public Logger logger = null;
139     public boolean debug = false;
140
141     public String JavaDoc lastName;
142
143     /**
144      * Values associated with each declared identifiers
145      */

146     protected class IdValue {
147         // Paths used in the select and where clauses starting with the
148
// corresponding id
149
private ArrayList JavaDoc paths = null;
150
151         // abstract schema name or collection values path
152
public String JavaDoc[] name = null;
153
154         // The query tree which corresponds to the id and the paths
155
public QueryTree qt = null;
156
157         // one of 4 possibilities
158
public int nameType = SpeedoQLAbstractVisitor.UNDEFINED;
159         
160         public String JavaDoc alias;
161
162         public IdValue(String JavaDoc[] name, int nameType) {
163             this();
164             this.name = name;
165             this.nameType = nameType;
166         }
167         public IdValue(String JavaDoc pathName, int nameType) {
168             this(pathName);
169             this.nameType = nameType;
170         }
171
172         public IdValue(String JavaDoc pathName) {
173             this();
174             name = splitPath(pathName);
175         }
176
177         public IdValue() {
178             paths = new ArrayList JavaDoc();
179         }
180
181         public void addPath(String JavaDoc path) {
182             if (!paths.contains(path)) {
183                 paths.add(path);
184             }
185         }
186
187         public String JavaDoc[] getSplitedPath(int idx) {
188             return splitPath((String JavaDoc) paths.get(idx));
189         }
190
191         public String JavaDoc getMergedPath(int idx) {
192             return (String JavaDoc) paths.get(idx);
193         }
194
195         public int getDeclaredPathLength() {
196             return paths.size();
197         }
198
199         /**
200          * this method returns the internal representation of an IdValue.
201          * this method is not optimized, because we don't need to call it
202          * a lot of times.
203          */

204         public String JavaDoc toString() {
205             String JavaDoc resName = new String JavaDoc();
206
207             if (name != null) {
208                 for (int i = 0; i < name.length; i++)
209                     resName += name[i] + ".";
210
211                 resName = "[name=" + resName.substring(0, resName.length() - 1) + "]";
212             } else
213                 resName = "[name=null] ";
214
215             String JavaDoc resPath = new String JavaDoc();
216             for (int i = 0; i < paths.size(); i++)
217                 resPath += (String JavaDoc) paths.get(i) + " & ";
218
219             return resName + " - [path=" + resPath + "] - [QT=" + ((qt == null) ? "null" : "something :-)") + "]";
220         }
221     }
222
223     /**
224      * Runtime Exception used to wrap exceptions thrown in visit methods
225      */

226     protected class VisitorException extends RuntimeException JavaDoc {
227         Exception JavaDoc nestedException;
228
229         VisitorException(Exception JavaDoc nestedException) {
230             this.nestedException = nestedException;
231         }
232
233         Exception JavaDoc getNestedException() {
234             return nestedException;
235         }
236     }
237
238     /**
239      * split a dot separated path into tokens
240      */

241     protected String JavaDoc[] splitPath(String JavaDoc path) {
242         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(path, ".");
243         String JavaDoc[] ret = new String JavaDoc[st.countTokens()];
244         for (int i = 0; i < ret.length; i++) {
245             ret[i] = st.nextToken();
246         }
247         return ret;
248     }
249
250     /**
251      *
252      */

253     protected String JavaDoc[] splitEndPath(String JavaDoc path, String JavaDoc prefix) {
254         String JavaDoc end = path.substring(prefix.length());
255
256         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(end, ".");
257         String JavaDoc[] ret = new String JavaDoc[st.countTokens() + 1];
258         ret[0] = prefix;
259         for (int i = 1; i < ret.length; i++) {
260             ret[i] = st.nextToken();
261         }
262         return ret;
263     }
264
265     protected String JavaDoc mergePath(String JavaDoc[] path, int begin, int length) {
266         if (length == 0)
267             return "";
268         StringBuffer JavaDoc ret = new StringBuffer JavaDoc();
269         for (int i = begin; i < (begin + length); i++) {
270             ret.append(path[i]);
271             ret.append('.');
272         }
273         ret.deleteCharAt(ret.length() - 1);
274         return ret.toString();
275     }
276
277     /**
278      * @param path the input path
279      * @return the merge tokens into a dot separated path
280      */

281     protected String JavaDoc mergePath(String JavaDoc[] path) {
282         return (mergePath(path, 0, path.length));
283     }
284
285     protected String JavaDoc getEndString(String JavaDoc total) {
286         return total.substring(total.lastIndexOf('.') + 1, total.length());
287     }
288
289     /**
290      * return the JormField for a given path
291      * @param path the path of the JormField to return
292      * @param ids the map of (id,QueryTree)pairs;
293      * @throws org.objectweb.speedo.query.parser.ParseException if identification variable not found.
294      * @throws org.objectweb.medor.api.MedorException if corresponding fielc does not exist
295      */

296     protected Field getMedorFieldFromPath(String JavaDoc path, Map JavaDoc ids)
297             throws MedorException, ParseException {
298         String JavaDoc[] paths = splitPath(path);
299         QueryTree qt = (QueryTree) ids.get(paths[0]);
300
301         if (paths.length > 2)
302             throw new Error JavaDoc("recursive path not implemented: " + path);
303         if (qt == null) {
304             throw new ParseException("Undeclared identification variable " + paths[0] + " in path " + path);
305         }
306         return qt.getTupleStructure().getField(path);
307     }
308
309     public String JavaDoc alias2fullname(String JavaDoc alias) {
310         int it = alias.indexOf("this.");
311         if (it == -1)
312             return alias;
313         else {
314             return curClass + "." + alias.substring(5, alias.length());
315         }
316     }
317
318     public String JavaDoc buildStringwithout(String JavaDoc[] ss, int toforget, String JavaDoc sep) {
319         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
320         String JavaDoc s = "";
321         for(int i=0; i<ss.length; i++) {
322             if (i != toforget) {
323                 sb.append(s);
324                 s = sep;
325                 sb.append(ss[i]);
326             }
327         }
328         return sb.toString();
329     }
330
331     public String JavaDoc withoutThis(String JavaDoc aname) {
332         int it = aname.indexOf("this.");
333         if (it == -1)
334             return aname;
335         else {
336             return aname.substring(5, aname.length());
337         }
338     }
339
340     public int isMethodOperator(String JavaDoc str) {
341         for(int i=METHODS_OPERATOR.length-1; i>=0; i--) {
342             if (METHODS_OPERATOR[i].equals(str)) {
343                 return i;
344             }
345         }
346         return -1;
347     }
348
349
350     /**
351      * ********************* VISITOR METHODS ***********************************
352      */

353
354     /**
355      * Visit method to call from constructor.
356      * Child node visitors get a <code>java.util.Stack</code> as data parameter.
357      * @throws java.lang.Exception any nested exception thrown from other visit method
358      */

359     public Object JavaDoc visit(SimpleNode node) throws Exception JavaDoc {
360         return visit(node, new Stack JavaDoc());
361     }
362
363     /**
364      * Generic visit method that traverses all child nodes
365      */

366     public Object JavaDoc visit(SimpleNode node, Object JavaDoc data) {
367         return node.childrenAccept(this, data);
368     }
369
370     public Object JavaDoc visit(ASTSpeedoPrimary node, Object JavaDoc data) {
371         return null;
372     }
373
374     public Object JavaDoc visit(ASTSpeedoQL node, Object JavaDoc data) {
375         return null;
376     }
377
378     public Object JavaDoc visit(ASTPrimary node, Object JavaDoc data) {
379         return null;
380     }
381
382     public Object JavaDoc visit(ASTRelationalExpression node, Object JavaDoc data) {
383         return null;
384     }
385
386     public Object JavaDoc visit(ASTAdditiveExpression node, Object JavaDoc data) {
387         return null;
388     }
389
390     public Object JavaDoc visit(ASTUnaryExpression node, Object JavaDoc data) {
391         return null;
392     }
393
394     public Object JavaDoc visit(ASTCastExpression node, Object JavaDoc data) {
395         return null;
396     }
397
398     public Object JavaDoc visit(ASTArgumentList node, Object JavaDoc data) {
399         return null;
400     }
401
402     public Object JavaDoc visit(ASTLiteral node, Object JavaDoc data) {
403         return null;
404     }
405
406     public Object JavaDoc visit(ASTType node, Object JavaDoc data) {
407         return null;
408     }
409
410     public Object JavaDoc visit(ASTQualifiedName node, Object JavaDoc data) {
411         return null;
412     }
413
414
415     /**
416      * ********************* SETTER METHODS ************************************
417      */

418     public void setParams(Map JavaDoc params) {
419         this.params = params;
420     }
421
422     public void setVars(Map JavaDoc vars) {
423         this.vars = vars;
424     }
425
426     public void setCurrentClass(String JavaDoc curClass) {
427         this.curClass = curClass;
428     }
429
430
431     // IMPLEMENTATION OF THE Loggable INTERFACE //
432
//------------------------------------------//
433

434     public void setLogger(Logger logger) {
435         this.logger = logger;
436     }
437
438     public Logger getLogger() {
439         return logger;
440     }
441
442     public void setLoggerFactory(LoggerFactory loggerFactory) {
443     }
444
445     public LoggerFactory getLoggerFactory() {
446         return null;
447     }
448 }
449
Popular Tags