KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > webdocwf > util > loader > generator > CreateIncludeFiles


1 /*
2      LoaderGenerator - tool for generated xml, sql and doml file needed for Octopus.
3     Copyright (C) 2003 Together
4     This library is free software; you can redistribute it and/or
5     modify it under the terms of the GNU Lesser General Public
6     License as published by the Free Software Foundation; either
7     version 2.1 of the License, or (at your option) any later version.
8     This library is distributed in the hope that it will be useful,
9     but WITHOUT ANY WARRANTY; without even the implied warranty of
10     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11     Lesser General Public License for more details.
12     You should have received a copy of the GNU Lesser General Public
13     License along with this library; if not, write to the Free Software
14     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15  */

16 package org.webdocwf.util.loader.generator;
17
18 import javax.xml.parsers.DocumentBuilder JavaDoc;
19 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
20 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
21 import javax.xml.parsers.ParserConfigurationException JavaDoc;
22
23 import org.w3c.dom.Document JavaDoc;
24
25 import org.w3c.dom.Element JavaDoc;
26
27 import java.io.*;
28 import java.sql.*;
29
30 import java.util.StringTokenizer JavaDoc;
31 import org.webdocwf.util.loader.*;
32
33 import java.net.*;
34
35 import org.webdocwf.util.loader.logging.Logger;
36 import org.webdocwf.util.loader.logging.StandardLogger;
37 import org.webdocwf.util.loader.wizard.AddClassPath;
38
39 /**
40  * CreateIncludeFiles class creates Xml(ImportDefinition.xml) and Sql( CreateTables.sql,
41  * CreateIntegrity.sql, CreateOisAdminData.sql, CreatePrimary.sql and CreateIndex.sql) files,
42  * if the input data is database.
43  * @author Radoslav Dutina
44  * @version 1.0
45  */

46 public class CreateIncludeFiles {
47
48     private Document JavaDoc document;
49     private Document JavaDoc documentDoml;
50     private Element JavaDoc rootDoml = null;
51     private Element JavaDoc childRoot1 = null;
52     private Element JavaDoc childRoot2 = null;
53     private Logger logger;
54     private InputParameters generatorParameters;
55
56
57     /**
58         * Construct object CreateIncludeFiles with associated parameter.
59         * @param generatorParameters represents the references to InputParameter object.
60         * @throws LoaderException
61         */

62     public CreateIncludeFiles(InputParameters generatorParameters) throws LoaderException {
63
64         try {
65                         setLogger();
66                         this.logger.write("normal","CreateIncludeFiles is started. Generating sql and xml files is started.");
67             createIncludeFiles(generatorParameters);
68                         this.logger.write("normal","CreateIncludeFiles is finished. Generating sql and xml files is finished.");
69         } catch (Exception JavaDoc e) {
70             throw new LoaderException("Exception:Error while create include files.", e);
71         } catch (FactoryConfigurationError JavaDoc e) {
72             throw new LoaderException("FactoryConfigurationError:Error while create include files.", e);
73         }
74     }
75
76
77 /**
78  * This method will generate all xml and sql files
79  * @param generatorParameters
80  * @throws LoaderException
81  * @throws FactoryConfigurationError
82  */

83     private void createIncludeFiles(InputParameters generatorParameters) throws LoaderException, FactoryConfigurationError JavaDoc {
84         
85                 this.logger.write("normal", "\tcreateIncludeFiles method is started.");
86         if (generatorParameters.getSourceDriverName().equalsIgnoreCase("freetds")) {
87            // if (this.logger != null) {
88

89            // }
90
//BufferOctopusClass.getInstance().writeToBuffer("Eroor : Freetds driver can't be used as source driver.");
91
LoaderException le = new LoaderException("Exception:", (Throwable JavaDoc) new Exception JavaDoc("Freetds driver can't be used as source driver."));
92                         this.logger.write("full", "Eroor : Freetds driver can't be used as source driver."+le.getStackTraceAsString());
93                         throw le;
94         }
95         
96
97         //Create an importDefinition.xml file, for csv tables
98
if (generatorParameters.getSourceType().equalsIgnoreCase("csv") || generatorParameters.getSourceType().equalsIgnoreCase("access") || generatorParameters.getSourceType().equalsIgnoreCase("xml")) {
99
100             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
101             DocumentBuilderFactory JavaDoc factoryDoml = DocumentBuilderFactory.newInstance();
102             try {
103                 DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
104                 document = builder.newDocument(); // Create from whole cloth
105
//for creating the doml file
106
DocumentBuilder JavaDoc builderDoml = factoryDoml.newDocumentBuilder();
107                 documentDoml = builderDoml.newDocument(); // Create from whole cloth
108

109                 Element JavaDoc rootDoml = (Element JavaDoc) documentDoml.createElement("doml");
110                 documentDoml.appendChild(rootDoml);
111
112                 Element JavaDoc childRoot1 = (Element JavaDoc) documentDoml.createElement("database");
113                 rootDoml.appendChild(childRoot1);
114                 childRoot1.setAttribute("database", generatorParameters.getTargetType());
115
116                 Element JavaDoc root = (Element JavaDoc) document.createElement("definitionInclude");
117                 document.appendChild(root);
118                 if (generatorParameters.getSourceType().equalsIgnoreCase("csv") || generatorParameters.getSourceType().equalsIgnoreCase("xml")) {
119                     String JavaDoc pathToSource = generatorParameters.getSourceDataBase();
120                     int endNameDB = pathToSource.indexOf(";");
121                     if (endNameDB != -1)
122                         pathToSource = pathToSource.substring(0, endNameDB);
123
124                     File file = new File(pathToSource);
125                     String JavaDoc[] listFiles = file.list();
126                     if (listFiles == null && listFiles.length == 0) {
127                         String JavaDoc msg = "Path to source database is wrong, or database is empty!";
128                         //if (this.logger != null) {
129

130                         //}
131
LoaderException le = new LoaderException("Exception:", new Exception JavaDoc(msg));
132                                                 this.logger.write("full", "Path to source database is wrong, or database is empty!"+le.getStackTraceAsString());
133                         throw le;
134                     }
135                     int x = 0;
136                     for (int i = 0; i < listFiles.length; i++) {
137                         String JavaDoc tableName = listFiles[i].substring(0, listFiles[i].lastIndexOf("."));
138                         if (!tableName.endsWith("csvext")) {
139                             //includeTable
140
boolean doJob = false;
141                             if (generatorParameters.getIncludeTableList().size() == 0) {
142                                 doJob = true;
143                             } else {
144                                 for (int j = 0; j < generatorParameters.getIncludeTableList().size(); j++) {
145                                     if (tableName.equalsIgnoreCase(generatorParameters.getIncludeTableList().get(j).toString())) {
146                                         doJob = true;
147                                         break;
148                                     }
149                                 }
150                             }
151                             if (doJob) {
152                                 //System.out.println("Working...." + tableName);
153
//BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
154
//if (this.logger != null) {
155
this.logger.write("normal", "Working...." + tableName);
156                                 //}
157
CsvTableDesignReader csvTableDesignReader = new CsvTableDesignReader(tableName, generatorParameters);
158                                 WriteImportDefinition writeImportDefinition = new WriteImportDefinition(document, root, csvTableDesignReader.getImportDefinition(), generatorParameters);
159                                 WriteSqlFiles writeSql = new WriteSqlFiles(tableName, x, csvTableDesignReader.getImportDefinition(), null, generatorParameters);
160                                 x++;
161                             }
162
163                         }
164                     }
165                     if (x < 1) {
166                         String JavaDoc msg = "There is no tables in specified source database. Check input parameters.";
167                         //if (this.logger != null) {
168

169                         //}
170
LoaderException le = new LoaderException("Exception:", new Exception JavaDoc(msg));
171                                                 this.logger.write("full", "There is no tables in specified source database. Check input parameters."+le.getStackTraceAsString());
172                         throw le;
173                     }
174                 } else { //access,excel database
175
JdbcParameters sourceJdbc = new JdbcParameters("source", generatorParameters);
176                     try {
177                         Connection conn = null;
178                         URL url = null;
179                         String JavaDoc app = "";
180                         String JavaDoc path = AddClassPath.getClassPathString();
181                         if (path != null) {
182                             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(path, ";");
183                             int count = 0;
184                             while (st.hasMoreTokens()) {
185                                 GeneratorClassLoader.addURL(new File(st.nextElement().toString()).toURL());
186                             }
187                             Class.forName(sourceJdbc.getJdbcParameters("JdbcDriver"));
188                         } else {
189                             Class.forName(sourceJdbc.getJdbcParameters("JdbcDriver"));
190                         }
191                         conn = DriverManager.getConnection(sourceJdbc.getJdbcParameters("Connection.Url"), sourceJdbc.getJdbcParameters("User"), sourceJdbc.getJdbcParameters("Password"));
192
193                         Statement stmt = conn.createStatement();
194                         String JavaDoc[] accessType = { "TABLE" };
195                         String JavaDoc accessDbName = generatorParameters.getSourceDataBase();
196                         ResultSet rs = conn.getMetaData().getTables(accessDbName, null, "%", accessType);
197
198                         int i = 0;
199                         while (rs.next()) {
200                             String JavaDoc tableName = rs.getString(3);
201                             //includeTable
202
boolean doJob = false;
203                             if (generatorParameters.getIncludeTableList().size() == 0) {
204                                 doJob = true;
205                             } else {
206                                 for (int j = 0; j < generatorParameters.getIncludeTableList().size(); j++) {
207                                     if (tableName.equalsIgnoreCase(generatorParameters.getIncludeTableList().get(j).toString())) {
208                                         doJob = true;
209                                         break;
210                                     }
211                                 }
212                             }
213                             if (doJob) {
214                                 //System.out.println("Working...." + tableName);
215
//BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
216
//if (this.logger != null) {
217
this.logger.write("normal", "Working...." + tableName);
218                                 //}
219
CsvTableDesignReader csvTableDesignReader = new CsvTableDesignReader(tableName, generatorParameters);
220
221                                 WriteImportDefinition writeImportDefinition = new WriteImportDefinition(document, root, csvTableDesignReader.getImportDefinition(), generatorParameters);
222                                 WriteSqlFiles writeSql = new WriteSqlFiles(tableName, i, csvTableDesignReader.getImportDefinition(), null, generatorParameters);
223                                 i++;
224                             }
225                         }
226                         if (i < 1) {
227                             String JavaDoc msg = "There is no tables in specified source database. Check input parameters.";
228                             //if (this.logger != null) {
229

230                             //}
231
LoaderException le = new LoaderException("Exception:", new Exception JavaDoc(msg));
232                                                         this.logger.write("full", "Exception:There is no tables in specified source database. Check input parameters."+le.getStackTraceAsString());
233                             throw le;
234                         }
235                         rs.close();
236                     } catch (ClassNotFoundException JavaDoc ce) {
237                         String JavaDoc msg = "Can't find driver class : ";
238                         //if (this.logger != null) {
239

240                         //}
241
LoaderException le = new LoaderException(msg + "\n" + ce.getMessage(), (Throwable JavaDoc) ce);
242                                                 this.logger.write("full", "Exception:Can't find driver class!" + "\n" + le.getStackTraceAsString());
243                         throw le;
244                     } catch (Exception JavaDoc e) {
245                         String JavaDoc msg = "Error while trying connect to database ( maybe password or username is wrong ? ) :";
246                         //if (this.logger != null) {
247

248                         //}
249
LoaderException le = new LoaderException(msg + "\n" + e.getMessage(), (Throwable JavaDoc) e);
250                                                 this.logger.write("full", "Exception:" + msg + "\n" + le.getStackTraceAsString());
251                         throw le;
252                     }
253                 }
254                 WriteXmlFile writeXmlFile;
255                 if (generatorParameters.getGenerateXml().equalsIgnoreCase("true"))
256                     writeXmlFile = new WriteXmlFile(document, generatorParameters);
257
258             } catch (ParserConfigurationException JavaDoc pce) {
259                 // Parser with specified options can't be built
260
String JavaDoc msg = "Exception in CreateIncludeFiles class:Parser with specified options can't be built";
261                 //if (this.logger != null) {
262

263                 //}
264
LoaderException le = new LoaderException(msg + "\n" + pce, (Throwable JavaDoc) pce);
265                                 this.logger.write("full", "Exception in CreateIncludeFiles class:Parser with specified options can't be built." + "\n" + le.getStackTraceAsString());
266                 throw le;
267             }
268             //System.out.println("\ndone...\n\n");
269
this.logger.write("normal", "\ndone...\n\n");
270             //BufferOctopusClass.getInstance().writeToBuffer("\ndone...\n\n");
271
}
272         //Create an importDefinition.xml file
273
else {
274             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
275             DocumentBuilderFactory JavaDoc factoryDoml = DocumentBuilderFactory.newInstance();
276             try {
277                 // Create Importdefinition file, initializing the Document object and creatint the root
278
// element.
279
DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
280                 document = builder.newDocument(); // Create from whole cloth
281
Element JavaDoc root = (Element JavaDoc) document.createElement("definitionInclude");
282                 document.appendChild(root);
283
284                 // Creating the doml file, initializing the Document object and creating the root,
285
// childRoot1 and childRoot2 elements.
286
DocumentBuilder JavaDoc builderDoml = factoryDoml.newDocumentBuilder();
287                 documentDoml = builderDoml.newDocument(); // Create from whole cloth
288
if ((generatorParameters.getGenerateDoml().equalsIgnoreCase("true"))) {
289                     rootDoml = (Element JavaDoc) documentDoml.createElement("doml");
290                     documentDoml.appendChild(rootDoml);
291                     childRoot1 = (Element JavaDoc) documentDoml.createElement("database");
292                     rootDoml.appendChild(childRoot1);
293                     childRoot1.setAttribute("database", generatorParameters.getTargetType());
294                     //Element childRoot2=null;
295
StringTokenizer JavaDoc newPackage = new StringTokenizer JavaDoc(generatorParameters.getPackageName(), ".");
296                     Element JavaDoc tmp = childRoot1;
297                     String JavaDoc name = "";
298                     String JavaDoc packageName = "";
299                     int count = 0;
300                     while (newPackage.hasMoreTokens()) {
301                         childRoot2 = (Element JavaDoc) documentDoml.createElement("package");
302                         tmp.appendChild(childRoot2);
303                         packageName = newPackage.nextToken();
304                         childRoot2.setAttribute("id", name + packageName);
305                         tmp = childRoot2;
306                         if (count == 0)
307                             name = packageName + ".";
308                         else
309                             name = name + packageName + ".";
310                         count++;
311                     }
312                 }
313
314                 //Creating Sql file
315
JdbcParameters sourceJdbc = new JdbcParameters("source", generatorParameters);
316                 Connection conn = null;
317                 try {
318                     URL url = null;
319                     String JavaDoc app = "";
320                     String JavaDoc path = AddClassPath.getClassPathString();
321                     if (path != null) {
322                         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(path, ";");
323                         int count = 0;
324                         while (st.hasMoreTokens()) {
325                             GeneratorClassLoader.addURL(new File(st.nextElement().toString()).toURL());
326                         }
327                         Class.forName(sourceJdbc.getJdbcParameters("JdbcDriver"));
328                     } else {
329                         Class.forName(sourceJdbc.getJdbcParameters("JdbcDriver"));
330                     }
331                     conn = DriverManager.getConnection(sourceJdbc.getJdbcParameters("Connection.Url"), sourceJdbc.getJdbcParameters("User"), sourceJdbc.getJdbcParameters("Password"));
332
333                 } catch (ClassNotFoundException JavaDoc ce) {
334                     String JavaDoc msg = "Can't find driver class : ";
335                     //if (this.logger != null) {
336

337                     //}
338
LoaderException le = new LoaderException(msg + "\n" + ce.getMessage(), (Throwable JavaDoc) ce);
339                                         this.logger.write("full", "Exception:Can't find driver class!" + "\n" + le.getStackTraceAsString());
340                     throw le;
341                 } catch (Exception JavaDoc e) {
342                     e.printStackTrace();
343                     String JavaDoc msg = "Error while trying connect to database ( maybe password, username or database url is wrong ? ) :";
344                     //if (this.logger != null) {
345

346                     //}
347
LoaderException le = new LoaderException(msg + "\n" + e.getMessage(), (Throwable JavaDoc) e);
348                                         this.logger.write("full", "Exception:" + msg + "\n" + le.getStackTraceAsString());
349                     throw le;
350                 }
351                 String JavaDoc[] types = { "TABLE" };
352                 String JavaDoc catalogName = null;
353                 int index = generatorParameters.getSourceDataBase().indexOf("DatabaseName=");
354                 int index1 = generatorParameters.getSourceDataBase().lastIndexOf(";");
355                 if (index > 0) {
356                     if (index1 > index) {
357                         catalogName = generatorParameters.getSourceDataBase().substring(index + 13, generatorParameters.getSourceDataBase().lastIndexOf(";"));
358                     } else {
359                         catalogName = generatorParameters.getSourceDataBase().substring(index + 13);
360                     }
361                 } else {
362                     int index2 = generatorParameters.getSourceDataBase().lastIndexOf("\\");
363                     int index3 = generatorParameters.getSourceDataBase().lastIndexOf("/");
364                     if (index2 > index3)
365                         catalogName = generatorParameters.getSourceDataBase().substring(generatorParameters.getSourceDataBase().lastIndexOf("\\") + 1);
366                     else
367                         catalogName = generatorParameters.getSourceDataBase().substring(generatorParameters.getSourceDataBase().lastIndexOf("/") + 1);
368                 }
369
370                 if(generatorParameters.getSourceType() != null &&
371                         (generatorParameters.getSourceType().equals("Hsqldb") ||
372                         generatorParameters.getSourceType().equals("HypersonicSQL")) ||
373                         generatorParameters.getSourceType().equals("DB2")
374                         ) {
375                         catalogName = null;
376                 }
377                 ResultSet rs = conn.getMetaData().getTables(catalogName, null, "%", types);
378
379                 int i = 0;
380                 while (rs.next()) {
381                     String JavaDoc tableName = rs.getObject(3).toString();
382                     boolean doJob = false;
383                     //includeTable
384
if (generatorParameters.getIncludeTableList().size() == 0) {
385                         doJob = true;
386                     } else {
387                         for (int j = 0; j < generatorParameters.getIncludeTableList().size(); j++) {
388                             if (tableName.equalsIgnoreCase(generatorParameters.getIncludeTableList().get(j).toString())) {
389                                 doJob = true;
390                                 break;
391                             }
392                         }
393                     }
394                     //excludeTable
395
String JavaDoc[] list = generatorParameters.getExcludedTables();
396                     if (doJob) {
397                         for (int j = 0; j < list.length; j++) {
398                             if (tableName.equalsIgnoreCase(list[j])) {
399                                 doJob = false;
400                                 break;
401                             }
402                         }
403                     }
404                     if (generatorParameters.getValueMode().equalsIgnoreCase("Update")) {
405                         //This method is not supported!
406
} else { //copy table mode
407
if (doJob) {
408                             int counterOfConstraints = 0;
409                             //System.out.println("Working...." + tableName);
410
//BufferOctopusClass.getInstance().writeToBuffer("Working...." + tableName);
411
//if (this.logger != null) {
412
this.logger.write("normal", "Working...." + tableName);
413                             //}
414
TableRelationshipsReader tableRelationshipsReader = new TableRelationshipsReader(conn, tableName, catalogName, generatorParameters, counterOfConstraints);
415                             TableDesignReader tableDesignReader = new TableDesignReader(tableName, conn, catalogName, generatorParameters);
416                             if (generatorParameters.isGenerateSql()) {
417                                 WriteSqlFiles writeSql = new WriteSqlFiles(tableName, i, tableDesignReader.getImportDefinition(), tableRelationshipsReader.getRelationshipsAttributes(), generatorParameters);
418                             }
419
420                             try {
421                                 WriteImportDefinition writeImportDefinition;
422                                 if (generatorParameters.getGenerateXml().equalsIgnoreCase("true"))
423                                     writeImportDefinition = new WriteImportDefinition(document, root, tableDesignReader.getImportDefinition(), generatorParameters);
424                                 if ((generatorParameters.getGenerateDoml().equalsIgnoreCase("true"))) {
425                                     GenerateDoml generateDoml;
426                                     generateDoml = new GenerateDoml(documentDoml, rootDoml, childRoot1, childRoot2, tableName, tableDesignReader.getImportDefinition(), tableRelationshipsReader.getRelationshipsAttributes(), generatorParameters);
427                                 }
428
429                             } catch (Exception JavaDoc pce) {
430                                 
431                                 LoaderException le = new LoaderException(pce.getMessage(), (Throwable JavaDoc) pce);
432                                                                 this.logger.write("full", "Exception:"+le.getStackTraceAsString());
433                                 throw le;
434                             }
435                             i++;
436                         } else {
437                             //System.out.println("\tTable " + tableName + " is excluded from the process.");
438
//BufferOctopusClass.getInstance().writeToBuffer("\tTable " + tableName + " is excluded from the process.");
439
//if (this.logger != null) {
440
this.logger.write("normal", "Table " + tableName + " is excluded from the process.");
441                             //}
442
}
443                     } //end of Copy tableMode
444
}
445                 if (i < 1) {
446                     String JavaDoc msg = "There is no tables in specified source database (" + catalogName + "). Check input parameters.";
447                     //if (this.logger != null) {
448

449                     //}
450
LoaderException le = new LoaderException("Exception:", new Exception JavaDoc(msg));
451                                         this.logger.write("full", "Exception:There is no tables in specified source database (" + catalogName + ")");
452                     throw le;
453                 }
454
455                 //System.out.println("\ndone...\n\n");
456
//BufferOctopusClass.getInstance().writeToBuffer("\ndone...\n\n");
457
//if (this.logger != null) {
458
this.logger.write("normal", "\ndone...\n\n");
459                 //}
460
WriteXmlFile writeXmlFile;
461                 if (generatorParameters.getGenerateXml().equalsIgnoreCase("true"))
462                     writeXmlFile = new WriteXmlFile(document, generatorParameters);
463
464                 if (generatorParameters.getGenerateDoml().equalsIgnoreCase("true")) {
465                     WriteDomlFile writeDomlFile;
466                     writeDomlFile = new WriteDomlFile(documentDoml, generatorParameters);
467                 }
468                 conn.close();
469
470             } catch (Exception JavaDoc e) {
471                 String JavaDoc msg = "Exception in class CreateIncludeFiles:";
472                 //if (this.logger != null) {
473

474                 //}
475
LoaderException le = new LoaderException(msg + "\n" + e.getMessage(), (Throwable JavaDoc) e);
476                 this.logger.write("full", "Exception in class CreateIncludeFiles:" + le.getStackTraceAsString());
477                 throw le;
478             }
479         }
480                 this.logger.write("normal", "\tcreateIncludeFiles method is finished.");
481     }
482
483       /**
484      * This method will set logger object
485      * @param logger
486      */

487     private void setLogger() {
488         this.logger = StandardLogger.getCentralLogger();
489     }
490 }
Popular Tags