KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > jdo > spi > persistence > support > ejb > ejbc > JDOCodeGenerator


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * JDOCodeGenerator.java
26  *
27  * Created on November 14, 2001
28  */

29
30 package com.sun.jdo.spi.persistence.support.ejb.ejbc;
31
32 import java.io.BufferedOutputStream JavaDoc;
33 import java.io.File JavaDoc;
34 import java.io.FileOutputStream JavaDoc;
35 import java.io.OutputStream JavaDoc;
36 import java.io.IOException JavaDoc;
37
38 import java.util.*;
39
40 import java.sql.Connection JavaDoc;
41 import java.sql.SQLException JavaDoc;
42
43 import com.sun.ejb.codegen.CMPGenerator;
44 import com.sun.ejb.codegen.EjbcContext;
45 import com.sun.ejb.codegen.GeneratorException;
46
47 import com.sun.enterprise.deployment.EjbBundleDescriptor;
48 import com.sun.enterprise.deployment.IASEjbCMPEntityDescriptor;
49
50 import com.sun.enterprise.deployment.backend.Deployer;
51 import com.sun.enterprise.deployment.io.DescriptorConstants;
52 import com.sun.enterprise.deployment.interfaces.QueryParser;
53
54 import com.sun.jdo.spi.persistence.utility.I18NHelper;
55 import com.sun.jdo.spi.persistence.utility.MergedBundle;
56 import com.sun.jdo.spi.persistence.utility.logging.Logger;
57 import com.sun.jdo.spi.persistence.utility.database.DatabaseConstants;
58
59 import com.sun.jdo.api.persistence.enhancer.generator.Main;
60
61 import com.sun.jdo.api.persistence.model.Model;
62 import com.sun.jdo.api.persistence.model.ModelException;
63 import com.sun.jdo.api.persistence.model.mapping.MappingClassElement;
64
65 import com.sun.jdo.api.persistence.mapping.ejb.ConversionException;
66
67 import com.sun.jdo.spi.persistence.support.ejb.enhancer.meta.EJBMetaDataModelImpl;
68 import com.sun.jdo.spi.persistence.support.ejb.model.DeploymentDescriptorModel;
69 import com.sun.jdo.spi.persistence.support.ejb.ejbqlc.EJBQLException;
70
71 import com.sun.jdo.api.persistence.support.JDOUserException;
72
73 import com.sun.jdo.spi.persistence.support.sqlstore.ejb.DeploymentHelper;
74 import com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.JDOQLParameterDeclarationParser;
75
76 import com.sun.jdo.spi.persistence.generator.database.DDLGenerator;
77 import com.sun.jdo.spi.persistence.generator.database.DatabaseOutputStream;
78
79 import org.netbeans.modules.dbschema.DBException;
80 import org.netbeans.modules.dbschema.SchemaElement;
81
82 import org.netbeans.modules.schema2beans.Schema2BeansException;
83
84 /*
85  * This is the JDO specific generator for the concrete CMP beans and any
86  * other dependent files.
87  *
88  * @author Marina Vatkina
89  */

90 public class JDOCodeGenerator
91     implements CMPGenerator, DatabaseConstants {
92
93     /**
94      * Signature with CVS keyword substitution for identifying the generated code
95      */

96     public static final String JavaDoc SIGNATURE = "$RCSfile: JDOCodeGenerator.java,v $ $Revision: 1.7 $"; //NOI18N
97

98     private static final String JavaDoc MAPPING_EXTENSION = ".mapping"; // NOI18N
99

100      /** The logger */
101     private static final Logger logger = LogHelperEJBCompiler.getLogger();
102
103      /** The resource bundle used for validation */
104     private static final ResourceBundle validationBundle = new MergedBundle(
105         I18NHelper.loadBundle(DeploymentDescriptorModel.class),
106         I18NHelper.loadBundle(Model.class));
107
108     private ArrayList files = new ArrayList();
109
110     private EjbcContext ejbcContext = null;
111     private ClassLoader JavaDoc loader = null;
112     private JDOConcreteBeanGenerator cmp11Generator;
113     private JDOConcreteBeanGenerator cmp20Generator;
114     private EjbBundleDescriptor bundle = null;
115     private NameMapper nameMapper;
116     private Model model;
117     private EJBMetaDataModelImpl ejbModel;
118     private static QueryParser jdoqlParamDeclParser = new JDOQLParameterDeclarationParser();
119     private String JavaDoc inputFilesPath;
120     private String JavaDoc generatedXmlsPath;
121     private File JavaDoc classout;
122     private MappingGenerator mappingGenerator = null;
123         
124     /**
125      * Flag set to <code>true</code> if code generation should proceed
126      * even if model validation fails
127      */

128     private static final boolean ignoreValidationResults = Deployer.getKeepFailedStubsValue();
129
130     /** String representing the signatures of generic code-gen files */
131     private static String JavaDoc signatures = null;
132
133     /**
134      * @see CMPGenerator#init(EjbBundleDescriptor, EjbcContext, String)
135      */

136     public void init(EjbBundleDescriptor bundle, EjbcContext ejbcContext,
137         String JavaDoc bundlePathName, String JavaDoc generatedXmlsPathName)
138         throws GeneratorException {
139
140         if (logger.isLoggable(Logger.FINE))
141             logger.fine("cmp gen init"); // NOI18N
142

143         this.ejbcContext = ejbcContext;
144         this.generatedXmlsPath = generatedXmlsPathName;
145         this.inputFilesPath = bundlePathName;
146         this.classout = ejbcContext.getStubsDir();
147
148         init(bundle, ejbcContext.getDescriptor().getClassLoader(),
149             bundlePathName, false);
150     }
151
152     /**
153      * @see CMPGenerator#init(EjbBundleDescriptor, ClassLoader, String)
154      *
155      * This method should be merged with {@link #init(EjbBundleDescriptor, EjbcContext, String)}
156      * when TestFramework is fixed for optional pm-descriptors and java2db support.
157      *
158      * @deprecated
159      */

160     public void init(EjbBundleDescriptor bundle, ClassLoader JavaDoc loader,
161         String JavaDoc bundlePathName) throws GeneratorException {
162
163         init(bundle, loader, bundlePathName, false);
164     }
165
166     /**
167      * Called by static verifier to bypass mapping validation or
168      * internally by other init() methods.
169      * Will force java2db generation if <code>ignoreSunDeploymentDescriptors</code>
170      * is <code>true</code>.
171      *
172      * @see CMPGenerator#init(EjbBundleDescriptor, ClassLoader, String)
173      */

174     public void init(EjbBundleDescriptor bundle, ClassLoader JavaDoc loader,
175             String JavaDoc bundlePathName, boolean ignoreSunDeploymentDescriptors)
176             throws GeneratorException {
177         if (logger.isLoggable(Logger.FINE))
178             logger.fine("cmp gen init"); // NOI18N
179

180         this.bundle = bundle;
181         this.loader = loader;
182
183         inputFilesPath = bundlePathName;
184
185         try {
186             nameMapper = new NameMapper(bundle);
187             model = new DeploymentDescriptorModel(nameMapper, loader);
188             mappingGenerator = new MappingGenerator(bundle, model, nameMapper, loader);
189             loadOrCreateMappingClasses(ignoreSunDeploymentDescriptors);
190
191             ejbModel = new EJBMetaDataModelImpl(model);
192
193         } catch (IOException JavaDoc e) {
194             // Problems storing properties file(s)
195
throw JDOCodeGeneratorHelper.createGeneratorException(
196                     "CMG.IOExceptionInInit", bundle, e); //NOI18N
197
}
198     }
199
200    /**
201     * @see CMPGenerator#validate(IASEjbCMPEntityDescriptor descr)
202     */

203     public Collection validate(IASEjbCMPEntityDescriptor descr) {
204
205         Collection c = new ArrayList();
206
207         c.addAll(validateModel(descr));
208
209         // only do EJBQL validation if the mapping info is present
210
if (getMappingMissingException(c) == null)
211             c.addAll(validateEJB(descr));
212
213         if (logger.isLoggable(Logger.FINE)) {
214             for (Iterator i = c.iterator(); i.hasNext();) {
215                 logger.log(Logger.FINE, "validation exception: ", //NOI18N
216
(Exception JavaDoc)i.next());
217             }
218         }
219
220         return c;
221     }
222
223     /**
224      * Validate the mapping file for the given class. First check if
225      * the mapping for the class exists in the sun-cmp-mappings. If so,
226      * continue to validate using {@link Model#validate(String, ClassLoader,
227      * ResourceBundle)}. If the resulting collection returned is not empty,
228      * it means it failed the test.
229      * The user should edit the mapping information, either in the
230      * IDE or the deploytool, or directly update
231      * the sun-cmp-mapping file.
232      *
233      * @param descr the IASEjbCMPEntityDescriptor for this CMP bean.
234      * @return a Collection of one GeneratorException if the mapping is
235      * totally missing or Collection of ModelException instances
236      * for each found validation error.
237      */

238     private Collection validateModel(IASEjbCMPEntityDescriptor descr) {
239         String JavaDoc beanName = descr.getName();
240         String JavaDoc className = nameMapper.getPersistenceClassForEjbName(beanName);
241
242         if (model.getPersistenceClass(className) == null) {
243            return Collections.singletonList(
244                JDOCodeGeneratorHelper.createGeneratorException(
245                "CMG.MissingBeanMapping", beanName, bundle)); //NOI18N
246
}
247
248         return model.validate(className, loader, validationBundle);
249     }
250
251     /**
252      * Checks a collection as returned by
253      * {@link #validateModel(IASEjbCMPEntityDescriptor)} to see if
254      * it contains (only) the {@link GeneratorException} used when the
255      * entire mapping definition is missing. In that case, we will
256      * want to skip other checks.
257      *
258      * @param c a collection of validation exceptions as returned by
259      * validateModel.
260      * @return if the collection contains exactly one GeneratorException
261      * return it, otherwise return <code>null</code>
262      */

263     private GeneratorException getMappingMissingException(Collection c) {
264         if (c.size() == 1) {
265             Object JavaDoc firstElement = c.iterator().next();
266
267             if (firstElement instanceof GeneratorException)
268                 return (GeneratorException)firstElement;
269         }
270
271         return null;
272     }
273
274     /**
275      * Validate the bean. For now, validate EJBQL for all finders and
276      * selectors of this bean.
277      *
278      * @param descr the IASEjbCMPEntityDescriptor for this CMP bean.
279      * @return a Collection of Exception instances for each found
280      * validation error.
281      */

282     private Collection validateEJB(IASEjbCMPEntityDescriptor descr) {
283         Collection c = null;
284         try {
285             JDOConcreteBeanGenerator cmpGenerator = getCMPGenerator(descr);
286             c = cmpGenerator.validate(new MethodHelper(descr), descr.getName());
287         } catch (GeneratorException e) {
288             c = new ArrayList();
289             c.add(e);
290         }
291
292         return c;
293     }
294
295     /**
296      * Validate if this bean is of a supported type.
297      *
298      * @param descr the IASEjbCMPEntityDescriptor for this CMP bean.
299      * @return a Collection of Exception instances for each found
300      * validation error.
301      */

302     private Collection validateSupported(IASEjbCMPEntityDescriptor descr) {
303         Collection rc = new ArrayList();
304         /*
305          * XXX Add validation of read-only configuration?
306          */

307
308         return rc;
309     }
310
311     /**
312      * @see CMPGenerator#generate(IASEjbCMPEntityDescriptor, File, File)
313      */

314     public void generate(IASEjbCMPEntityDescriptor ejbcmp, File JavaDoc srcout,
315         File JavaDoc classout)
316         throws GeneratorException {
317
318         String JavaDoc beanName = ejbcmp.getName();
319
320         // StringBuffer to store validation exception messages if there are any.
321
// If there are no validation exceptions, the reference will be null.
322
StringBuffer JavaDoc validateex = null;
323     
324         boolean debug = logger.isLoggable(Logger.FINE);
325         if (debug)
326             logger.fine("gen file in " + srcout.getAbsolutePath()); // NOI18N
327

328         // We need to create a new ArrayList because model validation
329
// returns an unmodifiable list. This may be a place to look
330
// for a performance improvement later for the case of empty
331
// or singleton collection (extra copies).
332
Collection c = new ArrayList(validateModel(ejbcmp));
333
334         // if the mapping info is not present, throw the exception and
335
// stop the generation process
336
GeneratorException mappingMissingEx = getMappingMissingException(c);
337         if (mappingMissingEx != null)
338             throw mappingMissingEx;
339
340         c.addAll(validateSupported(ejbcmp));
341
342         JDOConcreteBeanGenerator cmpGenerator = getCMPGenerator(ejbcmp);
343         MethodHelper mh = new MethodHelper(ejbcmp);
344         c.addAll(cmpGenerator.validate(mh, beanName));
345
346         if (!c.isEmpty()) {
347             // Validation failed the test. We will try to display all the
348
// exceptions in a concatenated message and a GeneratorException
349
// is thrown.
350
validateex = new StringBuffer JavaDoc();
351             Iterator iter = c.iterator();
352     
353             while (iter.hasNext()) {
354                 Exception JavaDoc ex = (Exception JavaDoc)iter.next();
355                 if (debug)
356                     logger.log(Logger.FINE,"validation exception: " , ex); //NOI18N
357
validateex.append(ex.getMessage()).append('\n'); //NOI18N
358
}
359     
360             if (!ignoreValidationResults)
361                 throw JDOCodeGeneratorHelper.createGeneratorException(
362                         "CMG.ExceptionInValidate", //NOI18N
363
beanName, bundle, validateex.toString());
364         }
365
366         try {
367             Collection newfiles = null;
368     
369             if (!ejbcmp.isEJB20())
370                 ejbcmp.setQueryParser(jdoqlParamDeclParser);
371     
372             // IMPORTANT:
373
// Concrete impl class generation must happen before generation of
374
// PC class as cmpGenerator will override cascadeDelete (DeleteAction)
375
// property if it is set, and generatePC() saves .mapping file.
376
newfiles = cmpGenerator.generate(mh, beanName, srcout, classout);
377             files.addAll(newfiles);
378
379             newfiles = generatePC(ejbcmp, srcout, classout);
380             files.addAll(newfiles);
381
382             if (validateex != null)
383                 throw JDOCodeGeneratorHelper.createGeneratorException(
384                         "CMG.ExceptionInValidate", //NOI18N
385
beanName, bundle, validateex.toString());
386         } catch (JDOUserException e) {
387             // User error found. Append this exception's message to validation
388
// messages if there are any.
389
throw JDOCodeGeneratorHelper.createGeneratorException(
390                     "CMG.ExceptionInGenerate", //NOI18N
391
beanName, bundle, e, validateex);
392
393         } catch (EJBQLException e) {
394             // EJBQL parsing error found. Append this exception's message to
395
// validation messages if there are any.
396
throw JDOCodeGeneratorHelper.createGeneratorException(
397                     "CMG.ExceptionInGenerate", //NOI18N
398
beanName, bundle, e, validateex);
399
400         } catch (IOException JavaDoc e) {
401             // Problems generating file(s). Append this exception's message to
402
// validation messages if there are any.
403
throw JDOCodeGeneratorHelper.createGeneratorException(
404                     "CMG.IOExceptionInGenerate", //NOI18N
405
beanName, bundle, e, validateex);
406         }
407
408     }
409
410     /** Generate PC class for the ConcreteImpl bean.
411      * @see CMPGenerator#generate(IASEjbCMPEntityDescriptor, File, File)
412      */

413     private Collection generatePC(IASEjbCMPEntityDescriptor ejbcmp,
414         File JavaDoc srcout, File JavaDoc classout)
415         throws IOException JavaDoc {
416
417         ArrayList fileList = new ArrayList();
418         Main gen = new Main(ejbModel, srcout);
419         String JavaDoc className = nameMapper.getPersistenceClassForEjbName(ejbcmp.getName());
420
421         if (className != null) {
422             // generate PC class
423
//@olsen, 4653156: the enhancer-generator deals with class names
424
// in JVM format, i.e., with '/' for '.' as separator
425
String JavaDoc jvmClassName = className.replace('.', '/');
426             File JavaDoc file = gen.generate(jvmClassName);
427             fileList.add(file);
428
429             // write mapping file
430
MappingClassElement mappingClass
431                 = model.getMappingClass(className);
432             BufferedOutputStream JavaDoc mapOut = null;
433             try {
434                 String JavaDoc mapPath = className.replace('.', File.separatorChar);
435                 String JavaDoc mappingFile = mapPath + MAPPING_EXTENSION;
436                 mapOut = new BufferedOutputStream JavaDoc(
437                     new FileOutputStream JavaDoc(new File JavaDoc(classout, mappingFile)));
438                 //"touch" need to create the output stream first since the
439
//classout directory is not in the classpath and
440
//therefore the standard storeMappingClass can't be used
441
model.storeMappingClass(mappingClass, mapOut);
442             } finally {
443                 if (mapOut != null) {
444                     try {
445                         mapOut.close();
446                     } catch(Exception JavaDoc ex) {
447                         if (logger.isLoggable(Logger.FINE))
448                             logger.fine(ex.getMessage());
449                     }
450                 }
451             }
452             
453         }
454         return fileList;
455     }
456
457    /*
458     * @see CMPGenerator#cleanup()
459     */

460     public Collection cleanup() throws GeneratorException {
461         // Remove the strong references to MappingClassElements
462
// needed during deployment. The mapping class cache
463
// can now be cleaned up by the garbage collector.
464
// It is done by mappingGenerator.
465
mappingGenerator.cleanup();
466
467         // Reset cmp generators.
468
cmp11Generator = null;
469         cmp20Generator = null;
470
471         return files;
472     }
473
474     /** Returns CMP bean classes generator of the appropriate type.
475      * @param descr the bean descriptor as IASEjbCMPEntityDescriptor.
476      * @return instance of JDOConcreteBeanGenerator.
477      */

478     private JDOConcreteBeanGenerator getCMPGenerator(
479             IASEjbCMPEntityDescriptor descr) throws GeneratorException {
480
481         JDOConcreteBeanGenerator cmpGenerator = null;
482         try {
483             if (descr.isEJB20()) {
484                 cmpGenerator = getCMP20Generator();
485             } else {
486                 cmpGenerator = getCMP11Generator();
487             }
488
489             cmpGenerator.setUpdateable(
490                     !descr.getIASEjbExtraDescriptors().isIsReadOnlyBean());
491
492         } catch (IOException JavaDoc e) {
493             // Problems reading file(s)
494
throw JDOCodeGeneratorHelper.createGeneratorException(
495                     "CMG.IOExceptionInInit", bundle, e); //NOI18N
496
}
497
498         return cmpGenerator;
499     }
500
501    /**
502      * Returns instance of generator for CMP2.x beans in this module.
503      */

504     private JDOConcreteBeanGenerator getCMP20Generator() throws IOException JavaDoc {
505         if (cmp20Generator == null) {
506             cmp20Generator = new JDOConcreteBean20Generator(loader, model,
507                     nameMapper);
508
509             addSignatures(cmp20Generator);
510         }
511
512         return cmp20Generator;
513     }
514
515     /**
516      * Returns instance of generator for CMP1.1 beans in this module.
517      */

518     private JDOConcreteBeanGenerator getCMP11Generator() throws IOException JavaDoc {
519         if (cmp11Generator == null) {
520             cmp11Generator = new JDOConcreteBean11Generator(loader, model,
521                     nameMapper);
522
523             addSignatures(cmp11Generator);
524         }
525
526         return cmp11Generator;
527     }
528
529     /**
530      * Add required signatures to the generator instance.
531      */

532     private void addSignatures(JDOConcreteBeanGenerator cmpGenerator)
533             throws IOException JavaDoc {
534
535         // Add the code generation signature of the input files
536
// Note, this is per bundle, so it needs to be set per
537
// cmpGenerator instance.
538
cmpGenerator.addCodeGenInputFilesSignature(getSignaturesOfInputFiles());
539     
540         // Add the code generation signature of the S1AS-specific generator classes.
541
cmpGenerator.addCodeGeneratorClassSignature(
542                 getS1ASSpecificGeneratorClassesSignature());
543     }
544
545     /**
546      * Returns the signatures of the classes and properties which are
547      * involved in the codegen for S1AS specific part.
548      * @return The signatures as a string.
549      */

550     private static synchronized String JavaDoc
551             getS1ASSpecificGeneratorClassesSignature()
552     {
553         if (signatures == null) {
554             StringBuffer JavaDoc sb = new StringBuffer JavaDoc().
555         
556             // adding signature of JDOCodeGenerator
557
append(JDOCodeGenerator.SIGNATURE).
558             append(CMPTemplateFormatter.signatureDelimiter_).
559         
560             // adding signature of NameMapper
561
append(NameMapper.SIGNATURE);
562         
563             signatures = sb.toString();
564         }
565         return signatures;
566     }
567
568     /**
569      * Returns the signatures (file length) of the input files for the codegen.
570      * Inputfiles are ejb-jar.xml, sun-ejb-jar.xml, sun-cmp-mappings.xml.
571      * @return The signatures as a string.
572      * @throws IOException
573      */

574     private String JavaDoc getSignaturesOfInputFiles() throws IOException JavaDoc
575     {
576         StringBuffer JavaDoc sb = new StringBuffer JavaDoc().
577                        
578             append(getFileInfoOfInputFile(inputFilesPath +
579                 File.separator + DescriptorConstants.EJB_JAR_ENTRY)).
580             append(CMPTemplateFormatter.signatureDelimiter_).
581                
582             append(getFileInfoOfInputFile(inputFilesPath +
583                 File.separator + DescriptorConstants.S1AS_EJB_JAR_ENTRY)).
584             append(CMPTemplateFormatter.signatureDelimiter_).
585
586             append(getFileInfoOfInputFile(inputFilesPath +
587                 File.separator + DescriptorConstants.S1AS_CMP_MAPPING_JAR_ENTRY));
588                
589         return sb.toString();
590     }
591
592     /**
593      * Returns a string consisting of the fully path and name of the input file
594      * and its length in bytes.
595      * @param pathname The path and file name of the input file.
596      * @return A string consisting of the fully path and name of the input file
597      * and its length in bytes.
598      * @throws IOException
599      */

600     private String JavaDoc getFileInfoOfInputFile(String JavaDoc pathname) throws IOException JavaDoc
601     {
602         File JavaDoc inputFile = new File JavaDoc(pathname);
603         
604         StringBuffer JavaDoc inputFileInfo = new StringBuffer JavaDoc().
605             append(inputFile.getCanonicalPath().replace('\\', '/')).
606             append(CMPTemplateFormatter.space_).
607             append(String.valueOf(inputFile.length())).
608             append(" bytes");
609
610         return inputFileInfo.toString();
611     }
612
613     /**
614      * It will load mapping classes if there is sun-cmp-mappings.xml,
615      * otherwise it will call database generation backend to create
616      * mapping classes and schema.
617      * Generates *.dbschema and sun-cmp-mappings.xml in application dir if it is
618      * in creating mapping classes mode
619      *
620      * @param ignoreSunDeploymentDescriptors Will force java2db generation
621      * if <code>true</code>.
622      */

623     private void loadOrCreateMappingClasses(boolean ignoreSunDeploymentDescriptors)
624         throws IOException JavaDoc, GeneratorException {
625
626         try {
627             SchemaElement schema = mappingGenerator.generateMapping(
628                     ejbcContext, inputFilesPath, generatedXmlsPath, classout,
629                     ignoreSunDeploymentDescriptors);
630             // If this is from verify, do not create DDL.
631
if (ejbcContext != null
632                     && mappingGenerator.isJavaToDatabase()) {
633                 createDDLs(schema, mappingGenerator.getDatabaseVendorName(), null);
634             }
635         } catch (SQLException JavaDoc ex) {
636             // Problems talking to the database.
637
throw JDOCodeGeneratorHelper.createGeneratorException(
638                     "CMG.SQLException", bundle, ex);
639         } catch (DBException ex) {
640             // Problems reading or creating DBModel.
641
throw JDOCodeGeneratorHelper.createGeneratorException(
642                     "CMG.DBException", bundle, ex); //NOI18N
643

644         } catch (ModelException ex) {
645             // Problems reading or creating model.
646
throw JDOCodeGeneratorHelper.createGeneratorException(
647                     "CMG.ModelException", bundle, ex); //NOI18N
648

649         } catch (Schema2BeansException ex) {
650             // Problems reading or creating sun-cmp-mapping.xml
651
throw JDOCodeGeneratorHelper.createGeneratorException(
652                     "CMG.Schema2BeansException", bundle, ex); //NOI18N
653
} catch (ConversionException ex) {
654             // Problems converting between sun-cmp-mappings and mapping model
655
throw JDOCodeGeneratorHelper.createGeneratorException(
656                     "CMG.MappingConversionException", bundle, ex); //NOI18N
657
}
658     }
659
660     /**
661      * Generates DDLs for specified database vendor name.
662      * @param schema a schema representing database in memory
663      * @param dbVendorName a string for database vendor name
664      * @param conn a database connection
665      * @throws IOException
666      * @throws DBException
667      */

668     private void createDDLs(SchemaElement schema, String JavaDoc dbVendorName, Connection JavaDoc conn)
669             throws IOException JavaDoc, DBException {
670
671         // Make sure that generatedXmlsPath directory is created
672
// before writing *.sql files to this location.
673
File JavaDoc fileDir = new File JavaDoc(generatedXmlsPath);
674
675         if (!fileDir.exists()) {
676             fileDir.mkdirs();
677         }
678
679         // Can't use schema name as at the time of the event listener
680
// processing, the name will be recalculated again, and it might
681
// not match.
682
String JavaDoc namePrefix = DeploymentHelper.getDDLNamePrefix(bundle);
683
684         // sql generation file names.
685
OutputStream JavaDoc createDDLSql = new FileOutputStream JavaDoc(new File JavaDoc(generatedXmlsPath,
686                 namePrefix + NAME_SEPARATOR + dbVendorName + CREATE_SQL_FILE_SUFFIX));
687         OutputStream JavaDoc dropDDLSql = new FileOutputStream JavaDoc(new File JavaDoc(generatedXmlsPath,
688                 namePrefix + NAME_SEPARATOR + dbVendorName + DROP_SQL_FILE_SUFFIX));
689
690         OutputStream JavaDoc dropDDLTxt = new FileOutputStream JavaDoc(new File JavaDoc(classout,
691                 namePrefix + DROP_DDL_JDBC_FILE_SUFFIX));
692         OutputStream JavaDoc createDDLTxt = new FileOutputStream JavaDoc(new File JavaDoc(classout,
693                 namePrefix + CREATE_DDL_JDBC_FILE_SUFFIX));
694
695         try {
696             // XXX This code might be used in the future with the create
697
// and drop flags to be set appropriately.
698
// If we have a live connection, we'll need to add flags that
699
// specify if it's necessary to create and drop tables at deploy.
700
// For now it's never executed so we set those booleans to false.
701
OutputStream JavaDoc dbStream = null;
702             boolean createTablesAtDeploy = false;
703             boolean dropTablesAtDeploy = false;
704             if ((conn != null) && (createTablesAtDeploy || dropTablesAtDeploy)) {
705                 dbStream = new DatabaseOutputStream(conn);
706             }
707             // XXX This is the end of the code that might be used in the future.
708

709             DDLGenerator.generateDDL(schema, dbVendorName, createDDLSql,
710                 dropDDLSql, dropDDLTxt, createDDLTxt, dbStream, dropTablesAtDeploy);
711         } catch (SQLException JavaDoc ex) {
712             if (logger.isLoggable(Logger.WARNING))
713                 logger.warning(ex.toString());
714         }
715     }
716
717 }
718
Popular Tags