Source code: javatools/applications/DBScriptExec/DBScriptExec.java
1 /*
2 * DBScriptExec.java
3 *
4 * Created on 17 dicembre 2001, 13.37
5 Javatools (modified version) - Some useful general classes.
6 Copyright (C) 2002-2003 Chris Bitmead (original) Antonio Petrelli (modified)
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22 Contact me at: brenmcguire@users.sourceforge.net
23 */
24
25
26 package javatools.applications.DBScriptExec;
27
28 import java.sql.*;
29 import java.util.*;
30 import java.io.*;
31 import javatools.sql.*;
32 import javatools.util.*;
33 import javatools.db.*;
34
35 /** Application to send a script to a DBMS.
36 * @author Antonio Petrelli
37 * @version 0.2.0
38 */
39 public class DBScriptExec {
40
41 /** Main method.
42 * @param args the command line arguments
43 */
44
45 public static void main (String args[]) {
46 int i, numComm, argsLength;
47 String dbms, url, username, password;
48 int port;
49
50 if (args.length > 0) {
51 argset = new ArgumentProcessor();
52 initArgumentProcessor();
53 argset.processArguments(args);
54 if (! showHelpPage()) {
55 if (! showVersion()) {
56 manager = DbManager.singleton();
57 getParams();
58 createDatabase();
59 createExecutor();
60 try {
61 loadScript();
62 execScript();
63 }
64 catch (DbException e) {
65 System.out.println(e.getMessage());
66 }
67 }
68 }
69 }
70 else
71 System.out.println(noParamsText);
72 }
73
74 /** Sets parameters to be used in a non-main session.
75 * @param pDbDir The directory to be used with DBMSs that use database-files (e.g. Firebird).
76 *
77 * @param pDbms The DBMS to use.
78 * @param pDbName The database name.
79 * @param pDriver The driver class.
80 * @param pDbAddress The address of the DBMS.
81 * @param pUserName The user name for connection.
82 * @param pPassword The password to connect.
83 * @param pPort The port for connection. <CODE>-1</CODE> means default.
84 * @param pFileName The script filename to execute.
85 */
86 public static void setParams(String pDbms, String pDbDir, String pDbName,
87 String pDriver, String pDbAddress, String pUserName, String pPassword,
88 int pPort, String pFileName) {
89 dbms = pDbms;
90 dbDir = pDbDir;
91 dbName = pDbName;
92 driver = pDriver;
93 dbAddress = pDbAddress;
94 userName = pUserName;
95 password = pPassword;
96 port = pPort;
97 fileName = pFileName;
98 }
99
100 /** Sets parameters to be used in a non-main session.
101 * @param pDbms The DBMS to use.
102 * @param pDbName The database name.
103 * @param pDriver The driver class.
104 * @param pDbAddress The address of the DBMS.
105 * @param pUserName The user name for connection.
106 * @param pPassword The password to connect.
107 * @param pPort The port for connection. <CODE>-1</CODE> means default.
108 * @param pFileName The script filename to execute. */
109 public static void setParams(String pDbms, String pDbName, String pDriver,
110 String pDbAddress, String pUserName, String pPassword, int pPort, String pFileName) {
111 setParams (pDbms, null, pDbName, pDriver, pDbAddress, pUserName,
112 pPassword, pPort, pFileName);
113 }
114 /** Runs the assigned script in a non-main session.
115 */
116 public static void runScript() throws DbException {
117 String dbPrefix;
118 boolean finished;
119 ResourceUtils utils;
120
121 manager = DbManager.singleton();
122 utils = ResourceUtils.singleton();
123 dbPrefix = dbms+"."+driver+".";
124 try {
125 if (manager.getProps().getProperty(dbPrefix + "pathNeeded").equals("true"))
126 pathNeeded = true;
127 else
128 pathNeeded = false;
129 if (manager.getProps().getProperty(dbPrefix + "canCreateDatabase").equals("true"))
130 canCreateDatabase = true;
131 else
132 canCreateDatabase = false;
133 }
134 catch (IOException e) {
135 throw new DbException (e.getMessage());
136 }
137 createExecutor();
138 try {
139 sexec.loadScript(DBScriptExec.class.getClassLoader().getResourceAsStream("res/" + fileName));
140 }
141 catch (FileNotFoundException e) {
142 System.out.println("Script file not found!");
143 System.exit(1);
144 }
145 catch (IOException e) {
146 System.out.println("Script file not found!");
147 System.exit(1);
148 }
149 finished = false;
150 try {
151 execScript();
152 finished = true;
153 }
154 catch (DbException e) {
155 if (!canCreateDatabase)
156 throw e;
157 }
158 try {
159 if (!finished && canCreateDatabase) {
160 System.out.println("Script execution failed, trying to create a database instance");
161 createDatabase();
162 execScript();
163 finished = true;
164 }
165 }
166 catch (DbException e) {
167 if (!canCreateDatabase)
168 throw e;
169 }
170 if (!finished && canCreateDatabase) {
171 System.out.println("Database creation failed, trying to create user first");
172 createUserAndDatabase();
173 execScript();
174 }
175 }
176
177 private static void initArgumentProcessor() {
178 int i, numFlags, numArgs;
179
180 numFlags = flags.length;
181 numArgs = parameters.length;
182
183 argset.setNumFlags(numFlags);
184 argset.setNumArguments(numArgs);
185 try {
186 for (i=0; i<numFlags; i++) {
187 argset.setFlagName(i, flags[i]);
188 argset.setFlagHelpText(i, flagHelpText[i]);
189 }
190 }
191 catch (IndexOutOfBoundsException e) {
192 System.out.println("Errors in flags definition");
193 System.exit(1);
194 }
195 try {
196 for (i=0; i<numArgs; i++) {
197 argset.setArgumentName(i, parameters[i]);
198 argset.setArgumentHelpText(i, argHelpText[i]);
199 }
200 }
201 catch (IndexOutOfBoundsException e) {
202 System.out.println("Errors in arguments definition");
203 System.exit(1);
204 }
205 }
206
207 private static boolean showHelpPage() {
208 int i, numFlags, numArgs;
209
210 try {
211 if (argset.getFlagValue("--help")) {
212 System.out.println(helpText);
213 numFlags = argset.getNumFlags();
214 for (i=0; i<numFlags; i++)
215 System.out.println("\t"+flags[i]+": "+
216 argset.getFlagHelpText(i));
217 numArgs = argset.getNumArguments();
218 for (i=0; i<numArgs; i++)
219 System.out.println("\t"+parameters[i]+" "+paramName[i]+": "+
220 argset.getArgumentHelpText(i, paramName[i]));
221
222 return true;
223 }
224 }
225 catch (IndexOutOfBoundsException e) {
226 System.out.println("Errors in getting help texts");
227 System.exit(1);
228 }
229 return false;
230 }
231
232 private static boolean showVersion() {
233 if (argset.getFlagValue("--version")) {
234 System.out.println(DBSCRIPTEXEC_VERSION);
235 return true;
236 }
237 return false;
238 }
239
240 private static void getParams() {
241 int tempPort;
242 String dbPrefix;
243
244 dbms = argset.getArgumentValue("--dbms");
245 dbName = argset.getArgumentValue("--dbname");
246 driver = argset.getArgumentValue("--driver");
247 dbAddress = argset.getArgumentValue("--dbaddress");
248 userName = argset.getArgumentValue("--username");
249 password = argset.getArgumentValue("--password");
250 fileName = argset.getArgumentValue("--file");
251 port = -1;
252 try {
253 port = Integer.decode(argset.getArgumentValue("--port")).intValue();
254 }
255 catch (NumberFormatException e) {
256 }
257 if (dbms.equals(""))
258 dbms = DBMS_DEFAULT;
259 if (dbName.equals(""))
260 dbName = DBNAME_DEFAULT;
261 if (driver.equals(""))
262 driver = DRIVER_DEFAULT;
263 if (dbAddress.equals(""))
264 dbAddress = DBADDRESS_DEFAULT;
265 dbPrefix = dbms+"."+driver+".";
266 try {
267 if (manager.getProps().getProperty(dbPrefix + "pathNeeded").equals("true"))
268 pathNeeded = true;
269 else
270 pathNeeded = false;
271 if (manager.getProps().getProperty(dbPrefix + "canCreateDatabase").equals("true"))
272 canCreateDatabase = true;
273 else
274 canCreateDatabase = false;
275 }
276 catch (IOException e) {
277 System.out.println(e.getMessage());
278 System.exit(1);
279 }
280 }
281
282 private static void createExecutor () {
283 String connectString;
284 String dbPrefix;
285
286 connectString = "";
287 dbPrefix = dbms+"."+driver+".";
288 try {
289 if (!pathNeeded)
290 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, dbName, "", "");
291 else
292 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, dbDir, dbName, "", "");
293 }
294 catch (DbException e) {
295 System.out.println(e.getMessage());
296 System.exit(1);
297 }
298 sexec = new ScriptExecutor();
299 sexec.setDatabase(manager, dbms, driver, connectString, userName, password);
300 }
301
302 private static void createDatabase() {
303 DbDatabaseAdmin db;
304 String connectString;
305 String completeDbName;
306
307 connectString = "";
308 try {
309 if (!pathNeeded)
310 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, "", "", "");
311 else
312 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, dbDir, "", "", "");
313 }
314 catch (DbException e) {
315 System.out.println(e.getMessage());
316 System.exit(1);
317 }
318 db = new DbDatabaseAdmin(manager, dbms, driver, connectString, userName, password);
319 try {
320 completeDbName = null;
321 if (dbName.equals(""))
322 completeDbName = DBNAME_DEFAULT;
323 else
324 completeDbName = dbName;
325 if (pathNeeded) {
326 if (!dbDir.endsWith(File.separator))
327 dbName = File.separator + dbName;
328 completeDbName = dbDir + dbName;
329 }
330 db.createDatabase(dbAddress, port, completeDbName);
331 }
332 catch (DbException e) {
333 System.out.println(e.getMessage());
334 }
335 }
336
337 private static void createUserAndDatabase() {
338 DbDatabaseAdmin db;
339 String connectString;
340 String completeDbName;
341
342 connectString = "";
343 try {
344 if (!pathNeeded)
345 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, "", "", "");
346 else
347 connectString = ConnectionString.build(manager, dbms, driver, dbAddress, port, dbDir, "", "", "");
348 }
349 catch (DbException e) {
350 System.out.println(e.getMessage());
351 System.exit(1);
352 }
353 db = new DbDatabaseAdmin(manager, dbms, driver, connectString, userName, password);
354 try {
355 completeDbName = null;
356 if (dbName.equals(""))
357 completeDbName = DBNAME_DEFAULT;
358 else
359 completeDbName = dbName;
360 if (pathNeeded) {
361 if (!dbDir.endsWith(File.separator))
362 dbName = File.separator + dbName;
363 completeDbName = dbDir + dbName;
364 }
365 db.createUser(userName, password);
366 db.createDatabase(dbAddress, port, completeDbName);
367 }
368 catch (DbException e) {
369 System.out.println(e.getMessage());
370 }
371 }
372
373 private static void loadScript() throws DbException {
374 String filename;
375
376 filename = argset.getArgumentValue("--file");
377 try {
378 if (filename.equals(""))
379 sexec.loadScript(SCRIPT_DEFAULT);
380 else
381 sexec.loadScript(filename);
382 }
383 catch (FileNotFoundException e) {
384 throw new DbException (e.getMessage());
385 }
386 }
387
388 private static void execScript() throws DbException {
389 sexec.execScript();
390 }
391
392 private static String DBMS_DEFAULT = "mysql";
393 private static String DBNAME_DEFAULT = "Default";
394 private static String DRIVER_DEFAULT = "org.gjt.mm.mysql.Driver";
395 private static String DBADDRESS_DEFAULT = "localhost";
396 private static int PORT_DEFAULT = -1;
397 private static String USERNAME_DEFAULT = "";
398 private static String PASSWORD_DEFAULT = "";
399 private static String SCRIPT_DEFAULT = "script.sql";
400 private static String DBSCRIPTEXEC_VERSION = "0.0.1";
401 private static String BATCH_FILENAME = "dbsexec";
402
403 private static String [] parameters =
404 {"--dbms", "--dbname", "--driver", "--dbaddress", "--port", "--username", "--password", "--file"};
405 private static String [] flags =
406 {"--version", "--help"};
407 private static String [] argHelpText =
408 {"Specify the name of the used DBMS\n"+
409 "\t\tdefault: "+DBMS_DEFAULT+"\n"+
410 "\t\t%P% = mysql: MySQL",
411 "Specify the name of the Database that is being created\n"+
412 "\t\twhere %P% is the name of the Database\n"+
413 "\t\tdefault: "+DBNAME_DEFAULT,
414 "Specify the driver to be used for the specified database\n"+
415 "\t\twhere %P% is the name of the driver\n"+
416 "\t\tdefault: "+DRIVER_DEFAULT+"\n"+
417 "\t\t%P% = org.gjt.mm.mysql.Driver: to use MM.MySQL",
418 "Specify the URL address of the DBMS server\n"+
419 "\t\twhere %P% is the name of the server\n"+
420 "\t\tdefault: "+DBADDRESS_DEFAULT,
421 "Specify the port through which the data will be sent\n"+
422 "\t\twhere %P% is the port number\n"+
423 "\t\tdefault: -1 [no port]",
424 "Specify the username which will be used for connection\n"+
425 "\t\twhere %P% is the username\n"+
426 "\t\tdefault is none",
427 "Specify the password which will be used for connection\n"+
428 "\t\twhere %P% is the password\n"+
429 "\t\tdefault is none",
430 "Specify the filename of the script file to be used\n"+
431 "\t\twhere %P% is the complete path to the file\n"+
432 "\t\tdefault: "+SCRIPT_DEFAULT};
433 private static String [] flagHelpText =
434 {"Show the version of the program",
435 "Show this help page"};
436 private static String [] paramName =
437 {"DBMS", "DataBaseName", "Driver", "URL", "Port_Number", "Username", "Password", "path_to_file"};
438 private static String noParamsText =
439 "DBScriptExec version "+DBSCRIPTEXEC_VERSION+"\n"+
440 "A program to initialize a database\n"+
441 "Now the program supports only MySQL! Please help us in supporting different DBMSs\n"+
442 "Type \"dbsexec --help\" to show usage of the program.";
443 private static String helpText =
444 "DBScriptExec version "+DBSCRIPTEXEC_VERSION+"\n"+
445 "Syntax: \n"+
446 "\t "+BATCH_FILENAME+" [params]\n"+
447 "List of parameters:";
448
449 private static ArgumentProcessor argset;
450 private static ScriptExecutor sexec;
451 private static DbManager manager;
452 private static String connString;
453
454 private static String dbms;
455 private static String driver;
456 private static String dbDir;
457 private static String dbName;
458 private static String dbAddress;
459 private static int port;
460 private static String userName;
461 private static String password;
462 private static String fileName;
463 private static boolean pathNeeded;
464 private static boolean canCreateDatabase;
465 }