KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.daffodilwoods.tools.shell;
2
3 import java.io.*;
4 import java.rmi.*;
5 import java.util.*;
6
7 import com.daffodilwoods.daffodildb.server.serversystem.*;
8 import com.daffodilwoods.daffodildb.utils.parser.*;
9 import com.daffodilwoods.database.resource.*;
10
11 public class DaffodilDBShell {
12   ShellHelp sHelp;
13   QueryExecuter qExec;
14   ScriptExecuter script;
15   private _Server server;
16   private _Connection connection;
17   static public boolean isRMI = false;
18   private Properties props;
19   private BufferedReader rd;
20   static private boolean notConnected;
21   static public boolean trace;
22
23
24    public DaffodilDBShell() {
25    }
26   private void connect() throws Exception JavaDoc {
27     ConnectInformation conInfo = new ConnectInformation(rd);
28     props = conInfo.getConnectionProperties();
29     if (isRMI) {
30       server = getRemoteServer(conInfo.hostName, conInfo.port);
31     }
32     else {
33       if (server != null) {
34         ( (ServerSystem) server).closeServerSystem();
35       }
36       server = getEmbeddedServer(conInfo.databasePath, conInfo.readOnly);
37     }
38
39     _User user = server.getUser(conInfo.hostName, conInfo.password);
40     ArrayList databaseList = user.getAllDatabases();
41     if (!databaseList.contains(conInfo.databaseName.toLowerCase())) {
42       System.out.println("\nCreating Database \nPlease Wait ...\n");
43     }
44     connection = server.getConnection(conInfo.databaseName, props);
45     connection.setTransactionIsolation(2);
46     script.setConnection(connection);
47     System.out.println("\nConnected \n");
48   }
49
50   private _Server getRemoteServer(String JavaDoc host, int port) throws Exception JavaDoc {
51     String JavaDoc lookUpString = "rmi://" + host + ":" + port + "/DaffodilDB";
52     _Server server = null;
53     Object JavaDoc obj = Naming.lookup(lookUpString);
54     server = (_Server) Class.forName("com.daffodilwoods.rmi.RmiServer").
55         getConstructors()[0].newInstance(new Object JavaDoc[] {obj});
56     return server;
57   }
58
59   private _Server getEmbeddedServer(String JavaDoc path, boolean readMode) throws
60       Exception JavaDoc {
61     System.setProperty(_Server.DAFFODILDB_HOME, path);
62     _Server server = null;
63     server = (_Server) Class.forName(
64         "com.daffodilwoods.daffodildb.server.serversystem.ServerSystem").
65         getConstructor(new Class JavaDoc[] {boolean.class}).
66         newInstance(new Object JavaDoc[] {new Boolean JavaDoc(readMode)});
67     return server;
68   }
69
70
71
72     private String JavaDoc readquery() throws IOException {
73       String JavaDoc query = "";
74       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
75       System.out.print("SQL>");
76       query = rd.readLine();
77       query = query != null ? query.trim() : "exit";
78       if ( (query.compareToIgnoreCase("exit") == 0) ||
79           (query.compareToIgnoreCase("help") == 0) ||
80           (query.compareToIgnoreCase("version") == 0) ||
81           (query.compareToIgnoreCase("quit") == 0) ||
82           (query.toLowerCase().trim().startsWith("run")) ||
83           (query.equalsIgnoreCase("connect")) || query.trim().length() == 0) {
84         return query;
85       }
86       while (!query.endsWith(";")) {
87         buffer.append(" " + query);
88         System.out.print(">");
89         query = rd.readLine();
90         if (query == null) {
91           notConnected = true;
92           System.exit(00);
93         }
94       }
95       buffer.append(" " + query);
96       query = buffer.toString();
97       return query.substring(0, query.lastIndexOf(";")).trim();
98     }
99
100   public void init() throws Exception JavaDoc {
101     sHelp = new ShellHelp();
102     rd = new BufferedReader(new InputStreamReader(System.in));
103     qExec = new QueryExecuter(rd);
104     script = new ScriptExecuter(qExec);
105     try {
106       connect(); //initialise server and connection
107
sHelp.showShellInformation();
108     }
109     catch (Exception JavaDoc ex) {
110       System.out.println("");
111       DisplayOutput.printError("", ex);
112       System.out.println("Unable to connect with any database...\n");
113     }
114     processCommands();
115   }
116
117    public void processCommands() {
118      String JavaDoc query;
119      boolean FINISHED = false;
120      while (true) {
121        try {
122          query = readquery();
123
124          if (query.equalsIgnoreCase("exit") || query.equalsIgnoreCase("quit")) {
125            break;
126          }
127          else if (query.equalsIgnoreCase("help")) {
128            sHelp.ShowHelp();
129          }
130          else if (query.equalsIgnoreCase("connect")) {
131            if (connection != null) {
132              connection.close();
133              connection=null;
134              notConnected = true;
135            }
136            connect();
137          }
138          else if (query.equalsIgnoreCase("version")) {
139            sHelp.displayVersion();
140          }
141          else if (query.toLowerCase().startsWith("run")) {
142            checkConnection();
143            runScript(query);
144          }
145          else if (query.toLowerCase().trim().startsWith("execute")) {
146            checkConnection();
147            executeScript(query);
148          }
149          else {
150            runSQL(query);
151          }
152        }
153        catch (DException ex) {
154          DisplayOutput.printError("", ex);
155        }
156        catch (IOException ex) {
157          DisplayOutput.printError("", ex);
158        }
159        catch (Exception JavaDoc ex) {
160          DisplayOutput.printError("", ex);
161        }
162      }
163    }
164
165   /**
166    * runScript
167    *
168    * @param query String
169    */

170   private void runScript(String JavaDoc query) {
171     System.out.println("Query = " + query);
172     try {
173       script.runScript(query.trim().substring(3, query.length()).trim());
174     }
175     catch (Exception JavaDoc ex) {
176       DisplayOutput.printError("", ex);
177     }
178   }
179
180   /**
181    * executeScript
182    *
183    * @param query String
184    */

185   private void executeScript(String JavaDoc query) {
186   }
187
188   /**
189    * runSQL
190    */

191   private void runSQL(String JavaDoc query) {
192     try {
193       checkConnection();
194       qExec.execute(query, connection);
195     }
196     catch (Exception JavaDoc e) {
197       if (e instanceof ParseException) {
198         DisplayOutput.locateSyntaxError(query, (ParseException) e);
199         DisplayOutput.printError("", e);
200       }
201       else {
202         DisplayOutput.printError("", e);
203       }
204     }
205   }
206
207
208    public static void main(String JavaDoc args[]) {
209
210      start(args.length != 0 && args[0].equalsIgnoreCase("true"));
211    }
212
213   /**
214    * start
215    */

216   private static void start(boolean isRMI) {
217     final DaffodilDBShell cmd = new DaffodilDBShell();
218     trace = false;
219     try {
220       DaffodilDBShell.isRMI = isRMI;
221     }
222     catch (ArrayIndexOutOfBoundsException JavaDoc ex) {
223       DaffodilDBShell.isRMI = false;
224     }
225     Runtime JavaDoc rt = Runtime.getRuntime();
226     Class JavaDoc cc = rt.getClass();
227     java.lang.reflect.Method JavaDoc mt = null;
228     try {
229       mt = cc.getDeclaredMethod("addShutdownHook", new Class JavaDoc[] {Thread JavaDoc.class});
230     }
231     catch (SecurityException JavaDoc ex1) {
232       System.err.println(ex1);
233     }
234     catch (NoSuchMethodException JavaDoc ex1) {
235       System.err.println(ex1);
236     }
237     if (mt != null) {
238       Thread JavaDoc tt = new Thread JavaDoc() {
239         public void run() {
240           try {
241             System.out.println("\nClosing CommandLine Tool");
242             if (cmd.connection != null) { // && !ConnectInformation.isError) {
243
cmd.connection.close();
244             }
245           }
246           catch (Exception JavaDoc e) {
247             DisplayOutput.printError("", e);
248           }
249         }
250       };
251
252       try {
253         mt.invoke(rt, new Object JavaDoc[] {tt});
254         cmd.init();
255       }
256       catch (Exception JavaDoc ex2) {
257         DisplayOutput.printError("", ex2);
258       }
259     }
260
261   }
262
263    private void checkConnection() throws Exception JavaDoc {
264      if (connection == null) {
265        throw new Exception JavaDoc("\nNot connected with any database\n");
266      }
267    }
268 }
269
Popular Tags