KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > utils > parser > ProductionRuleParser


1 package com.daffodilwoods.daffodildb.utils.parser;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Arrays JavaDoc;
5 import java.util.HashMap JavaDoc;
6 import java.util.Vector JavaDoc;
7 import java.util.List JavaDoc;
8 import java.io.*;
9 import java.net.URL JavaDoc;
10 import com.daffodilwoods.database.resource.*;
11 import com.daffodilwoods.database.utility.P;
12 import com.daffodilwoods.daffodildb.utils.DBStack;
13 import java.net.*;
14 import java.util.TreeMap JavaDoc;
15
16 /**
17  * This class is used for making ProductionRules Hierarchy by reading coding.txt file
18  * Rules made by this class is used for parsing.
19  */

20
21 public class ProductionRuleParser implements ProductionRuleParserConstants {
22
23    /**
24     * HashMap contains entries of definition of rules read from file.
25     */

26    private HashMap JavaDoc fileEntries;
27
28    /**
29     * HashMap contains entries of all rules.
30     * Key being the nameOfRule and Value being ProductionRules
31     */

32    private HashMap JavaDoc rulea;
33
34    /**
35     * HashMap containing entries of all Token Rules.
36     * Key being the nameOfRule and Value being ProductionRules
37     * This hashMap is used for making TokenProductionRules.
38     */

39    HashMap JavaDoc allRules;
40
41    /**
42     * Stack held to set recurssive flag in ProductionRules
43     */

44    DBStack recursion;
45
46    /**
47     * Boolean Flag For Token, If True then token ProductionRules are being made
48     */

49    boolean tokenFlag;
50
51    /**
52     * Vector used to hold rules withcomparablewithhashmap
53     */

54    protected List JavaDoc withHashMapWithBinary;
55
56    /**
57     * Stack containing HashMap Rules , Rules having multiple parents.
58     * This rules are read from file withHashMapRules.
59     */

60    private ArrayList JavaDoc withHashMapRules;
61
62    private List JavaDoc nonHashMap;
63
64    /**
65     * Vector for NonReserved Word and Reserved Word
66     */

67    List JavaDoc reservedWord;
68    List JavaDoc nonReservedWord;
69
70    private String JavaDoc reserved = "SRESERVEDWORD1206543922"; // STRING's To WRITE
71
private String JavaDoc nonReserved = "SNONRESERVEDWORD136444255";
72
73    URL JavaDoc url;
74    ClassLoader JavaDoc classLoader;
75
76    public static final TokenGenerator tk=new TokenGenerator();
77
78    public ProductionRuleParser(ClassLoader JavaDoc classLoader0) throws DException{
79       this(null, classLoader0);
80    }
81
82    public ProductionRuleParser(URL JavaDoc urlPath, ClassLoader JavaDoc classLoader0) throws DException{
83       classLoader = classLoader0;
84       url = urlPath;
85       initialize();
86       initializeTokenGeneratorMaps();
87    }
88
89   private void initializeTokenGeneratorMaps() throws DException{
90     tk.reserveWords=new TreeMap JavaDoc(String.CASE_INSENSITIVE_ORDER);
91     String JavaDoc obj[]=new String JavaDoc[]{"ABSOLUTE","ADD","ADMIN","AFTER","AGGREGATE","ALL","ALLOCATE","ALTER",
92         "AND","ANY","ARE","ARRAY","AS","ASC","ASSERTION","AT","AUTHORIZATION","BEFORE","BEGIN","BIGINT","BINARY","BIT","BLOB","BOOLEAN","BOTH","BREADTH","BY","BYTE", "CALL","CASCADE","CASCADED","CASE","CAST","CATALOG","CHAR","CHARACTER","CHECK","CLASS","CLOB","CLOSE","COLLATE","COLLATION","COLUMN","COMMIT",
93         "COMPLETION","CONNECT","CONNECTION","CONSTRAINT","CONSTRAINTS","CONSTRUCTOR","CONTINUE","CORRESPONDING","CREATE","CROSS","CUBE","CURRENT","CURRENT_DATABASE", "CURRENT_DATE","CURRENT_PATH","CURRENT_ROLE","CURRENT_TIME","CURRENT_TIMESTAMP",
94         "CURRENT_USER","CURRENTVAL","CURSOR","CYCLE"/*,"DATA"*/,"DATE","DAY","DEALLOCATE","DEC","DECIMAL","DECLARE", "DEFAULT","DEFERRABLE","DEFERRED","DELETE","DEPTH","DEREF","DESC","DESCRIBE","DESCRIPTOR",
95         "DESTROY","DESTRUCTOR","DETERMINISTIC","DICTIONARY","DIAGNOSTICS","DISCONNECT", "DISTINCT","DOMAIN","DOUBLE","DROP","DYNAMIC","EACH","ELSE","END","EQUALS","ESCAPE","EVERY","EXCEPT","EXCEPTION","EXEC","EXECUTE","EXTERNAL",
96         "FALSE","FETCH","FIRST","FLOAT","FOR","FOREIGN","FOUND","FROM","FREE","FULL", "FUNCTION","GENERAL","GET","GLOBAL","GO","GOTO","GRANT","GROUP","GROUPING",
97         "HASRECORD","HAVING","HOST","HOUR","IDENTITY","IGNORE","IMMEDIATE","IN","INDICATOR","INITIALIZE","INITIALLY","INNER","INOUT","INPUT","INSERT","INT","INTEGER","INTERSECT","INTERVAL",
98         "INTO","IS","ISOLATION","ITERATE","JOIN","KEY","LANGUAGE","LARGE","LAST","LATERAL","LEFT","LESS","LEVEL","LIKE", "LOCAL","LOCALTIME","LOCALTIMESTAMP","LOCATOR","LONG","LONGINT",
99         "MAP","MATCH","MINUTE","MODIFIES","MODIFY","MODULE","MONTH","NAMES","NATIONAL","NATURAL","NCHAR","NCLOB","NEW","NEXTVAL","NO","NONE", "NOT","NULL","NUMBER","NUMERIC","OF","OFF","OLD","ON","ONLY","OPEN",
100         "OR","ORDER","ORDINALITY","OUT","OUTER","OUTPUT","PAD","PARAMETER","PARTIAL","PATH","POSTFIX","PRECISION","PREORDER","PREPARE","PRESERVE","PRIMARY",
101         "PRIOR","PRIVILEGES","PROCEDURE","PUBLIC","READ","READS","REAL","RECURSIVE","REF","REFERENCES","REFERENCING","RELATIVE","RELEASE","RESTRICT","RETURN","RETURNS","REVOKE","RIGHT", "ROLLBACK","ROLLUP","ROUTINE","ROW","ROWNUM","ROWS","SAVEPOINT","SCHEMA","SCROLL","SCOPE",
102         "SEARCH","SECOND","SECTION","SELECT","SEQUENCE","SESSION","SESSION_USER","SET","SETS","SIZE", "SMALLINT","SOME","SPACE","SPECIFIC","SPECIFICTYPE","SQL","SQLEXCEPTION","SQLSTATE","SQLWARNING","START","STATEMENT","STATIC","STRUCTURE","SYSTEM_USER",
103         "TABLE","TEMPORARY","TERMINATE","THAN","THEN","TIME","TIMESTAMP","TIMEZONE_HOUR","TIMEZONE_MINUTE","TINYINT","TO","TRAILING","TRANSACTION","TRANSLATION",
104         "TREAT","TRIGGER","TRUE","UNDER","UNION","UNIQUE","UNKNOWN","UNNEST","UPDATE","USAGE","USER","USING","VALUES","VARBINARY","VARCHAR","VARCHAR2","VARIABLE",
105         "VARYING","VIEW","WHENEVER","WHERE","WITH","WITHOUT","WORK","WRITE","ZONE","CONDITION", "DO","ELSEIF","EXIT","HANDLER","IF","ITERATE","LEAVE","LOOP","REDO"/*,"REPEAT"*/,"RESIGNAL","SIGNAL","UNDO","UNTIL","WHILE","JAVAPARAMETER", "STRING","SYSDATE"};
106     for(int i=0;i<obj.length;i++)
107       tk.reserveWords.put(obj[i],obj[i]);
108     obj=new String JavaDoc[]{"NEXT","OBJECT","ROLE","ACTION","COUNT","AVG","LIMIT","MAX","OPERATION","PREFIX","RESULT","SUM","WHEN","MIN","REPEAT","CONTAINS","DATA","ABS","ACOS","ADA","ALIAS","ASENSITIVE","ASCII","ASSIGNMENT","ASENSITIVE","ASIN","ASYMMETRIC","ATAN","ATAN2","ATOMIC","ATTRIBUTE","AUTOINCREMENT","B",
109         "BETWEEN","BIT_LENGTH","BITVAR","C","CALLED","CARDINALITY","CATALOG_NAME","CEILING","CHAIN","CHAR_LENGTH","CHARACTER_LENGTH","CHARACTER_SET_CATALOG","CHARACTER_SET_NAME","CHARACTERISTICS",
110         "CHARACTER_SET_SCHEMA","CHECKED","CLASS_ORIGIN","COALESCE","COBOL","COLLATION_CATALOG","COLLATION_NAME","COLLATION_SCHEMA","COLUMN_NAME","COMMAND_FUNCTION","COMMAND_FUNCTION_CODE","COMMITTED","CONCAT","CONDITION_NUMBER",
111         "CONNECTION_NAME","CONSTRAINT_CATALOG","CONSTRAINT_NAME","CONSTRAINT_SCHEMA",
112         "CONVERT","COS","COT","COUNTRY","CURDATE","CURSOR_NAME","CURTIME","CURTIMESTAMP","DATABASE","DATESPAN","DATETIME_INTERVAL_CODE","DATETIME_INTERVAL_PRECISION","DAYNAME",
113         "DAYOFMONTH","DAYOFWEEK","DAYOFYEAR","DEFINED","DEFINER","DEGREES","DERIVED","DIFFERENCE","DISPATCH","DYNAMIC_FUNCTION","DYNAMIC_FUNCTION_CODE",
114         "EXISTING","EXISTS","EXP","EXTRACT","FILESIZE","FILEGROWTH","FINAL","FLOOR","FORTRAN","FULLTEXT","G","GENERATED","GRANTED",
115         "HIERARCHY","HOLD","IFNULL","IMPLEMENTATION","INCREMENT","INDEX","INFIX","INSENSITIVE","INSTANCE","INSTANTIABLE","INVOKER","K","KEY_MEMBER","KEY_TYPE","LCASE","LENGTH","LOCATE","LOG","LOWER",
116         "LTRIM","M","MATERIALIZED","MAXVALUE","MESSAGE_LENGTH","MESSAGE_OCTET_LENGTH","MESSAGE_TEXT","METHOD","MINVALUE","MOD","MONTHNAME","MORE","MOUNT","MUMPS","NAME","NOMAXVALUE",
117         "NOW","NOCYCLE","NOMINVALUE","NOORDER","NULLABLE","NULLIF",
118         "OCTET_LENGTH","OPTIONS","ORDERING","OVERLAPS","OVERLAY","OVERRIDING","PASCAL","PARAMETER_MODE","OPTION","PARAMETERS",
119         "PARAMETER_NAME","PARAMETER_ORDINAL_POSITION","PARAMETER_SPECIFIC_CATALOG",
120         "PARAMETER_SPECIFIC_NAME","PARAMETER_SPECIFIC_SCHEMA","PASSWORD","PI","PLI","PLACING","POSITION","POWER","RADIANS","RAND","REPEATABLE","REPEAT","REPLACE","RETURNED_LENGTH"," RETURNED_OCTET_LENGTH",
121         "RETURNED_SQLSTATE","ROUND","ROUTINE_CATALOG","ROUTINE_NAME","ROUTINE_SCHEMA","ROW_COUNT","RTRIM","SCALE","SCHEMA_NAME","SECURITY","SELF","SENSITIVE","SERIALIZABLE","SERVER_NAME",
122         "SIMPLE","SIGN","SIN","SOUNDEX","SOURCE","SPECIFIC_NAME","SIMILAR","SQL_TSI_DAY","SQL_TSI_FRAC_SECOND","SQL_TSI_HOUR","SQL_TSI_MINUTE","SQL_TSI_MONTH","SQL_TSI_QUARTER","SQL_TSI_SECOND",
123         "SQL_TSI_WEEK","SQL_TSI_YEAR","SQRT","SUBLIST","SUBSTRING","SUPPORT","STATE","STYLE","SUBCLASS_ORIGIN","SYMMETRIC","SYSTEM","TABLE_NAME","TAN","THROW","TIMESTAMPADD","TIMESTAMPDIFF","TOP","TRANSACTIONS_COMMITTED","TRANSACTIONS_ROLLED_BACK","TRANSACTION_ACTIVE","TRANSFORM","TRANSFORMS","TRANSLATE","TRIGGER_CATALOG","TRIGGER_SCHEMA",
124         "TRIGGER_NAME","TRIM","TRUNCATE","TYPE","UCASE","UNICODE","UNCOMMITTED","UNNAMED","UPPER","USER_DEFINED_TYPE_CATALOG","USER_DEFINED_TYPE_NAME",
125         "USER_DEFINED_TYPE_SCHEMA","VALUE","WEEK","X","YEAR","CONDITION_IDENTIFIER","ISOPEN","NOTFOUND","A","C","D","E","F","a","b","c","d","e","f","x", "TRUNC" , "INITCAP"
126 , "DECODE" , "DUMP" , "SYS_CONTEXT" ,"LEADING" , "TRAILING" , "BOTH" };
127
128     tk.nonReserveWords=new TreeMap JavaDoc(String.CASE_INSENSITIVE_ORDER);
129     for(int i=0;i<obj.length;i++)
130       tk.nonReserveWords.put(obj[i],obj[i]);
131   }
132
133    private void initialize() throws DException{
134          fileEntries = new HashMap JavaDoc();
135          rulea = new HashMap JavaDoc();
136          allRules = new HashMap JavaDoc();
137          recursion = new DBStack();
138          withHashMapRules = new ArrayList JavaDoc();
139          withHashMapWithBinary = new DBStack();
140          nonHashMap = vectorForBestAndNonBest.getRulesWithHashMapToBeIncludedAsNonHashMap();
141          readFromFile1();
142          readFileForWithHashMapRules1();
143          testRetrievalOfFiles(); // reading Reserved and nonReserved Words from file
144
}
145
146    /**
147     * For reading HashMapRules from file in to an Stack withHashMapRules.
148     */

149    private void readFileForWithHashMapRules1() throws DException{
150       URL JavaDoc url1 = null;
151       if (url == null) {
152          url1 = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/withHashMapRules.obj");
153          if (url1 == null) {
154             throw new DException("DSE0", new Object JavaDoc[] {"withHashMapRules.obj file is missing in classpath"});
155          }
156       } else {
157          try {
158             url1 = new URL JavaDoc(url.getProtocol() + ":" + url.getPath() + "/withHashMapRules.obj");
159          }catch (MalformedURLException ex) {
160             throw new DException("DSE0", new Object JavaDoc[]{ex});
161          }
162       }
163       try {
164          ObjectInputStream ooin = new ObjectInputStream(new BufferedInputStream(url1.openStream()));
165
166          withHashMapRules = (ArrayList JavaDoc) ooin.readObject();
167          ooin.close();
168       } catch (ClassNotFoundException JavaDoc ex1) {
169          throw new DException("DSE0", new Object JavaDoc[] {ex1});
170       } catch (IOException ex1) {
171          throw new DException("DSE0", new Object JavaDoc[] {ex1});
172       }
173    }
174
175    /**
176     * For reading definition from coding file in an hashMap fileEntries.
177     * This definition does not uses RandomAccessFile.
178     */

179
180    private void readFromFile1() throws DException{
181     URL JavaDoc url1 = null;
182     if (url == null){
183       url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema");
184       try {
185         url = new URL JavaDoc(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema")));
186       }
187       catch (MalformedURLException ex2) {
188         ex2.printStackTrace();
189         throw new DException("DSE0",new Object JavaDoc[]{ex2});
190       }
191       try {
192          url1=new URL JavaDoc(url.getProtocol() + ":" + url.getPath() + "/parser.schema");
193       } catch (MalformedURLException ex) {
194          throw new DException("DSE0",new Object JavaDoc[]{ex});
195       }
196
197        if(url1 == null){
198           throw new DException("DSE0",new Object JavaDoc[]{"Parser.schema file is missing in classpath."});
199        }
200     }
201     else{
202        try {
203           url1=new URL JavaDoc(url.getProtocol() + ":" + url.getPath() + "/parser.schema");
204
205        } catch (MalformedURLException ex) {
206           throw new DException("DSE0",new Object JavaDoc[]{ex});
207        }
208     }
209     ArrayList JavaDoc arr1 = null;// String rule = null;
210
StringBuffer JavaDoc rule=null;
211     try {
212         LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream())));
213        arr1 = new ArrayList JavaDoc();
214        rule = new StringBuffer JavaDoc("");
215        while (true) {
216           String JavaDoc str1 = raf.readLine();
217           if (str1 == null) {
218              break;
219           }
220           String JavaDoc str = str1.trim();
221           if (str.length() == 0) {
222              if (rule.length() > 0) {
223                 arr1.add(rule.toString());
224              }
225              rule = new StringBuffer JavaDoc("");
226           } else {
227           rule.append(" ").append(str);
228        }
229        }
230        raf.close();
231     } catch (IOException ex1) {
232        ex1.printStackTrace();
233        throw new DException("DSE0",new Object JavaDoc[]{ex1});
234     }
235
236     if (rule.length() > 0)
237        arr1.add(rule.toString());
238     for (int i = 0; i < arr1.size(); i++) {
239        String JavaDoc str = (String JavaDoc) arr1.get(i);
240        int index = str.indexOf("::=");
241        if (index == -1) {
242           P.pln("Error " + str);
243           throw new DException("DSE0",new Object JavaDoc[]{"Rule is missing from parser.schema"});
244        }
245        String JavaDoc key = str.substring(0, index).trim();
246        String JavaDoc value = str.substring(index + 3).trim();
247        Object JavaDoc o = fileEntries.put(key, value);
248        if (o != null) {
249           new Exception JavaDoc("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace();
250        }
251     }
252 }
253
254    /**
255     * This Method is used for Making Entry in HashMap rulea of all rules
256     * This method is also used to load all rules classes.
257     */

258
259    private void makeEntryInHashMap(ProductionRules production, String JavaDoc className, String JavaDoc nameOfRule) {
260       if (production instanceof OptionalProductionRules || production instanceof OptionalProductionRulesWithHashMap)
261          return;
262       if (! (production instanceof RepetitiveProductionRules || production instanceof OrProductionRules || production instanceof RepetitiveProductionRulesWithHashMap || production instanceof OrProductionRulesWithHashMap) && tokenFlag)
263          allRules.put(nameOfRule, production);
264    }
265
266    /**
267     * This Function Initialize the name Of rule.
268     * for example : rulename abc-ss is changed as sql.abc_ss
269     * Initialised name of rule is used to load class into memory using reflection.
270     */

271    String JavaDoc initailizeNameOfClass(String JavaDoc nameRule) {
272       return updateNameOfRule(nameRule);
273    }
274
275    /**
276     * This method updates the nameOfRule to a desired format.
277     * For example : rulename abc-ss is changed as abc_ss
278     */

279    private String JavaDoc updateNameOfRule(String JavaDoc nameRule) {
280       char[] value = nameRule.toCharArray();
281       StringBuffer JavaDoc str = new StringBuffer JavaDoc();
282       for (int i = 0, count = value.length; i < count; i++)
283          if (value[i] == '-')
284             str.append('_');
285          else if (! (value[i] == ' ' || value[i] == ':' || value[i] == '(' || value[i] == ')' || value[i] == '\\' || value[i] == '\''))
286             str.append(value[i]);
287       return str.toString();
288    }
289
290    /**
291     * This method is used for making ProductionRules of ruleName passed.
292     * RuleNamed "charater string literal" is made as CharacterStringLiteralProductionRules
293     * Rules in KeyWord rule are made as KeyWordProductionRules.
294     * 0 type is set for StringProductionRules
295     * 1 type is set for KeyWordProductionRules
296     * 2 type is set for StringProductionRulesWithoutSpace
297     */

298    public ProductionRules getProductionRule(String JavaDoc productionRuleName) throws DException{
299       ProductionRules pr = getProductionRule2(productionRuleName);
300       modifyProductionRuleName(pr);
301       return pr;
302    }
303
304    private ProductionRules getProductionRule2(String JavaDoc productionRuleName) throws DException{
305       productionRuleName = productionRuleName.trim();
306       if (allRules != null) {
307          Object JavaDoc obj = allRules.get(productionRuleName);
308          if (obj != null)
309             return (ProductionRules) obj;
310       }
311       String JavaDoc temp = productionRuleName;
312       ProductionRules production = (ProductionRules) rulea.get(productionRuleName);
313       if (production == null) {
314          production = getProductionRuleObjectType(productionRuleName);
315          recursion.push(productionRuleName);
316          productionRuleName = getNameOfRule(production, productionRuleName, -1);
317          production.setProductionRuleName(productionRuleName);
318          production.ruleKey = production.nameOfRule;
319          rulea.put(productionRuleName, production);
320          makeEntryInHashMap(production, production.className, production.getProductionRuleName());
321          if (productionRuleName.equalsIgnoreCase(REGULARIDENTIFIER)) {
322             makeRangeProductionRules(production);
323          } else if (productionRuleName.equalsIgnoreCase(CHARACTERSTRINGLITERAL)) {
324            makeCharacterStringLiteralProductionRules('\'', production);
325
326          } else if (productionRuleName.equalsIgnoreCase(BITSTRINGLITERAL)) {
327             makeStringLiteralProductionRules(BinaryStringLiteralProductionRules.BITSTRINGTYPE, production);
328          } else if (productionRuleName.equalsIgnoreCase(HEXSTRINGLITERAL)) {
329             makeStringLiteralProductionRules(BinaryStringLiteralProductionRules.HEXSTRINGTYPE, production);
330          } else if (productionRuleName.equalsIgnoreCase(DELIMITEDIDENTIFIER)) {
331            makeCharacterStringLiteralProductionRules('"', production);
332          } else {
333             if (ifRuleForKeyWordProductionRule(temp)) // instead of this make a or rule orRule.and check for contains
334
getProductionRuleObject(production, temp, 1);
335             else
336                getProductionRuleObject(production, temp, 0);
337          }
338          recursion.pop();
339       }
340       if (!tokenFlag && !allRules.containsKey(temp))
341          CheckRecursive(temp, production);
342       return production;
343    }
344
345    /**
346     * RangeProductionRules
347     */

348    private void makeRangeProductionRules(ProductionRules production) {
349       ArrayList JavaDoc arr = new ArrayList JavaDoc(1);
350       RangeProductionRules rule = new RangeProductionRules(classLoader);
351       rule.setProductionRuleName("SpecialHandlingRule");
352       rule.ruleKey = "SpecialHandlingRule";
353       arr.add(rule);
354       production.setProductionRules(arr);
355    }
356
357    /**
358     * Function for getting characterstringliteralproductionrules
359     * FLAG TRUE FOR CHARACTERSTRINGLITERAL
360     * FLAG FALSE FOR DELIMITEDIDENTIFIER
361
362    private void makeCharacterStringLiteralProductionRules(boolean flag, ProductionRules production) {
363       ArrayList arr = new ArrayList(1);
364       CharacterStringLiteralProductionRules rule = new CharacterStringLiteralProductionRules(flag, classLoader);
365       rule.setProductionRuleName("SpecialHandlingRule");
366       rule.ruleKey = "SpecialHandlingRule";
367       arr.add(rule);
368       production.setProductionRules(arr);
369    }
370 */

371
372   /**
373    * Function for getting characterstringliteralproductionrules
374    * c == ''' FOR CHARACTERSTRINGLITERAL
375    * c == '"' FOR DELIMITEDIDENTIFIER
376    */

377   private void makeCharacterStringLiteralProductionRules(char c, ProductionRules production) {
378     ArrayList JavaDoc arr = new ArrayList JavaDoc(1);
379     CharacterStringLiteralProductionRules rule = new CharacterStringLiteralProductionRules(c, classLoader);
380     rule.setProductionRuleName("SpecialHandlingRule");
381     rule.ruleKey = "SpecialHandlingRule";
382     arr.add(rule);
383     production.setProductionRules(arr);
384 }
385
386   private void makeStringLiteralProductionRules(int flag, ProductionRules production) {
387       ArrayList JavaDoc arr = new ArrayList JavaDoc(1);
388       BinaryStringLiteralProductionRules rule = new BinaryStringLiteralProductionRules(classLoader);
389       rule.setProductionRuleName("StringLiteralHandlingRule");
390       rule.ruleKey = "StringLiteralHandlingRule";
391       arr.add(rule);
392       production.setProductionRules(arr);
393       rule.setClassName(flag);
394    }
395
396    /**
397     * This method is used to set recursive flag true for rules which are recursive.
398     */

399    private void CheckRecursive(String JavaDoc productionRuleName, ProductionRules production) {
400       int index = recursion.indexOf(productionRuleName);
401       if (index == -1)
402          return;
403       int size = recursion.size() - 1;
404       while (index <= size) {
405          ProductionRules productionRule = (ProductionRules) rulea.get(recursion.get(index));
406          if (!productionRule.recursiveflag)
407             productionRule.recursiveflag = true;
408          ++index;
409       }
410    }
411
412    /**
413     * This method is used to get Type of ProductionRule of ruleName passed.
414     */

415    private ProductionRules getProductionRuleObjectType(String JavaDoc productionRuleName) throws DException{
416       return makingProductionRuleObject(makeStack(getProductionRuleString(productionRuleName)), productionRuleName);
417    }
418
419    /**
420     * This Method is used for getting ProductionRule String from HashMap of ruleName passed.
421     */

422    private String JavaDoc getProductionRuleString(String JavaDoc name) throws DException{
423       name = name.trim();
424       if (name.length() == 0)
425         throw new DException("DSE885", new Object JavaDoc[] {name});
426       StringBuffer JavaDoc str=new StringBuffer JavaDoc("<");
427       str.append(name).append(">");
428       String JavaDoc toFollow = (String JavaDoc) fileEntries.get(str.toString());
429       if (toFollow == null)
430         throw new DException("DSE324", new Object JavaDoc[] {name});
431       return toFollow;
432    }
433
434    /**
435     * This method is used for getting ProductionRules for an object passed with it's ruleName.
436     * Type passed is used to differentiate types of StringProductionRules.
437     */

438
439    private ProductionRules getProductionRuleObject(ProductionRules production, String JavaDoc productionRuleName, int type) throws DException {
440       char queryArray[] = getProductionRuleString(productionRuleName).toCharArray();
441       makingProductionRules(production, queryArray, type);
442       production.setProductionRuleName(productionRuleName);
443       return production;
444    }
445
446    /**
447     * Assembling on basis of OrProductionRule,UnionProductionRule,OptionalProductionRule,RepititiveProductionRule
448     * 1. If keywords occur or words with capital letters then object of StringProductionRules
449     * 2. If string ocuur starting with < and ending with > then object of ProductionRules
450     * 3. Assembling of these above two occur on the basis of
451     * a) if","symbol occurs then type is setted as OrProductionRule
452     * b) if no","symbol occurs then type is setted as UnionProductionRule.
453     * NOW , till string ends add all objects of any type in arrayList
454     * and then set arrayList acc to type.
455     * Now if [ occurs then productionRule inside [] are added as OptionalproductionRule
456     * Now if ... occurs then object of repetitive production rules.
457     * StringProductionRules is made of different types.
458     * Argument passed is ProductionRules Object for which we are going on.
459     * Character array of definition read from file for rule.
460     * Type used for differentiating types of StringProductionRules.
461     * Return Type is ProductionRules With it's arrayList initialised.
462     * This method is also used for getting ComparableRules for OrRules when tokenFlag is true only.
463     */

464    private ProductionRules makingProductionRules(ProductionRules productionRule, char productionRuleArray[], int flag) throws DException {
465       ArrayList JavaDoc rules = new ArrayList JavaDoc();
466       DBStack stack = new DBStack();
467       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(100);
468       int length = productionRuleArray.length;
469       for (int index = 0; index < length; ++index) {
470          switch (productionRuleArray[index]) {
471             case '<':
472                if (length > 2) {
473                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
474                   Object JavaDoc object[] = processingForAngularBracket(productionRuleArray, index);
475                   index = object[1].hashCode();
476                   if (!tokenFlag && ( (ProductionRules) object[0]).nameOfRule.equalsIgnoreCase("boolean value expression")
477                       && productionRule.nameOfRule.equalsIgnoreCase("SQL 99")) {
478                      stack.pop();
479                      break;
480                   }
481                   if (!tokenFlag && ( (ProductionRules) object[0]).nameOfRule.equalsIgnoreCase("token")) {
482                      while (index < length && productionRuleArray[index] != '<')
483                         ++index;
484                      --index;
485                   } else {
486                      rules.add( (ProductionRules) object[0]);
487                      stack.push(new Integer JavaDoc(rules.size() - 1));
488                   }
489                } else
490                   buffer.append(productionRuleArray[index]);
491                break;
492             case '|':
493                if (length > 2) {
494                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
495                   rules.add(makingUnionProductionRuleObject(stack, rules));
496                   stack.push(new Integer JavaDoc(rules.size() - 1));
497                   stack.push("|");
498                } else
499                   buffer.append(productionRuleArray[index]);
500                break;
501             case '[':
502                if (length > 1) {
503                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
504                   stack.push("[");
505                } else
506                   buffer.append(productionRuleArray[index]);
507                break;
508             case ']':
509                if (length > 1) {
510                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
511                   rules.add(EmptyingStack("]", stack, rules));
512                   stack.push(new Integer JavaDoc(rules.size() - 1));
513                } else
514                   buffer.append(productionRuleArray[index]);
515                break;
516             case '{':
517                if (length > 1) {
518                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
519                   stack.push("{");
520                } else
521                   buffer.append(productionRuleArray[index]);
522                break;
523             case '}':
524                if (length > 1) {
525                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
526                   ProductionRules productionRule2 = EmptyingStack("}", stack, rules);
527                   rules.add(productionRule2);
528                   stack.push(new Integer JavaDoc(rules.size() - 1));
529                } else
530                   buffer.append(productionRuleArray[index]);
531                break;
532             case '.':
533                if ( (index + 2) < length) {
534                   if (productionRuleArray[index + 1] == '.' && productionRuleArray[index + 2] == '.') {
535                      rules.add(handlingForRepetitiveGroup(rules));
536                      index += 2;
537                      break;
538                   }
539                }
540             default:
541                if (productionRuleArray[index] == ' ')
542                   handlingForStringProductionRules(null, rules, buffer, stack, flag);
543                else
544                   buffer.append(productionRuleArray[index]);
545          }
546       }
547       handlingForStringProductionRules(productionRule, rules, buffer, stack, flag);
548       ProductionRules productionrule = gettingProductionRule(productionRule, rules, stack);
549       return productionrule;
550    }
551
552    /**
553     * This method is used for checking for productionrule in HashMap, If Exist then returned from
554     * HashMap otherwise making ProductionRules object acc to type passed.
555     * RuleKey is the key for making entries in hashmap
556     */

557    private ProductionRules checkingForHashMap(String JavaDoc nameOfRule, ArrayList JavaDoc list, int type, String JavaDoc ruleKey) {
558       String JavaDoc ruleName = nameOfRule;
559       nameOfRule = getNameOfRule(null, nameOfRule, type); // making nameOFRule as rep + string and opt + string
560
ruleKey = getNameOfRule(null, ruleKey, type);
561       if (allRules != null) {
562          Object JavaDoc obj = allRules.get(nameOfRule); // getting from tokenrules hashMap
563
if (obj != null) {
564             return (ProductionRules) obj;
565          }
566       }
567       ProductionRules productionRules = (ProductionRules) rulea.get(ruleKey);
568       if (productionRules == null) { //|| type == OPTIONALPRODUCTIONRULE ){ // for making duplicate reference
569
productionRules = makingProductionRuleObject(type, ruleKey); // nameOfRule is replaced by ruleKey
570
productionRules.setProductionRuleName(nameOfRule);
571          productionRules.setProductionRules(list);
572          productionRules.ruleKey = ruleKey;
573          rulea.put(ruleKey, productionRules); // to put by key
574
makeEntryInHashMap(productionRules, productionRules.className, productionRules.nameOfRule);
575       }
576       return productionRules;
577    }
578
579    /**
580     * This method is used for making RepetitiveProductionRules for rules passed.
581     */

582    private ProductionRules handlingForRepetitiveGroup(ArrayList JavaDoc rules) {
583       ArrayList JavaDoc array = new ArrayList JavaDoc();
584       ProductionRules productionRules = (ProductionRules) rules.remove(rules.size() - 1);
585       array.add(productionRules);
586       String JavaDoc nameOfRule = productionRules.nameOfRule;
587       return checkingForHashMap(nameOfRule, array, REPETITIVEPRODUCTIONRULE, nameOfRule);
588    }
589
590    /**
591     * This method is used for making ProductionRules having an index maintained in Stack.
592     * ProductionRules passed is rule for which we are going on.
593     * ArrayList Rules is setted as rules arrayList for rule
594     * Stack contains index of rules in an arrayList.
595     */

596    public ProductionRules gettingProductionRule(ProductionRules productionRules, ArrayList JavaDoc rules, DBStack stack) {
597       int max = stack.size();
598       if (max == 0)
599          return productionRules;
600       ArrayList JavaDoc list = new ArrayList JavaDoc();
601       while (max >= 1) {
602          Object JavaDoc temporary = stack.pop();
603          if (temporary instanceof Integer JavaDoc)
604             list.add(rules.remove(temporary.hashCode()));
605          else if (temporary.equals("|")) {
606             ProductionRules production = processingForRestElementsInStack(stack, list, UNIONPRODUCTIONRULE);
607             if (production != null) {
608                list = new ArrayList JavaDoc();
609                list.add(production);
610             }
611             poppingOutAllOr(stack);
612             max = stack.size() + 1;
613          }
614          --max;
615       }
616       productionRules.setProductionRules(list);
617       return productionRules;
618    }
619
620    /**
621     * This method is used for processing Rest of Elements in Stack.
622     */

623    private ProductionRules processingForRestElementsInStack(DBStack stack, ArrayList JavaDoc list, int type) {
624       if (list.size() > 1) {
625          String JavaDoc[] array = gettingNames(list, type);
626          return checkingForHashMap(array[0], list, type, array[1]);
627       }
628       return null;
629    }
630
631    /**
632     * For Getting productionruleObject ruleName read between < and >
633     * Retruns Object array for rule name to be made.
634     * Object[0] for ProductionRules
635     * Object[1] for index of query character array.
636     */

637    private Object JavaDoc[] processingForAngularBracket(char productionRuleArray[], int index) throws DException{
638       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(100);
639       while (productionRuleArray[++index] != '>')
640          buffer.append(productionRuleArray[index]);
641       ProductionRules productionRules = getProductionRule2(new String JavaDoc(buffer));
642       return new Object JavaDoc[] {productionRules, new Integer JavaDoc(index)};
643    }
644
645    /**
646     * This method is used for making StringProductionRules.
647     */

648    private void handlingForStringProductionRules(ProductionRules productionRules, ArrayList JavaDoc rules, StringBuffer JavaDoc buffer, DBStack stack, int flag) {
649       if (buffer.length() == 0)
650          return;
651       String JavaDoc temporary = new String JavaDoc(buffer);
652       if (!temporary.trim().equals("")) {
653          if (stack.size() == 0 && productionRules != null) {
654             StringProductionRules strp = (StringProductionRules) productionRules;
655             strp.setString(temporary, null);
656             strp.ruleKey = strp.keyWord;
657             return;
658          }
659          StringProductionRules rule = flag == 1 ? new KeyWordProductionRules(classLoader) : new StringProductionRules(classLoader);
660          rule.setProductionRuleName(temporary);
661          String JavaDoc temporary1 = updateNameOfRule(rule.nameOfRule);
662          if ( (nonReservedWord.contains(temporary1) || temporary.equalsIgnoreCase("DATA")) && !temporary.equalsIgnoreCase("ROWNUM")) {
663             rule.className = initailizeNameOfClass(nonReserved); // u can do here itself as sql + . + name
664
rule.setString(temporary, nonReserved);
665          } else if ( (reservedWord.contains(temporary1) || temporary.equalsIgnoreCase("ROWNUM"))) {
666             rule.className = initailizeNameOfClass(reserved);
667             rule.setString(temporary, reserved);
668          } else
669             rule.setString(temporary, null);
670          rule.ruleKey = rule.nameOfRule; // same as nameOfRule
671
rules.add(rule);
672          stack.push(new Integer JavaDoc(rules.size() - 1));
673          allRules.put(rule.nameOfRule, rule);
674          rulea.put(rule.nameOfRule, rule);
675       }
676       buffer.setLength(0);
677    }
678
679    /**
680     * Function for writing reservedWords and nonReservedWords Vectors
681     */

682
683    /*private void makeEntryInVectors(ProductionRules rule){
684       if ( type == 1 ){
685         String name1 = updateNameOfRule(rule.nameOfRule);
686         if ( nonReservedWord != null && !nonReservedWord.contains(name1) )
687            nonReservedWord.add(name1);
688       }
689       if ( type == 2 ){
690         String name = updateNameOfRule(rule.nameOfRule);
691         if ( reservedWord != null && !reservedWord.contains(name) )
692          reservedWord.add(name);
693       }
694         }*/

695
696    /**
697     * Making StringProductionRules Object
698     */

699
700    /*private void makingStringProductionRulesObjects(ProductionRules rule,String hh){
701       try{
702         if(rule.classMaker == null )
703              rule.classMaker = Class.forName(hh);
704         if ( rule.classObject == null )
705              rule.classObject = rule.classMaker.newInstance();
706       }catch(Exception e){
707       }
708          }*/

709
710    /**
711     * This method is used for making Rules lying between []
712     * This method is also used for making Rules lying between {}
713     */

714    private ProductionRules EmptyingStack(String JavaDoc oper, DBStack stack, ArrayList JavaDoc rules) {
715       int type = -1;
716       ArrayList JavaDoc list = new ArrayList JavaDoc(); // for productionRules in [ ]
717
ProductionRules productionRules = null;
718       if (oper.equals("}"))
719          oper = "{";
720       if (oper.equals("]")) {
721          oper = "[";
722          type = OPTIONALPRODUCTIONRULE;
723       } while (true) {
724          Object JavaDoc temporary = stack.pop();
725          if (temporary instanceof Integer JavaDoc)
726             list.add(rules.remove(temporary.hashCode()));
727          else if (temporary.equals("|")) {
728             ProductionRules production = processingForRestElementsInStack(stack, list, UNIONPRODUCTIONRULE);
729             if (production != null) {
730                list = new ArrayList JavaDoc();
731                list.add(production);
732             }
733             poppingOutAllOr(stack);
734             productionRules = makingProductionRuleObject(ORPRODUCTIONRULE, ""); //3
735
}
736          if (oper.equals(temporary))
737             break;
738       }
739       ProductionRules rr = gettingObject(list, productionRules, type);
740       return rr;
741    }
742
743    /**
744     * This method is used for popping out all or's from Stack.
745     */

746    private void poppingOutAllOr(DBStack stack) {
747       int i = stack.size() - 1;
748       while (i >= 0) {
749          Object JavaDoc oper = stack.get(i);
750          if (oper.equals("{") || oper.equals("["))
751             break;
752          else if (oper.equals("|"))
753             stack.remove(i);
754          --i;
755       }
756    }
757
758    private ProductionRules gettingObject(ArrayList JavaDoc list, ProductionRules productionRules, int type) {
759       ArrayList JavaDoc array1;
760       if (list.size() == 1 && type != -1) { // to differentiate case [ NOT ] with [ WITH ADMIN OPTION ]
761
String JavaDoc array[] = gettingNames(list, type);
762          return checkingForHashMap(array[0], list, type, array[1]);
763       }
764       if (productionRules != null) {
765          String JavaDoc[] array = gettingNames(list, type);
766          String JavaDoc nameOfRule = array[0];
767          String JavaDoc ruleKey = array[1];
768          if (rulea.containsKey(ruleKey))
769             productionRules = (ProductionRules) rulea.get(ruleKey);
770          else {
771             productionRules = makingProductionRuleObject(ORPRODUCTIONRULE, ruleKey); // nameOfRule is replaced By ruleKey
772
productionRules.setProductionRuleName(nameOfRule);
773             productionRules.ruleKey = ruleKey;
774             productionRules.setProductionRules(list);
775             rulea.put(ruleKey, productionRules);
776             makeEntryInHashMap(productionRules, productionRules.className, productionRules.nameOfRule);
777          }
778          array1 = new ArrayList JavaDoc();
779          array1.add(productionRules);
780          list = array1;
781       }
782       if (list.size() > 1) { // if size of list is > 1 and orproductionRules is not set
783
String JavaDoc[] array = gettingNames(list, type);
784          String JavaDoc nameOfRule = array[0];
785          String JavaDoc ruleKey = array[1];
786          productionRules = checkingForHashMap(nameOfRule, list, UNIONPRODUCTIONRULE, ruleKey);
787          array1 = new ArrayList JavaDoc();
788          array1.add(productionRules);
789          list = array1;
790       }
791       if (type == -1) {
792          if (productionRules == null)
793             return (ProductionRules) list.remove(list.size() - 1);
794          return productionRules;
795       }
796       String JavaDoc nameOfRule = ( (ProductionRules) list.get(0)).nameOfRule;
797       String JavaDoc ruleKey = ( (ProductionRules) list.get(0)).ruleKey;
798       return checkingForHashMap(nameOfRule, list, type, ruleKey);
799    }
800
801    /**
802     * For making NameOfRule from arrayLIst passed to it
803     */

804    private String JavaDoc[] gettingNames(ArrayList JavaDoc list, int type) {
805       StringBuffer JavaDoc bufferForgettingNames = new StringBuffer JavaDoc(100);
806       StringBuffer JavaDoc bufferForRuleKey = new StringBuffer JavaDoc(100);
807       int size = list.size() - 1;
808       for (int i = size; i >= 0; i--) {
809          ProductionRules rule = (ProductionRules) list.get(i);
810          if (rule instanceof StringProductionRules) {
811             bufferForgettingNames.append( ( (StringProductionRules) rule).keyWord);
812             bufferForRuleKey.append( ( (StringProductionRules) rule).nameOfRule);
813          } else {
814             bufferForgettingNames.append(rule.nameOfRule);
815             bufferForRuleKey.append(rule.nameOfRule);
816          }
817       }
818       return new String JavaDoc[] {bufferForgettingNames.toString(), bufferForRuleKey.toString()};
819    }
820
821    /**
822     * This method is used for making ProductionRules WithHashMap if nameOfRule passed has an entry in withHashMapRules Stack.
823     * ProductionRules object is made for type passed.
824     */

825    private ProductionRules makingProductionRuleObject(int type, String JavaDoc nameOfRule) {
826       switch (type) {
827          case UNIONPRODUCTIONRULE:
828             if ( (withHashMapRules.contains(nameOfRule) || withHashMapWithBinary.contains(nameOfRule)) && !nonHashMap.contains(nameOfRule))
829                return new UnionProductionRulesWithHashMap(classLoader);
830             return new UnionProductionRules(classLoader);
831          case OPTIONALPRODUCTIONRULE:
832             if ( (withHashMapRules.contains(nameOfRule) || withHashMapWithBinary.contains(nameOfRule)) && !nonHashMap.contains(nameOfRule))
833                return new OptionalProductionRulesWithHashMap(classLoader);
834             return new OptionalProductionRules(classLoader);
835          case ORPRODUCTIONRULE:
836             if ( (withHashMapRules.contains(nameOfRule) || withHashMapWithBinary.contains(nameOfRule)) && !nonHashMap.contains(nameOfRule))
837                return new OrProductionRulesWithHashMap(classLoader);
838             return new OrProductionRules(classLoader);
839          case REPETITIVEPRODUCTIONRULE:
840             if ( (withHashMapRules.contains(nameOfRule) || withHashMapWithBinary.contains(nameOfRule)) && !nonHashMap.contains(nameOfRule))
841                return new RepetitiveProductionRulesWithHashMap(classLoader);
842             return new RepetitiveProductionRules(classLoader);
843          case STRINGPRODUCTIONRULE:
844             return new StringProductionRules(classLoader);
845          case SIMPLEPRODUCTIONRULE:
846             if ( (withHashMapRules.contains(nameOfRule) || withHashMapWithBinary.contains(nameOfRule)) && !nonHashMap.contains(nameOfRule))
847                return new SimpleProductionRulesWithHashMap(classLoader);
848             return new SimpleProductionRules(classLoader);
849       }
850       return null;
851    }
852
853    /**
854     * This Method is used for makingUnionProductionRules object.
855     */

856    private ProductionRules makingUnionProductionRuleObject(DBStack stack, ArrayList JavaDoc rules) {
857       int max = stack.size();
858       ArrayList JavaDoc array = new ArrayList JavaDoc();
859       while (max >= 1) {
860          Object JavaDoc temporary = stack.peek();
861          if (temporary instanceof Integer JavaDoc) {
862             temporary = stack.pop();
863             array.add(rules.remove(temporary.hashCode()));
864          } else if (temporary==null || temporary.getClass() == String JavaDoc.class)
865             break;
866          --max;
867       }
868       if (array.size() == 1)
869          return (ProductionRules) array.get(0);
870       String JavaDoc[] array1 = gettingNames(array, UNIONPRODUCTIONRULE);
871       String JavaDoc nameOfRule = array1[0];
872       String JavaDoc ruleKey = array1[1];
873       return checkingForHashMap(nameOfRule, array, UNIONPRODUCTIONRULE, ruleKey);
874    }
875
876    /**
877     * This Method is used for getting NameOfRule for Production Rule passed
878     */

879    private String JavaDoc getNameOfRule(ProductionRules production, String JavaDoc str, int type) {
880       StringBuffer JavaDoc strbuf=null;
881       if (type == REPETITIVEPRODUCTIONRULE || production instanceof RepetitiveProductionRules
882           || production instanceof RepetitiveProductionRulesWithHashMap){
883          strbuf = new StringBuffer JavaDoc("Rep");
884          strbuf.append(str);
885          return strbuf.toString();
886       }
887       if (type == OPTIONALPRODUCTIONRULE || production instanceof OptionalProductionRules
888           || production instanceof OptionalProductionRulesWithHashMap){
889          strbuf = new StringBuffer JavaDoc("Opt");
890          strbuf.append(str);
891          return strbuf.toString();
892       }
893       return str;
894    }
895
896    /**
897     * This method is used for making Stack for getting type of productionrule without evaluating.
898     */

899    private int makeStack(String JavaDoc name) {
900       char[] array = name.trim().toCharArray();
901       DBStack stack = new DBStack();
902       int length = array.length;
903       for (int i = 0; i < length; ++i) {
904          switch (array[i]) {
905             case '<':
906                if (length > 2)
907                   stack.push("<");
908                else
909                   stack.push(new Character JavaDoc('<'));
910                break;
911             case '>':
912                if (length > 2)
913                   EmptyingStackTill(stack, "<");
914                else
915                   stack.push(new Character JavaDoc('>'));
916                break;
917             case '|':
918                if (length > 2)
919                   stack.push("|");
920                else
921                   stack.push(new Character JavaDoc('|'));
922                break;
923             case '[':
924                if (length > 1)
925                   stack.push("[");
926                else
927                   stack.push(new Character JavaDoc('['));
928                break;
929             case ']':
930                if (length > 1)
931                   EmptyingStackTill(stack, "[");
932                else
933                   stack.push(new Character JavaDoc(']'));
934                break;
935             case '{':
936                if (length > 1)
937                   stack.push("{");
938                else
939                   stack.push(new Character JavaDoc('{'));
940                break;
941             case '}':
942                if (length > 1)
943                   EmptyingStackTill(stack, "{");
944                else
945                   stack.push(new Character JavaDoc('}'));
946                break;
947             case '.':
948                if ( (i + 2) < array.length) {
949                   if (array[i + 1] == '.' && array[i + 2] == '.') {
950                      stack.pop();
951                      stack.push("%R");
952                      i = i + 2;
953                      break;
954                   }
955                }
956             default:
957                if (array[i] != ' ' && i < array.length)
958                   stack.push(new Character JavaDoc(array[i]));
959                else
960                   checkingForString(stack);
961          }
962       }
963       return returningType(stack);
964    }
965
966    private void checkingForString(DBStack stack) {
967       int j = stack.size() - 1;
968       while (j >= 0 && stack.get(j)instanceof Character JavaDoc) {
969          char ch = ( (Character JavaDoc) stack.get(j)).charValue();
970          if (Character.isUpperCase(ch)) {
971             stack.pop();
972             --j;
973             if (j < 0)
974                stack.push("&O");
975          } else {
976             stack.push("&O");
977             break;
978          }
979       }
980    }
981
982    /**
983     * Returning Type Of Object.
984     */

985    private int returningType(DBStack stack) {
986       int max = stack.size();
987       if (stack.indexOf("|") != -1) {
988          if (max <= 2)
989             return STRINGPRODUCTIONRULE; // for "||"
990
return ORPRODUCTIONRULE; // for orproductionRule
991
}
992       if (max >= 1)
993          return checkingForUnion(stack);
994       return STRINGPRODUCTIONRULE;
995    }
996
997    /**
998     * CheckingFor Union Rule in Stack.
999     */

1000   private int checkingForUnion(DBStack stack) {
1001      int i = 0;
1002      int type = STRINGPRODUCTIONRULE; // for characters
1003
int max = stack.size();
1004      while (i < max) {
1005         if (stack.get(i)instanceof String JavaDoc) {
1006            String JavaDoc str = (String JavaDoc) stack.get(i);
1007            if (max == 1)
1008               return SIMPLEPRODUCTIONRULE; //<>
1009
if (str.equals("&O") || str.equals("^C") || str.equals("%A") || str.equals("%R"))
1010               type = UNIONPRODUCTIONRULE;
1011         }
1012         ++i;
1013      }
1014      return type;
1015   }
1016
1017   /**
1018    * Emtying Stack for string s passed.
1019    */

1020   private void EmptyingStackTill(DBStack stack, String JavaDoc s) {
1021      String JavaDoc str;
1022      if (s.equals("[") && stack.size() > 1)
1023         str = "&O";
1024      else if (s.equals("[") && stack.size() == 1)
1025         str = "%S";
1026      else if (s.equals("{"))
1027         str = "^C";
1028      else {
1029         str = "%A";
1030         if (stack.size() == 1) {
1031            stack.push("%S");
1032            return;
1033         } else if (stack.empty()) {
1034            stack.push(">");
1035            return;
1036         }
1037      }
1038      while (true) {
1039         Object JavaDoc temp = stack.pop();
1040         if (temp.equals(s))
1041            break;
1042      }
1043      stack.push(str);
1044   }
1045
1046   private boolean ifRuleForKeyWordProductionRule(String JavaDoc temp) {
1047      if (temp.equalsIgnoreCase(DATELITERAL) || temp.equalsIgnoreCase(TIMELITERAL) ||
1048          temp.equalsIgnoreCase(TIMESTAMPLITERAL) || temp.equalsIgnoreCase(RESERVEDWORD) ||
1049          temp.equalsIgnoreCase(NONRESERVEDWORD) || temp.equalsIgnoreCase(NATIONALCHARACTERSTRINGLITERAL) ||
1050          temp.equalsIgnoreCase(BITSTRINGLITERAL) || temp.equalsIgnoreCase(HEXSTRINGLITERAL) ||
1051          temp.equalsIgnoreCase(BINARYSTRINGLITERAL) || temp.equalsIgnoreCase(INTERVALLITERAL) ||
1052          temp.equalsIgnoreCase(BOOLEANLITERAL) || temp.equalsIgnoreCase("multiplier"))
1053         return true;
1054      return false;
1055   }
1056
1057   private void testRetrievalOfFiles() throws DException {
1058      Class JavaDoc cls = getClass();
1059      URL JavaDoc url1 = null;
1060      if (url == null) {
1061         url1 = cls.getResource("/com/daffodilwoods/daffodildb/utils/parser/reservedWord.obj");
1062         if (url1 == null)
1063            throw new DException("DSE0", new Object JavaDoc[] {"Reserveword file is missing in classpath."});
1064      } else {
1065         try {
1066            url1 = new URL JavaDoc(url.getProtocol() + ":" + url.getPath() + "/reservedWord.obj");
1067         } catch (MalformedURLException ex) {
1068            throw new DException("DSE0", new Object JavaDoc[] {ex});
1069         }
1070      }
1071      try {
1072         ObjectInputStream ooin = new ObjectInputStream(new BufferedInputStream(url1.openStream()));
1073         reservedWord = new ArrayList JavaDoc( (Vector JavaDoc) ooin.readObject());
1074         ooin.close();
1075      } catch (ClassNotFoundException JavaDoc ex1) {
1076         ex1.printStackTrace();
1077         throw new DException("DSE0", new Object JavaDoc[] {ex1});
1078      } catch (IOException ex1) {
1079         ex1.printStackTrace();
1080         throw new DException("DSE0", new Object JavaDoc[] {ex1});
1081      }
1082      if (url == null) {
1083         url1 = cls.getResource("/com/daffodilwoods/daffodildb/utils/parser/nonReservedWord.obj");
1084         if (url1 == null)
1085            throw new DException("DSE0", new Object JavaDoc[] {"NonReserveword file is missing in classpath."});
1086      } else {
1087         try {
1088            url1 = new URL JavaDoc(url.getProtocol() + ":" + url.getPath() + "/nonReservedWord.obj");
1089         } catch (MalformedURLException ex1) {
1090            ex1.printStackTrace();
1091            throw new DException("DSE0", new Object JavaDoc[] {ex1});
1092         }
1093      }
1094      try {
1095         ObjectInputStream ooin = new ObjectInputStream(new BufferedInputStream(url1.openStream()));
1096         nonReservedWord = new ArrayList JavaDoc( (Vector JavaDoc) ooin.readObject());
1097         ooin.close();
1098      } catch (ClassNotFoundException JavaDoc ex1) {
1099         ex1.printStackTrace();
1100         throw new DException("DSE0", new Object JavaDoc[] {ex1});
1101      } catch (IOException ex1) {
1102         ex1.printStackTrace();
1103         throw new DException("DSE0", new Object JavaDoc[] {ex1});
1104      }
1105   }
1106
1107   /*private void display(Object []array,boolean flag){
1108      for(int i = 0; i < array.length; ++i){
1109        if ( flag )
1110         ;//// Removed By Program ** System.out.println("NONRESERVED WORD ------------- "+array[i]);
1111        else
1112         ;//// Removed By Program ** System.out.println("RESERVED WORD ------------- "+array[i]);
1113      }
1114       }*/

1115
1116   ArrayList JavaDoc awe = new ArrayList JavaDoc();
1117   private void modifyProductionRuleName(ProductionRules pr1) {
1118      if (awe.contains(pr1.nameOfRule)) {
1119         return;
1120      }
1121      awe.add(pr1.nameOfRule);
1122      Object JavaDoc[] asd = pr1.rules;
1123      if (asd == null) {
1124         return;
1125      }
1126      for (int i = 0; i < asd.length; i++) {
1127         if (asd[i] instanceof ProductionRules)
1128            modifyProductionRuleName( (ProductionRules) asd[i]);
1129      }
1130      /* This return is done for the case of timestamp function parsing problem */
1131      if ( pr1.nameOfRule.equalsIgnoreCase("SComma94843605character string literal") )
1132        return;
1133
1134      ProductionRules pr = pr1;
1135      if (pr instanceof UnionProductionRules || pr instanceof UnionProductionRulesWithHashMap) {
1136         Object JavaDoc[] updatedRules = pr.rules;
1137         ArrayList JavaDoc productionRules = new ArrayList JavaDoc(Arrays.asList(updatedRules));
1138         ArrayList JavaDoc productionRules1 = new ArrayList JavaDoc(Arrays.asList(updatedRules));
1139         int size1 = updatedRules.length - 1;
1140         boolean ff = false, ff1 = true;
1141         if (size1 > 0) {
1142            if (updatedRules[size1].toString().equalsIgnoreCase("[Scomma94843605] SPR [,]")) {
1143               Object JavaDoc o = productionRules.remove(size1);
1144               productionRules1.set(size1, null);
1145               ff = true;
1146            }
1147            if (updatedRules[size1].toString().equalsIgnoreCase("[Sleft paren653880241] SPR [(]")
1148                && updatedRules[0].toString().equalsIgnoreCase("[Sright paren-1874859514] SPR [)]")
1149                ) {
1150               Object JavaDoc o = productionRules.remove(size1);
1151               o = productionRules.remove(0);
1152               productionRules1.set(size1, null);
1153               productionRules1.set(0, null);
1154               ff1 = false;
1155            }
1156         }
1157         Object JavaDoc[] temp = pr.rules;
1158         pr.rules = null;
1159         boolean b = updateArrayList(pr.nameOfRule, productionRules);
1160         if (b) {
1161            Object JavaDoc o = productionRules1.set(1, Boolean.FALSE);
1162            pr.setRepUnionType(true);
1163         }
1164         if (ff && !pr.angularType) {
1165            pr.setProductionRuleName(gettingNames(productionRules));
1166            pr.toMakeClass = false;
1167         }
1168         boolean ss = pr.toMakeClass;
1169         pr.toMakeClass = ff1;
1170         pr.setProductionRules(productionRules);
1171         pr.toMakeClass = ss;
1172         pr.rules = temp;
1173         pr.updatedRules = productionRules1.toArray();
1174      }
1175   }
1176
1177   private boolean updateArrayList(String JavaDoc asd, ArrayList JavaDoc pr) {
1178      if (pr.size() == 2) {
1179         ProductionRules pr0 = (ProductionRules) pr.get(0);
1180         ProductionRules pr1 = (ProductionRules) pr.get(1);
1181         if (pr0 instanceof OptionalProductionRules || pr0 instanceof OptionalProductionRulesWithHashMap) {
1182            pr0 = (ProductionRules) pr0.rules[0];
1183            if (pr0 instanceof RepetitiveProductionRules || pr0 instanceof RepetitiveProductionRulesWithHashMap) {
1184               pr0 = (ProductionRules) pr0.rules[0];
1185            }
1186         }
1187         if (pr0.nameOfRule.equalsIgnoreCase(pr1.nameOfRule)) {
1188            ProductionRules o = (ProductionRules) pr.remove(1);
1189            ProductionRules o1 = (ProductionRules) pr.get(0);
1190            o1.nameOfRule = asd;
1191            return true;
1192         }
1193      }
1194      return false;
1195   }
1196
1197   private String JavaDoc gettingNames(ArrayList JavaDoc list) {
1198      StringBuffer JavaDoc bufferForgettingNames = new StringBuffer JavaDoc(100);
1199      int size = list.size() - 1;
1200      for (int i = size; i >= 0; i--) {
1201         ProductionRules rule = (ProductionRules) list.get(i);
1202         if (rule instanceof StringProductionRules) {
1203            bufferForgettingNames.append( ( (StringProductionRules) rule).keyWord);
1204         } else {
1205            bufferForgettingNames.append(rule.nameOfRule);
1206         }
1207      }
1208      return bufferForgettingNames.toString();
1209   }
1210}
1211
Popular Tags