KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > tools > shell > ScriptExecuter


1 package com.daffodilwoods.tools.shell;
2
3 import java.io.*;
4
5 import com.daffodilwoods.daffodildb.server.serversystem.*;
6
7 /****************************************************************************
8  * ScriptExecuter class reads statements from script file and pass statement
9  * one by one to _Connection.execute method.
10  * It displays the result of executed statement on the shell
11  */

12
13 public class ScriptExecuter {
14   private _Connection connection;
15   static int initialBlockSize = 1500;
16   private QueryExecuter queryExecuter;
17
18   public ScriptExecuter(QueryExecuter queryExecuter0) {
19     queryExecuter = queryExecuter0;
20   }
21   /**
22    * Required for GenericScriptExecuter
23    * @param queryExecuter0 QueryExecuter
24    */

25   public ScriptExecuter() {
26   }
27
28   public void setConnection(_Connection con) {
29     connection = con;
30   }
31
32   /*******************************************************************************
33    * This method executes commands listed in a script file one by one.
34    *
35    * @param scriptFile have script file name specified by user
36    * @param connection _Connection type object to execute statement
37    * @throws java.lang.Exception
38    */

39   public void runScript(String JavaDoc filename) throws Exception JavaDoc {
40     if (isConnectionClosed()) {
41       throw new Exception JavaDoc("\nNot connected with any database\n");
42     }
43     RandomAccessFile scriptFile = null;
44     try {
45       scriptFile = new RandomAccessFile(filename, "r");
46       runScript(scriptFile);
47     }
48     catch (FileNotFoundException ex) {
49       DisplayOutput.displayLn("File [" + filename + "] does not exists");
50     }
51     finally {
52       if (scriptFile != null) {
53         scriptFile.close();
54       }
55     }
56   }
57
58   /*******************************************************************************
59    * This method executes create commands listed in a script file.
60    * If a command is not executed, then this method store this
61    * command in a notParsedFile. When the commands of script file finished
62    * it executes commands of notParsedFile
63    *
64    * @param scriptFile have script file name specified by user
65    * @param notParsedFile String type variable to store not parsed file name
66    * @param connection _Connection type object to execute statement
67    * @throws java.lang.Exception
68    */

69   public void runScript(RandomAccessFile file) throws Exception JavaDoc {
70     String JavaDoc line = "";
71     StringBuffer JavaDoc finalStr = new StringBuffer JavaDoc();
72     int count = 1;
73     while ( (line = file.readLine()) != null) {
74       if (line.startsWith("#") || line.startsWith("--")) {
75         continue;
76       }
77       int lineCommentIndex = line.indexOf("--");
78       line = (lineCommentIndex > -1 ) ? line.substring(0,lineCommentIndex -1) : line;
79       if (line.trim().equals("/"))
80           finalStr.append("\n").append(line.trim()).append("\n");
81       else
82           finalStr.append(" ").append(line.trim());
83       if (count >= initialBlockSize)
84       {
85         line = runScript(finalStr.toString(), true); // line would assigne the stub
86
finalStr.setLength(0);
87         finalStr.append(line);
88         count = 0;
89       }
90       count++;
91     }
92     if (count < initialBlockSize) {
93       runScript(finalStr.toString(), false);
94     }
95   }
96
97   /**
98    * partial is true if number of lines in the file is greater than the buffer size.
99    *
100    * @param partialScript String
101    * @param partial boolean
102    * @throws Exception
103    * @return String
104    */

105   private String JavaDoc runScript(String JavaDoc partialScript, boolean partial) throws
106       Exception JavaDoc {
107     partialScript = removeComments(partialScript);
108     int halfCommentedIndex = partialScript.indexOf("/*");
109     String JavaDoc executableBlock = halfCommentedIndex == -1 ? partialScript :
110         partialScript.substring(0, halfCommentedIndex);
111     String JavaDoc stub = halfCommentedIndex == -1 ? "" :
112         partialScript.substring(halfCommentedIndex, partialScript.length());
113
114     if (partial) {
115       int lastSemicolonIndx = executableBlock.lastIndexOf(";");
116       stub = executableBlock.substring(lastSemicolonIndx) + stub;
117       executableBlock = executableBlock.substring(0, lastSemicolonIndx);
118     }
119     return processAtomicQuery(executableBlock) + stub;
120   }
121
122   /**
123    * Remove multi-line comments
124    *
125    * @param str String
126    * @return String
127    */

128   private String JavaDoc removeComments(String JavaDoc str) {
129     int startS = 0;
130     StringBuffer JavaDoc finalString = new StringBuffer JavaDoc();
131     while (true) {
132       int s = str.indexOf("/*", startS);
133       if (s == -1) {
134         break;
135       }
136       finalString.append(str.substring(startS, s));
137       int e = str.indexOf("*/", startS + 2);
138       str = str.substring(e + 2);
139     }
140     finalString.append(str);
141     return finalString.toString();
142   }
143
144   /**
145    * return false if single quote (') or double quote (") is mismatching.
146    *
147    * @param str String
148    * @return boolean
149    */

150   private boolean isQuotesMatching(String JavaDoc str) {
151     int len = str.length();
152     int s = 0, d = 0;
153     for (int i = 0; i < len; i++) {
154       char c = str.charAt(i);
155       if (c == '\'') {
156         s++;
157       }
158       if (c == '\"') {
159         d++;
160       }
161     }
162     return s % 2 == 0 && d % 2 == 0;
163   }
164
165   /**
166    *
167    * @param str String
168    * @throws Exception
169    * @return String
170    */

171   int n=0;
172   private String JavaDoc processAtomicQuery(String JavaDoc str) throws Exception JavaDoc {
173     String JavaDoc delim = ";", query = "";
174     boolean completeQuery = true;
175     while (true) {
176         int start = 0;
177         if (completeQuery) {
178             if(isPSMQuery(str.trim())) {
179                 delim = "\n/\n";
180             }
181             else {
182                 delim = ";";
183             }
184       }
185       int end = str.indexOf(delim);
186       if (end == -1) {
187         break;
188       }
189       if (completeQuery) {
190         query = str.substring(start, end);
191       }
192       else {
193         query = query + delim + str.substring(0, end);
194       }
195       completeQuery = isQuotesMatching(query);
196       if (completeQuery) {
197           executeQuery(query);
198       }
199     try
200     {
201         str = str.substring(end + delim.length());
202     }
203     catch (Exception JavaDoc ex)
204     {
205         DisplayOutput.printError("Error ....",ex);
206     }
207     }
208     return str;
209   }
210
211   private boolean isPSMQuery(String JavaDoc str) { //optimization toupper case should run on first word of str
212
if (!str.toUpperCase().startsWith("CREATE")) {
213       return false;
214     }
215     int secondWordStart = str.indexOf(" ");
216     str = str.substring(secondWordStart, str.length()).trim();
217     String JavaDoc dbObject = str.substring(0,str.indexOf(" ")).trim();
218     return (dbObject.toUpperCase().equals("PROCEDURE") ||
219             dbObject.toUpperCase().equals("TRIGGER") ||
220             dbObject.toUpperCase().equals("FUNCTION") ||
221             dbObject.toUpperCase().equals("OR"));
222   }
223
224   /**
225    * Transfer the call to QueryExecuter
226    * @param query String
227    */

228   protected void executeQuery(String JavaDoc query) {
229     try {
230       if (!"".equals(query.trim())) {
231         DisplayOutput.displayLn("\n" + query);
232         queryExecuter.execute(query, connection);
233       }
234     }
235     catch (Exception JavaDoc ex) {
236       DisplayOutput.printError("", ex);
237     }
238   }
239
240   protected boolean isConnectionClosed() throws Exception JavaDoc {
241     return connection==null || connection.isClosed();
242   }
243 }
244
Popular Tags