KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > tools > mapping > reversedb > DBTable


1 package org.apache.ojb.tools.mapping.reversedb;
2
3 /* Copyright 2002-2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 import javax.swing.tree.TreeNode JavaDoc;
19 import java.sql.SQLException JavaDoc;
20 import java.io.File JavaDoc;
21
22 /**
23  *
24  * @author <a HREF="mailto:bfl@florianbruckner.com">Florian Bruckner</a>
25  * @version $Id: DBTable.java,v 1.1.2.1 2005/12/21 22:32:04 tomdz Exp $
26  */

27 public class DBTable implements MetadataNodeInterface, TreeNode JavaDoc, org.apache.ojb.tools.mapping.reversedb.gui.PropertySheetModel
28 {
29   private java.sql.DatabaseMetaData JavaDoc dbMeta;
30   private DBSchema aSchema;
31   private java.util.HashMap JavaDoc hmReferences = new java.util.HashMap JavaDoc(0);
32   private java.util.HashMap JavaDoc hmCollections = new java.util.HashMap JavaDoc(0);
33   private java.util.TreeMap JavaDoc tmColumns = new java.util.TreeMap JavaDoc();
34   private java.util.Vector JavaDoc vSubTreeNodes = new java.util.Vector JavaDoc();
35   private String JavaDoc strTableName;
36   private String JavaDoc strClassName;
37   private String JavaDoc strPackageName = ""; // In default package by default ;-)
38
private String JavaDoc strConversionStrategyClass = "";
39   
40   private boolean dynamicProxy = false;
41
42   private boolean enabled = true;
43
44   
45   /** Creates a new instance of DBTable */
46   public DBTable (java.sql.DatabaseMetaData JavaDoc pdbMeta, DBSchema paSchema,
47                   String JavaDoc pstrTableName)
48   {
49     strTableName = pstrTableName;
50     // this.strClassName = Character.toUpperCase (strTableName.charAt(0)) + strTableName.substring(1).toLowerCase();
51
this.strClassName = Namer.nameClass(this.strTableName);
52     aSchema = paSchema;
53     dbMeta = pdbMeta;
54   }
55   
56   public boolean hasDynamicProxy()
57   {
58     return dynamicProxy;
59   }
60   
61   public void setDynamicProxy(boolean b)
62   {
63     dynamicProxy = b;
64   }
65   
66   public String JavaDoc getConversionStrategyClass()
67   {
68     return this.strConversionStrategyClass;
69   }
70   
71   public void setConversionStrategyClass(String JavaDoc s)
72   {
73     this.strConversionStrategyClass = s;
74   }
75   
76   public boolean isEnabled()
77   {
78     return this.enabled;
79   }
80   
81   public void setEnabled(boolean b)
82   {
83     this.enabled = b;
84   }
85   
86   public boolean isTreeEnabled()
87   {
88     return this.aSchema.isTreeEnabled() && this.isEnabled();
89   }
90   
91   
92   public DBColumn getColumn(String JavaDoc colName)
93   {
94     return (DBColumn)tmColumns.get(colName);
95   }
96   
97   public String JavaDoc getTableName()
98   {
99     return strTableName;
100   }
101   
102   public String JavaDoc getFQTableName()
103   {
104     String JavaDoc strReturn = null;
105     // Are table names supported in table definitions?
106
if (aSchema.getDBCatalog().getDBMeta().getSupportsCatalogsInTableDefinitions ())
107     {
108       // Yes, include catalog name in fq table name
109
// Now check, where we have to specify the catalog
110
if (aSchema.getDBCatalog().getDBMeta().getIsCatalogAtStart ())
111       {
112         // At the beginning
113
strReturn = aSchema.getDBCatalog().getCatalogName()
114           + aSchema.getDBCatalog().getDBMeta().getCatalogSeparator ()
115           + aSchema.getSchemaName() + "." + this.getTableName();
116       }
117       else
118       {
119         // At the end
120
strReturn = aSchema.getSchemaName() + "." + this.getTableName()
121           + aSchema.getDBCatalog().getDBMeta().getCatalogSeparator ()
122           + aSchema.getDBCatalog().getCatalogName();
123       }
124     }
125     else
126     {
127       strReturn = aSchema.getSchemaName() + "." + this.getTableName();
128     }
129     return strReturn;
130   }
131   
132   public String JavaDoc getClassName()
133   {
134     return strClassName;
135   }
136   
137   public void setClassName(String JavaDoc s)
138   {
139     this.strClassName = s;
140   }
141   
142   public String JavaDoc getPackageName()
143   {
144     return strPackageName;
145   }
146
147   public void setPackageName(String JavaDoc s)
148   {
149     this.strPackageName = s;
150   }
151   
152   public String JavaDoc getFQClassName()
153   {
154     if (this.getPackageName() != null && this.getPackageName().trim().length() > 0)
155       return this.getPackageName() + "." + this.getClassName();
156     else
157       return this.getClassName();
158   }
159   
160   public DBSchema getDBSchema()
161   {
162     return this.aSchema;
163   }
164   
165   
166   public void read() throws SQLException JavaDoc
167   {
168
169   }
170   
171   public void addColumn(String JavaDoc strColumnName,
172             int iDataType, String JavaDoc strTypeName, int iColumnSize, int iNullable)
173   {
174     DBColumn aDBColumn = new DBColumn(this.dbMeta, this, strColumnName, iDataType, strTypeName);
175     this.tmColumns.put(strColumnName, aDBColumn);
176   }
177   
178   public void addPrimaryKeyColumn(String JavaDoc strColumnName)
179   {
180     DBColumn aDBColumn = this.getColumn(strColumnName);
181     if (aDBColumn != null)
182     {
183       aDBColumn.setPrimaryKeyPart(true);
184     }
185   }
186   
187   public void generateReferences() throws SQLException JavaDoc
188   {
189     // Check if primary keys for this table have already been set. If not, do it now...
190
// This is necessary because Oracle doesn't return the Primary Keys for all tables
191
// and for Informix it speeds up things significantly if we do it onve for all tables.
192
java.util.Iterator JavaDoc it = this.tmColumns.values().iterator();
193     boolean hasNoPrimaryKey = true;
194     while (hasNoPrimaryKey && it.hasNext()) if ( ((DBColumn)it.next()).isPrimaryKeyPart()) hasNoPrimaryKey = false;
195     if (hasNoPrimaryKey) readPrimaryKeys();
196     
197     // Now generate References and Collections
198
generateFKReferences();
199     generateFKCollections();
200     vSubTreeNodes.addAll(this.tmColumns.values());
201     vSubTreeNodes.addAll(this.hmCollections.values());
202     vSubTreeNodes.addAll(this.hmReferences.values());
203   }
204   
205   public java.util.Enumeration JavaDoc children ()
206   {
207     return vSubTreeNodes.elements();
208   }
209   
210   public boolean getAllowsChildren ()
211   {
212     return true;
213   }
214   
215   public TreeNode JavaDoc getChildAt(int param)
216   {
217     TreeNode JavaDoc tn =
218       (TreeNode JavaDoc)vSubTreeNodes.elementAt(param);
219     return tn;
220   }
221   
222   public int getChildCount ()
223   {
224     return this.vSubTreeNodes.size();
225   }
226   
227   public int getIndex(TreeNode JavaDoc treeNode)
228   {
229     return this.vSubTreeNodes.indexOf(treeNode);
230   }
231   
232   public TreeNode JavaDoc getParent()
233   {
234     return this.aSchema;
235   }
236   
237   public boolean isLeaf ()
238   {
239     if (this.vSubTreeNodes.size() == 0) return true;
240     else return false;
241   }
242   
243   public String JavaDoc toString()
244   {
245     return this.strTableName;
246   }
247   
248   
249   private void readPrimaryKeys() throws SQLException JavaDoc
250   {
251     // Now get the primary keys for this table. Ignore any exceptions thrown here as
252
// primary keys are not absolutely necessary for reverse engineering
253
java.sql.ResultSet JavaDoc rs = null;
254     try
255     {
256       rs = dbMeta.getPrimaryKeys(null,
257                                   this.getDBSchema().getSchemaName(), this.strTableName);
258       while (rs.next())
259       {
260         String JavaDoc strCatalogName = rs.getString("TABLE_CAT");
261         String JavaDoc strSchemaName = rs.getString("TABLE_SCHEM");
262         if ( (strSchemaName == null && this.aSchema.getSchemaName() == null || strSchemaName.equals(this.aSchema.getSchemaName()))
263              &&
264              (strCatalogName == null && this.aSchema.getDBCatalog().getCatalogName() == null
265               || strCatalogName.equals(this.aSchema.getDBCatalog().getCatalogName())))
266         {
267           String JavaDoc strColumnName = rs.getString("COLUMN_NAME");
268           String JavaDoc pkName = rs.getString("PK_NAME");
269           DBColumn dbcol = (DBColumn)tmColumns.get(strColumnName);
270           if (dbcol != null) dbcol.setPrimaryKeyPart(true);
271         }
272       }
273     }
274     catch (SQLException JavaDoc sqlEx)
275     {
276       // Ignore excpetions here.
277
}
278     finally
279     {
280       try
281       {
282         rs.close();
283       }
284       catch (Throwable JavaDoc t)
285       {} // Ignore this exception
286
}
287   }
288
289   private void generateFKReferences() throws SQLException JavaDoc
290   {
291     // References, points from this class to another class using attributes
292
// of this class
293
// Ignore any exceptions thrown here.
294
java.sql.ResultSet JavaDoc rs = null;
295     try
296     {
297       rs = dbMeta.getImportedKeys(this.getDBSchema().getDBCatalog().getCatalogName(),
298                                                      this.getDBSchema().getSchemaName(), strTableName);
299       while (rs.next())
300       {
301         String JavaDoc strFKSchemaName = rs.getString("FKTABLE_SCHEM");
302         String JavaDoc strFKCatalogName = rs.getString("FKTABLE_CAT");
303
304         if ( (strFKCatalogName == null && this.aSchema.getDBCatalog().getCatalogName() == null || strFKCatalogName.equals(this.aSchema.getDBCatalog().getCatalogName()))
305             && (strFKSchemaName == null && this.aSchema.getSchemaName() == null || strFKSchemaName.equals(this.aSchema.getSchemaName())))
306         {
307           String JavaDoc strPKCatalogName = rs.getString("PKTABLE_CAT");
308           String JavaDoc strPKSchemaName = rs.getString("PKTABLE_SCHEM");
309           String JavaDoc strPKTableName = rs.getString("PKTABLE_NAME");
310           String JavaDoc strPKColumnName = rs.getString("PKCOLUMN_NAME");
311           String JavaDoc strFKTableName = rs.getString("FKTABLE_NAME");
312           String JavaDoc strFKColumnName = rs.getString("FKCOLUMN_NAME");
313
314           // Resolove the primaryKey column
315
DBCatalog dbPKCatalog = this.aSchema.getDBCatalog().getDBMeta().getCatalog(strPKCatalogName);
316           if (dbPKCatalog != null)
317           {
318             DBSchema dbPKSchem = dbPKCatalog.getSchema(strPKSchemaName);
319             if (dbPKSchem != null)
320             {
321               DBTable dbPKTable = dbPKSchem.getTable(strPKTableName);
322               if (dbPKTable != null)
323               {
324                 DBColumn dbPKColumn = dbPKTable.getColumn(strPKColumnName);
325                 // The FK column is always from this table.
326
DBColumn dbFKColumn = getColumn(strFKColumnName);
327
328                 // Now retrieve the FKReference to this table from the collection
329
DBFKRelation aFKRef =
330                   (DBFKRelation)this.hmReferences.get(dbPKSchem.getSchemaName()
331                     + "." + dbPKTable.getTableName());
332                 if (aFKRef == null)
333                 {
334                   aFKRef = new DBFKRelation(dbPKTable, this, false);
335                   this.hmReferences.put(dbPKSchem.getSchemaName()
336                     + "." + dbPKTable.getTableName(), aFKRef);
337                 }
338                 aFKRef.addColumnPair(dbPKColumn, dbFKColumn);
339               }
340             }
341           }
342         }
343       }
344     }
345     catch (SQLException JavaDoc sqlEx)
346     {
347       // sqlEx.printStackTrace();
348
}
349     try
350     {
351       rs.close();
352     }
353     catch (Throwable JavaDoc t) {}
354   }
355   
356   private void generateFKCollections() throws SQLException JavaDoc
357   {
358     // Collections, points from this class to a collection of objects using
359
// attributes from the referenced class
360
// Ignore any exceptions thrown here
361
java.sql.ResultSet JavaDoc rs = null;
362     try
363     {
364       rs = dbMeta.getExportedKeys(this.getDBSchema().getDBCatalog().getCatalogName(),
365                                                        this.getDBSchema().getSchemaName(), strTableName);
366       while (rs.next())
367       {
368         String JavaDoc strPKSchemaName = rs.getString("PKTABLE_SCHEM");
369         String JavaDoc strPKCatalogName = rs.getString("PKTABLE_CAT");
370
371         if ( (strPKSchemaName == null && this.aSchema.getSchemaName()==null || strPKSchemaName.equals(this.aSchema.getSchemaName()))
372              && (strPKCatalogName == null && this.aSchema.getDBCatalog().getCatalogName() == null
373                  || strPKCatalogName.equals(this.aSchema.getDBCatalog().getCatalogName())))
374         {
375           String JavaDoc strPKTableName = rs.getString("PKTABLE_NAME");
376           String JavaDoc strPKColumnName = rs.getString("PKCOLUMN_NAME");
377           String JavaDoc strFKCatalogName= rs.getString("FKTABLE_CAT");
378           String JavaDoc strFKTableName = rs.getString("FKTABLE_NAME");
379           String JavaDoc strFKColumnName = rs.getString("FKCOLUMN_NAME");
380           String JavaDoc strFKSchemaName = rs.getString("FKTABLE_SCHEM");
381
382           // Resolve the FK column. If catalog is supported in the index
383
// definition, resolve the catalog of the FK column, otherwise
384
// assume the current catalog (Note: This is needed for Informix,
385
// because the driver reports null for the catalog in this case.
386
DBCatalog dbFKCatalog = null;
387           if (this.aSchema.getDBCatalog().getDBMeta().getSupportsCatalogsInIndexDefinitions())
388           {
389             dbFKCatalog = this.aSchema.getDBCatalog().getDBMeta().getCatalog(strFKCatalogName);
390           }
391           else
392           {
393             dbFKCatalog = this.aSchema.getDBCatalog();
394           }
395           if (dbFKCatalog != null)
396           {
397             DBSchema dbFKSchema = dbFKCatalog.getSchema(strFKSchemaName);
398             if (dbFKSchema != null)
399             {
400               DBTable dbFKTable = dbFKSchema.getTable(strFKTableName);
401               if (dbFKTable != null)
402               {
403                 DBColumn dbFKColumn = dbFKTable.getColumn(strFKColumnName);
404                 // The PK column is always from this table
405
DBColumn dbPKColumn = getColumn(strPKColumnName);
406                 //Retrieve the FK Reference for the FK Table
407
DBFKRelation aFKRef =
408                   (DBFKRelation)this.hmCollections.get(dbFKSchema.getSchemaName()
409                     + "." + dbFKTable.getTableName());
410                 if (aFKRef == null)
411                 {
412                   aFKRef = new DBFKRelation(this, dbFKTable, true);
413                   this.hmCollections.put(dbFKSchema.getSchemaName()
414                     + "." + dbFKTable.getTableName(), aFKRef);
415                 }
416                 aFKRef.addColumnPair(dbPKColumn, dbFKColumn);
417               }
418             }
419           }
420         }
421       }
422     }
423     catch (SQLException JavaDoc sqlEx)
424     {
425       // sqlEx.printStackTrace();
426
}
427     try
428     {
429       rs.close();
430     }
431     catch (Throwable JavaDoc t)
432     {
433     }
434   }
435   
436   
437   public Class JavaDoc getPropertySheetClass ()
438   {
439     return org.apache.ojb.tools.mapping.reversedb.gui.DBTablePropertySheet.class;
440   }
441   
442   public String JavaDoc getXML()
443   {
444         java.io.StringWriter JavaDoc sw = new java.io.StringWriter JavaDoc();
445         writeXML(new java.io.PrintWriter JavaDoc(sw));
446         return sw.getBuffer().toString();
447   }
448   
449   public void writeXML(java.io.PrintWriter JavaDoc pw)
450   {
451     // Only generate a Classdescriptor if this table is enabled
452
if (this.isTreeEnabled())
453     {
454       java.util.Iterator JavaDoc it = tmColumns.values().iterator();
455       if (it.hasNext())
456       {
457         // Generate the class descriptor
458
pw.println("<class-descriptor ");
459           pw.println(" class=\"" + this.getFQClassName() + "\"");
460           pw.println(" table=\"" + this.getFQTableName() + "\">");
461           if (this.hasDynamicProxy())
462             pw.println(" <class.proxy>dynamic</class.proxy>");
463           if (this.getConversionStrategyClass () != null
464             && this.getConversionStrategyClass ().trim().length() > 0)
465             pw.println(" <conversionStrategy>" + this.getConversionStrategyClass () + "</conversionStrategy>");
466
467           it = this.tmColumns.values().iterator();
468         
469         while (it.hasNext())
470         {
471             ((DBColumn)it.next()).writeXML(pw);
472         }
473         
474         // Generate references
475
it = this.hmReferences.values().iterator();
476         while (it.hasNext())
477         {
478           ((DBFKRelation)it.next()).writeXML(pw);
479         }
480         // Generate collections
481
it = this.hmCollections.values().iterator();
482         while (it.hasNext())
483         {
484           ((DBFKRelation)it.next()).writeXML(pw);
485         }
486         pw.println("</class-descriptor>");
487       }
488     }
489   }
490   
491   public void generateJava(File JavaDoc aFile, String JavaDoc strHeader, String JavaDoc strFooter) throws java.io.IOException JavaDoc, java.io.FileNotFoundException JavaDoc
492   {
493     if (this.isTreeEnabled())
494     {
495       // 1. Generate the package directories
496
String JavaDoc dirName = this.getPackageName().replace('.', File.separatorChar);
497       File JavaDoc packageDir;
498       if (this.getPackageName() != null && this.getPackageName().trim().length() > 0)
499       {
500         packageDir = new File JavaDoc(aFile, dirName);
501       }
502       else
503       {
504         packageDir = aFile;
505       }
506
507       if (!packageDir.exists()) packageDir.mkdirs();
508       File JavaDoc javaFile = new File JavaDoc(packageDir, this.getClassName()+ ".java");
509       if (!javaFile.exists()) javaFile.createNewFile();
510       java.io.PrintWriter JavaDoc pw = new java.io.PrintWriter JavaDoc(new java.io.FileOutputStream JavaDoc(javaFile));
511       pw.println(strHeader);
512       pw.println("// Generated by OJB SchemeGenerator");
513       pw.println();
514       if (this.getPackageName().trim().length() > 0)
515       {
516         pw.println("package " + this.getPackageName() + ";");
517         pw.println();
518       }
519       pw.println("public class " + this.getClassName());
520       pw.println("{");
521
522       // Generate Fields
523
java.util.Iterator JavaDoc it = this.tmColumns.values().iterator();
524       while (it.hasNext())
525       {
526         pw.println(((DBColumn)it.next()).getJavaFieldDefinition());
527         pw.println();
528       }
529
530       it = this.hmReferences.values().iterator();
531       while (it.hasNext())
532       {
533         pw.println(((DBFKRelation)it.next()).getJavaFieldDefinition());
534         pw.println();
535       }
536
537       it = this.hmCollections.values().iterator();
538       while (it.hasNext())
539       {
540         pw.println(((DBFKRelation)it.next()).getJavaFieldDefinition());
541         pw.println();
542       }
543
544       // Generate Getter/Setter
545
it = this.tmColumns.values().iterator();
546       while (it.hasNext())
547       {
548         pw.println(((DBColumn)it.next()).getJavaGetterSetterDefinition());
549         pw.println();
550       }
551
552       it = this.hmReferences.values().iterator();
553       while (it.hasNext())
554       {
555         pw.println(((DBFKRelation)it.next()).getJavaGetterSetterDefinition());
556         pw.println();
557       }
558
559       it = this.hmCollections.values().iterator();
560       while (it.hasNext())
561       {
562         pw.println(((DBFKRelation)it.next()).getJavaGetterSetterDefinition());
563         pw.println();
564       }
565
566       pw.println("}");
567       pw.println(strFooter);
568       pw.close();
569     }
570   }
571   
572   public void setPackage (String JavaDoc packageName)
573   {
574     this.setPackageName(packageName);
575   }
576   
577   public void disableClassesWithRegex(org.apache.regexp.RE aRegexp)
578   {
579     if (aRegexp.match(this.getClassName())) this.setEnabled(false);
580   }
581   
582 }
583
584
585 /***************************** Changelog *****************************
586 // $Log: DBTable.java,v $
587 // Revision 1.1.2.1 2005/12/21 22:32:04 tomdz
588 // Updated license
589 //
590 // Revision 1.1 2004/05/05 16:39:05 arminw
591 // fix fault
592 // wrong package structure used:
593 // org.apache.ojb.tools.reversdb
594 // org.apache.ojb.tools.reversdb2
595 //
596 // instead of
597 // org.apache.ojb.tools.mapping.reversdb
598 // org.apache.ojb.tools.mapping.reversdb2
599 //
600 // Revision 1.1 2004/05/04 13:45:01 arminw
601 // move reverseDB stuff
602 //
603 // Revision 1.9 2004/04/04 23:53:42 brianm
604 // Fixed initial copyright dates to match cvs repository
605 //
606 // Revision 1.8 2004/03/11 18:16:22 brianm
607 // ASL 2.0
608 //
609 // Revision 1.7 2003/12/12 16:37:16 brj
610 // removed unnecessary casts, semicolons etc.
611 //
612 // Revision 1.6 2003/07/22 11:05:13 florianbruckner
613 // add a name beautifier (courtesy G.Wayne Kidd)
614 //
615 // Revision 1.5 2003/06/21 10:35:03 florianbruckner
616 // implement XML generation with PrintWriter; getXML() still works and uses writeXML(java.io.PrintWriter)
617 // does not generate an Id anymore.
618 //
619 // Revision 1.4 2003/01/28 21:42:53 florianbruckner
620 // update XML generation
621 //
622 // Revision 1.3 2003/01/28 19:59:14 florianbruckner
623 // some updates to schema reading to make it a bit more compatible
624 //
625 // Revision 1.2 2002/06/17 19:34:33 jvanzyl
626 // Correcting all the package references.
627 // PR:
628 // Obtained from:
629 // Submitted by:
630 // Reviewed by:
631 //
632 // Revision 1.1.1.1 2002/06/17 18:16:52 jvanzyl
633 // Initial OJB import
634 //
635 // Revision 1.3 2002/05/16 11:47:09 florianbruckner
636 // fix CR/LF issue, change license to ASL
637 //
638 // Revision 1.2 2002/05/16 10:43:59 florianbruckner
639 // use jakarta-regexp instead of gnu-regexp due to the move to jakarta.
640 //
641 // Revision 1.1 2002/04/18 11:44:16 mpoeschl
642 //
643 // move files to new location
644 //
645 // Revision 1.3 2002/04/07 09:05:16 thma
646 // *** empty log message ***
647 //
648 // Revision 1.2 2002/03/11 17:36:05 florianbruckner
649 // fix line break issue for these files that were previously checked in with -kb
650 //
651 // Revision 1.1 2002/03/04 17:19:32 thma
652 // initial checking for Florians Reverse engineering tool
653 //
654 // Revision 1.2 2002/02/20 13:55:11 Administrator
655 // add semicolon after package name
656 //
657 // Revision 1.1.1.1 2002/02/20 13:35:25 Administrator
658 // initial import
659 //
660 /***************************** Changelog *****************************/

661
Popular Tags