001: /*
002: LoaderGenerator - tool for generated xml, sql and doml file needed for Octopus.
003: Copyright (C) 2003 Together
004: This library is free software; you can redistribute it and/or
005: modify it under the terms of the GNU Lesser General Public
006: License as published by the Free Software Foundation; either
007: version 2.1 of the License, or (at your option) any later version.
008: This library is distributed in the hope that it will be useful,
009: but WITHOUT ANY WARRANTY; without even the implied warranty of
010: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
011: Lesser General Public License for more details.
012: You should have received a copy of the GNU Lesser General Public
013: License along with this library; if not, write to the Free Software
014: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
015: */
016: package org.webdocwf.util.loader.generator;
017:
018: import javax.xml.parsers.DocumentBuilder;
019: import javax.xml.parsers.DocumentBuilderFactory;
020: import javax.xml.parsers.FactoryConfigurationError;
021: import javax.xml.parsers.ParserConfigurationException;
022:
023: import org.w3c.dom.Document;
024:
025: import org.w3c.dom.Element;
026:
027: import java.io.*;
028: import java.sql.*;
029:
030: import java.util.StringTokenizer;
031: import org.webdocwf.util.loader.*;
032:
033: import java.net.*;
034:
035: import org.webdocwf.util.loader.logging.Logger;
036: import org.webdocwf.util.loader.logging.StandardLogger;
037: import org.webdocwf.util.loader.wizard.AddClassPath;
038:
039: /**
040: * CreateIncludeFiles class creates Xml(ImportDefinition.xml) and Sql( CreateTables.sql,
041: * CreateIntegrity.sql, CreateOisAdminData.sql, CreatePrimary.sql and CreateIndex.sql) files,
042: * if the input data is database.
043: * @author Radoslav Dutina
044: * @version 1.0
045: */
046: public class CreateIncludeFiles {
047:
048: private Document document;
049: private Document documentDoml;
050: private Element rootDoml = null;
051: private Element childRoot1 = null;
052: private Element childRoot2 = null;
053: private Logger logger;
054: private InputParameters generatorParameters;
055:
056: /**
057: * Construct object CreateIncludeFiles with associated parameter.
058: * @param generatorParameters represents the references to InputParameter object.
059: * @throws LoaderException
060: */
061: public CreateIncludeFiles(InputParameters generatorParameters)
062: throws LoaderException {
063:
064: try {
065: setLogger();
066: this .logger
067: .write("normal",
068: "CreateIncludeFiles is started. Generating sql and xml files is started.");
069: createIncludeFiles(generatorParameters);
070: this .logger
071: .write("normal",
072: "CreateIncludeFiles is finished. Generating sql and xml files is finished.");
073: } catch (Exception e) {
074: throw new LoaderException(
075: "Exception:Error while create include files.", e);
076: } catch (FactoryConfigurationError e) {
077: throw new LoaderException(
078: "FactoryConfigurationError:Error while create include files.",
079: e);
080: }
081: }
082:
083: /**
084: * This method will generate all xml and sql files
085: * @param generatorParameters
086: * @throws LoaderException
087: * @throws FactoryConfigurationError
088: */
089: private void createIncludeFiles(InputParameters generatorParameters)
090: throws LoaderException, FactoryConfigurationError {
091:
092: this .logger.write("normal",
093: "\tcreateIncludeFiles method is started.");
094: if (generatorParameters.getSourceDriverName().equalsIgnoreCase(
095: "freetds")) {
096: // if (this.logger != null) {
097:
098: // }
099: //BufferOctopusClass.getInstance().writeToBuffer("Eroor : Freetds driver can't be used as source driver.");
100: LoaderException le = new LoaderException(
101: "Exception:",
102: (Throwable) new Exception(
103: "Freetds driver can't be used as source driver."));
104: this .logger.write("full",
105: "Eroor : Freetds driver can't be used as source driver."
106: + le.getStackTraceAsString());
107: throw le;
108: }
109:
110: //Create an importDefinition.xml file, for csv tables
111: if (generatorParameters.getSourceType().equalsIgnoreCase("csv")
112: || generatorParameters.getSourceType()
113: .equalsIgnoreCase("access")
114: || generatorParameters.getSourceType()
115: .equalsIgnoreCase("xml")) {
116:
117: DocumentBuilderFactory factory = DocumentBuilderFactory
118: .newInstance();
119: DocumentBuilderFactory factoryDoml = DocumentBuilderFactory
120: .newInstance();
121: try {
122: DocumentBuilder builder = factory.newDocumentBuilder();
123: document = builder.newDocument(); // Create from whole cloth
124: //for creating the doml file
125: DocumentBuilder builderDoml = factoryDoml
126: .newDocumentBuilder();
127: documentDoml = builderDoml.newDocument(); // Create from whole cloth
128:
129: Element rootDoml = (Element) documentDoml
130: .createElement("doml");
131: documentDoml.appendChild(rootDoml);
132:
133: Element childRoot1 = (Element) documentDoml
134: .createElement("database");
135: rootDoml.appendChild(childRoot1);
136: childRoot1.setAttribute("database", generatorParameters
137: .getTargetType());
138:
139: Element root = (Element) document
140: .createElement("definitionInclude");
141: document.appendChild(root);
142: if (generatorParameters.getSourceType()
143: .equalsIgnoreCase("csv")
144: || generatorParameters.getSourceType()
145: .equalsIgnoreCase("xml")) {
146: String pathToSource = generatorParameters
147: .getSourceDataBase();
148: int endNameDB = pathToSource.indexOf(";");
149: if (endNameDB != -1)
150: pathToSource = pathToSource.substring(0,
151: endNameDB);
152:
153: File file = new File(pathToSource);
154: String[] listFiles = file.list();
155: if (listFiles == null && listFiles.length == 0) {
156: String msg = "Path to source database is wrong, or database is empty!";
157: //if (this.logger != null) {
158:
159: //}
160: LoaderException le = new LoaderException(
161: "Exception:", new Exception(msg));
162: this .logger.write("full",
163: "Path to source database is wrong, or database is empty!"
164: + le.getStackTraceAsString());
165: throw le;
166: }
167: int x = 0;
168: for (int i = 0; i < listFiles.length; i++) {
169: String tableName = listFiles[i].substring(0,
170: listFiles[i].lastIndexOf("."));
171: if (!tableName.endsWith("csvext")) {
172: //includeTable
173: boolean doJob = false;
174: if (generatorParameters
175: .getIncludeTableList().size() == 0) {
176: doJob = true;
177: } else {
178: for (int j = 0; j < generatorParameters
179: .getIncludeTableList().size(); j++) {
180: if (tableName
181: .equalsIgnoreCase(generatorParameters
182: .getIncludeTableList()
183: .get(j).toString())) {
184: doJob = true;
185: break;
186: }
187: }
188: }
189: if (doJob) {
190: //System.out.println("Working...." + tableName);
191: //BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
192: //if (this.logger != null) {
193: this .logger.write("normal",
194: "Working...." + tableName);
195: //}
196: CsvTableDesignReader csvTableDesignReader = new CsvTableDesignReader(
197: tableName, generatorParameters);
198: WriteImportDefinition writeImportDefinition = new WriteImportDefinition(
199: document, root,
200: csvTableDesignReader
201: .getImportDefinition(),
202: generatorParameters);
203: WriteSqlFiles writeSql = new WriteSqlFiles(
204: tableName, x,
205: csvTableDesignReader
206: .getImportDefinition(),
207: null, generatorParameters);
208: x++;
209: }
210:
211: }
212: }
213: if (x < 1) {
214: String msg = "There is no tables in specified source database. Check input parameters.";
215: //if (this.logger != null) {
216:
217: //}
218: LoaderException le = new LoaderException(
219: "Exception:", new Exception(msg));
220: this .logger.write("full",
221: "There is no tables in specified source database. Check input parameters."
222: + le.getStackTraceAsString());
223: throw le;
224: }
225: } else { //access,excel database
226: JdbcParameters sourceJdbc = new JdbcParameters(
227: "source", generatorParameters);
228: try {
229: Connection conn = null;
230: URL url = null;
231: String app = "";
232: String path = AddClassPath.getClassPathString();
233: if (path != null) {
234: StringTokenizer st = new StringTokenizer(
235: path, ";");
236: int count = 0;
237: while (st.hasMoreTokens()) {
238: GeneratorClassLoader.addURL(new File(st
239: .nextElement().toString())
240: .toURL());
241: }
242: Class.forName(sourceJdbc
243: .getJdbcParameters("JdbcDriver"));
244: } else {
245: Class.forName(sourceJdbc
246: .getJdbcParameters("JdbcDriver"));
247: }
248: conn = DriverManager.getConnection(sourceJdbc
249: .getJdbcParameters("Connection.Url"),
250: sourceJdbc.getJdbcParameters("User"),
251: sourceJdbc
252: .getJdbcParameters("Password"));
253:
254: Statement stmt = conn.createStatement();
255: String[] accessType = { "TABLE" };
256: String accessDbName = generatorParameters
257: .getSourceDataBase();
258: ResultSet rs = conn.getMetaData().getTables(
259: accessDbName, null, "%", accessType);
260:
261: int i = 0;
262: while (rs.next()) {
263: String tableName = rs.getString(3);
264: //includeTable
265: boolean doJob = false;
266: if (generatorParameters
267: .getIncludeTableList().size() == 0) {
268: doJob = true;
269: } else {
270: for (int j = 0; j < generatorParameters
271: .getIncludeTableList().size(); j++) {
272: if (tableName
273: .equalsIgnoreCase(generatorParameters
274: .getIncludeTableList()
275: .get(j).toString())) {
276: doJob = true;
277: break;
278: }
279: }
280: }
281: if (doJob) {
282: //System.out.println("Working...." + tableName);
283: //BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
284: //if (this.logger != null) {
285: this .logger.write("normal",
286: "Working...." + tableName);
287: //}
288: CsvTableDesignReader csvTableDesignReader = new CsvTableDesignReader(
289: tableName, generatorParameters);
290:
291: WriteImportDefinition writeImportDefinition = new WriteImportDefinition(
292: document, root,
293: csvTableDesignReader
294: .getImportDefinition(),
295: generatorParameters);
296: WriteSqlFiles writeSql = new WriteSqlFiles(
297: tableName, i,
298: csvTableDesignReader
299: .getImportDefinition(),
300: null, generatorParameters);
301: i++;
302: }
303: }
304: if (i < 1) {
305: String msg = "There is no tables in specified source database. Check input parameters.";
306: //if (this.logger != null) {
307:
308: //}
309: LoaderException le = new LoaderException(
310: "Exception:", new Exception(msg));
311: this .logger
312: .write(
313: "full",
314: "Exception:There is no tables in specified source database. Check input parameters."
315: + le
316: .getStackTraceAsString());
317: throw le;
318: }
319: rs.close();
320: } catch (ClassNotFoundException ce) {
321: String msg = "Can't find driver class : ";
322: //if (this.logger != null) {
323:
324: //}
325: LoaderException le = new LoaderException(msg
326: + "\n" + ce.getMessage(),
327: (Throwable) ce);
328: this .logger.write("full",
329: "Exception:Can't find driver class!"
330: + "\n"
331: + le.getStackTraceAsString());
332: throw le;
333: } catch (Exception e) {
334: String msg = "Error while trying connect to database ( maybe password or username is wrong ? ) :";
335: //if (this.logger != null) {
336:
337: //}
338: LoaderException le = new LoaderException(msg
339: + "\n" + e.getMessage(), (Throwable) e);
340: this .logger.write("full", "Exception:" + msg
341: + "\n" + le.getStackTraceAsString());
342: throw le;
343: }
344: }
345: WriteXmlFile writeXmlFile;
346: if (generatorParameters.getGenerateXml()
347: .equalsIgnoreCase("true"))
348: writeXmlFile = new WriteXmlFile(document,
349: generatorParameters);
350:
351: } catch (ParserConfigurationException pce) {
352: // Parser with specified options can't be built
353: String msg = "Exception in CreateIncludeFiles class:Parser with specified options can't be built";
354: //if (this.logger != null) {
355:
356: //}
357: LoaderException le = new LoaderException(msg + "\n"
358: + pce, (Throwable) pce);
359: this .logger
360: .write(
361: "full",
362: "Exception in CreateIncludeFiles class:Parser with specified options can't be built."
363: + "\n"
364: + le.getStackTraceAsString());
365: throw le;
366: }
367: //System.out.println("\ndone...\n\n");
368: this .logger.write("normal", "\ndone...\n\n");
369: //BufferOctopusClass.getInstance().writeToBuffer("\ndone...\n\n");
370: }
371: //Create an importDefinition.xml file
372: else {
373: DocumentBuilderFactory factory = DocumentBuilderFactory
374: .newInstance();
375: DocumentBuilderFactory factoryDoml = DocumentBuilderFactory
376: .newInstance();
377: try {
378: // Create Importdefinition file, initializing the Document object and creatint the root
379: // element.
380: DocumentBuilder builder = factory.newDocumentBuilder();
381: document = builder.newDocument(); // Create from whole cloth
382: Element root = (Element) document
383: .createElement("definitionInclude");
384: document.appendChild(root);
385:
386: // Creating the doml file, initializing the Document object and creating the root,
387: // childRoot1 and childRoot2 elements.
388: DocumentBuilder builderDoml = factoryDoml
389: .newDocumentBuilder();
390: documentDoml = builderDoml.newDocument(); // Create from whole cloth
391: if ((generatorParameters.getGenerateDoml()
392: .equalsIgnoreCase("true"))) {
393: rootDoml = (Element) documentDoml
394: .createElement("doml");
395: documentDoml.appendChild(rootDoml);
396: childRoot1 = (Element) documentDoml
397: .createElement("database");
398: rootDoml.appendChild(childRoot1);
399: childRoot1.setAttribute("database",
400: generatorParameters.getTargetType());
401: //Element childRoot2=null;
402: StringTokenizer newPackage = new StringTokenizer(
403: generatorParameters.getPackageName(), ".");
404: Element tmp = childRoot1;
405: String name = "";
406: String packageName = "";
407: int count = 0;
408: while (newPackage.hasMoreTokens()) {
409: childRoot2 = (Element) documentDoml
410: .createElement("package");
411: tmp.appendChild(childRoot2);
412: packageName = newPackage.nextToken();
413: childRoot2.setAttribute("id", name
414: + packageName);
415: tmp = childRoot2;
416: if (count == 0)
417: name = packageName + ".";
418: else
419: name = name + packageName + ".";
420: count++;
421: }
422: }
423:
424: //Creating Sql file
425: JdbcParameters sourceJdbc = new JdbcParameters(
426: "source", generatorParameters);
427: Connection conn = null;
428: try {
429: URL url = null;
430: String app = "";
431: String path = AddClassPath.getClassPathString();
432: if (path != null) {
433: StringTokenizer st = new StringTokenizer(path,
434: ";");
435: int count = 0;
436: while (st.hasMoreTokens()) {
437: GeneratorClassLoader.addURL(new File(st
438: .nextElement().toString()).toURL());
439: }
440: Class.forName(sourceJdbc
441: .getJdbcParameters("JdbcDriver"));
442: } else {
443: Class.forName(sourceJdbc
444: .getJdbcParameters("JdbcDriver"));
445: }
446: conn = DriverManager.getConnection(sourceJdbc
447: .getJdbcParameters("Connection.Url"),
448: sourceJdbc.getJdbcParameters("User"),
449: sourceJdbc.getJdbcParameters("Password"));
450:
451: } catch (ClassNotFoundException ce) {
452: String msg = "Can't find driver class : ";
453: //if (this.logger != null) {
454:
455: //}
456: LoaderException le = new LoaderException(msg + "\n"
457: + ce.getMessage(), (Throwable) ce);
458: this .logger.write("full",
459: "Exception:Can't find driver class!" + "\n"
460: + le.getStackTraceAsString());
461: throw le;
462: } catch (Exception e) {
463: e.printStackTrace();
464: String msg = "Error while trying connect to database ( maybe password, username or database url is wrong ? ) :";
465: //if (this.logger != null) {
466:
467: //}
468: LoaderException le = new LoaderException(msg + "\n"
469: + e.getMessage(), (Throwable) e);
470: this .logger.write("full", "Exception:" + msg + "\n"
471: + le.getStackTraceAsString());
472: throw le;
473: }
474: String[] types = { "TABLE" };
475: String catalogName = null;
476: int index = generatorParameters.getSourceDataBase()
477: .indexOf("DatabaseName=");
478: int index1 = generatorParameters.getSourceDataBase()
479: .lastIndexOf(";");
480: if (index > 0) {
481: if (index1 > index) {
482: catalogName = generatorParameters
483: .getSourceDataBase().substring(
484: index + 13,
485: generatorParameters
486: .getSourceDataBase()
487: .lastIndexOf(";"));
488: } else {
489: catalogName = generatorParameters
490: .getSourceDataBase().substring(
491: index + 13);
492: }
493: } else {
494: int index2 = generatorParameters
495: .getSourceDataBase().lastIndexOf("\\");
496: int index3 = generatorParameters
497: .getSourceDataBase().lastIndexOf("/");
498: if (index2 > index3)
499: catalogName = generatorParameters
500: .getSourceDataBase().substring(
501: generatorParameters
502: .getSourceDataBase()
503: .lastIndexOf("\\") + 1);
504: else
505: catalogName = generatorParameters
506: .getSourceDataBase().substring(
507: generatorParameters
508: .getSourceDataBase()
509: .lastIndexOf("/") + 1);
510: }
511:
512: if (generatorParameters.getSourceType() != null
513: && (generatorParameters.getSourceType().equals(
514: "Hsqldb") || generatorParameters
515: .getSourceType()
516: .equals("HypersonicSQL"))
517: || generatorParameters.getSourceType().equals(
518: "DB2")) {
519: catalogName = null;
520: }
521: ResultSet rs = conn.getMetaData().getTables(
522: catalogName, null, "%", types);
523:
524: int i = 0;
525: while (rs.next()) {
526: String tableName = rs.getObject(3).toString();
527: boolean doJob = false;
528: //includeTable
529: if (generatorParameters.getIncludeTableList()
530: .size() == 0) {
531: doJob = true;
532: } else {
533: for (int j = 0; j < generatorParameters
534: .getIncludeTableList().size(); j++) {
535: if (tableName
536: .equalsIgnoreCase(generatorParameters
537: .getIncludeTableList().get(
538: j).toString())) {
539: doJob = true;
540: break;
541: }
542: }
543: }
544: //excludeTable
545: String[] list = generatorParameters
546: .getExcludedTables();
547: if (doJob) {
548: for (int j = 0; j < list.length; j++) {
549: if (tableName.equalsIgnoreCase(list[j])) {
550: doJob = false;
551: break;
552: }
553: }
554: }
555: if (generatorParameters.getValueMode()
556: .equalsIgnoreCase("Update")) {
557: //This method is not supported!
558: } else { //copy table mode
559: if (doJob) {
560: int counterOfConstraints = 0;
561: //System.out.println("Working...." + tableName);
562: //BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
563: //if (this.logger != null) {
564: this .logger.write("normal", "Working...."
565: + tableName);
566: //}
567: TableRelationshipsReader tableRelationshipsReader = new TableRelationshipsReader(
568: conn, tableName, catalogName,
569: generatorParameters,
570: counterOfConstraints);
571: TableDesignReader tableDesignReader = new TableDesignReader(
572: tableName, conn, catalogName,
573: generatorParameters);
574: if (generatorParameters.isGenerateSql()) {
575: WriteSqlFiles writeSql = new WriteSqlFiles(
576: tableName,
577: i,
578: tableDesignReader
579: .getImportDefinition(),
580: tableRelationshipsReader
581: .getRelationshipsAttributes(),
582: generatorParameters);
583: }
584:
585: try {
586: WriteImportDefinition writeImportDefinition;
587: if (generatorParameters
588: .getGenerateXml()
589: .equalsIgnoreCase("true"))
590: writeImportDefinition = new WriteImportDefinition(
591: document,
592: root,
593: tableDesignReader
594: .getImportDefinition(),
595: generatorParameters);
596: if ((generatorParameters
597: .getGenerateDoml()
598: .equalsIgnoreCase("true"))) {
599: GenerateDoml generateDoml;
600: generateDoml = new GenerateDoml(
601: documentDoml,
602: rootDoml,
603: childRoot1,
604: childRoot2,
605: tableName,
606: tableDesignReader
607: .getImportDefinition(),
608: tableRelationshipsReader
609: .getRelationshipsAttributes(),
610: generatorParameters);
611: }
612:
613: } catch (Exception pce) {
614:
615: LoaderException le = new LoaderException(
616: pce.getMessage(),
617: (Throwable) pce);
618: this .logger.write("full", "Exception:"
619: + le.getStackTraceAsString());
620: throw le;
621: }
622: i++;
623: } else {
624: //System.out.println("\tTable " + tableName + " is excluded from the process.");
625: //BufferOctopusClass.getInstance().writeToBuffer("\tTable " + tableName + " is excluded from the process.");
626: //if (this.logger != null) {
627: this .logger.write("normal", "Table "
628: + tableName
629: + " is excluded from the process.");
630: //}
631: }
632: } //end of Copy tableMode
633: }
634: if (i < 1) {
635: String msg = "There is no tables in specified source database ("
636: + catalogName
637: + "). Check input parameters.";
638: //if (this.logger != null) {
639:
640: //}
641: LoaderException le = new LoaderException(
642: "Exception:", new Exception(msg));
643: this .logger.write("full",
644: "Exception:There is no tables in specified source database ("
645: + catalogName + ")");
646: throw le;
647: }
648:
649: //System.out.println("\ndone...\n\n");
650: //BufferOctopusClass.getInstance().writeToBuffer("\ndone...\n\n");
651: //if (this.logger != null) {
652: this .logger.write("normal", "\ndone...\n\n");
653: //}
654: WriteXmlFile writeXmlFile;
655: if (generatorParameters.getGenerateXml()
656: .equalsIgnoreCase("true"))
657: writeXmlFile = new WriteXmlFile(document,
658: generatorParameters);
659:
660: if (generatorParameters.getGenerateDoml()
661: .equalsIgnoreCase("true")) {
662: WriteDomlFile writeDomlFile;
663: writeDomlFile = new WriteDomlFile(documentDoml,
664: generatorParameters);
665: }
666: conn.close();
667:
668: } catch (Exception e) {
669: String msg = "Exception in class CreateIncludeFiles:";
670: //if (this.logger != null) {
671:
672: //}
673: LoaderException le = new LoaderException(msg + "\n"
674: + e.getMessage(), (Throwable) e);
675: this .logger.write("full",
676: "Exception in class CreateIncludeFiles:"
677: + le.getStackTraceAsString());
678: throw le;
679: }
680: }
681: this .logger.write("normal",
682: "\tcreateIncludeFiles method is finished.");
683: }
684:
685: /**
686: * This method will set logger object
687: * @param logger
688: */
689: private void setLogger() {
690: this.logger = StandardLogger.getCentralLogger();
691: }
692: }
|