Search in sources :

Example 1 with SchemaElementImpl

use of org.netbeans.modules.dbschema.jdbcimpl.SchemaElementImpl in project Payara by payara.

the class MappingGenerator method ensureDBSchemaExistence.

/**
 * Check that there is a dbschema for each element of the SunCmpMappings.
 * For those which are missing, create a corresponding .dbschema file.
 * @param cmpResource Provides JNDI name for getting database connection
 * @param sunCmpMappings SunCmpMappings which is checked for having schema
 * @param inputFilesPath the directory where this bundle's files are located
 * @param classout the directory where the classes are located
 * @exception DBException Thrown if database model throws it
 * @exception IOException Thrown if .dbschema file cannot be created.
 * @exception SQLException Thrown if we cannot get get required info from
 * the database.
 */
private void ensureDBSchemaExistence(ResourceReferenceDescriptor cmpResource, SunCmpMappings sunCmpMappings, String inputFilesPath, File classout) throws DBException, SQLException, GeneratorException {
    String generatedSchemaName = getInfoHelper().getSchemaNameToGenerate();
    Set tables = new HashSet();
    int size = sunCmpMappings.sizeSunCmpMapping();
    // and save it.
    for (int i = 0; i < size; i++) {
        SunCmpMapping sunCmpMapping = sunCmpMappings.getSunCmpMapping(i);
        String schemaName = sunCmpMapping.getSchema();
        if (StringHelper.isEmpty(schemaName)) {
            if (!isVerifyFlag) {
                // The tables in this section need to be captured.
                addAllTables(sunCmpMapping, tables);
                sunCmpMapping.setSchema(generatedSchemaName);
            } else {
                // If it is from verifier, capture schema internally
                // to perform sun-cmp-mappings.xml and EJB validation
                getConversionHelper().setEnsureValidation(false);
            }
        } else {
            File dbschemaFile = new File(new StringBuffer(inputFilesPath).append(File.separator).append(schemaName).append(DBSCHEMA_EXTENSION).toString());
            if (!(dbschemaFile.exists() && dbschemaFile.isFile() && dbschemaFile.canRead())) {
                throw new GeneratorException(I18NHelper.getMessage(// NOI18N
                messages, // NOI18N
                "CMG.MissingDBSchema", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle), schemaName));
            }
        }
    }
    // Now we need to go and capture those tables.
    if (tables.size() > 0) {
        String userSchema = null;
        Connection con = DeploymentHelper.getConnection(cmpResource.getJndiName());
        DatabaseMetaData dmd = con.getMetaData();
        if (DBVendorTypeHelper.requireUpperCaseSchema(dmd)) {
            userSchema = dmd.getUserName().trim().toUpperCase();
        }
        ConnectionProvider cp = new ConnectionProvider(con, dmd.getDriverName().trim());
        if (userSchema != null) {
            cp.setSchema(userSchema);
        }
        OutputStream outstream = null;
        try {
            SchemaElementImpl outSchemaImpl = new SchemaElementImpl(cp);
            SchemaElement schemaElement = new SchemaElement(outSchemaImpl);
            schemaElement.setName(DBIdentifier.create(generatedSchemaName));
            if (dmd.getDatabaseProductName().compareToIgnoreCase("MYSQL") == 0)
                outSchemaImpl.initTables(cp, new LinkedList(tables), new LinkedList(), true);
            else
                outSchemaImpl.initTables(cp, new LinkedList(tables), new LinkedList(), false);
            outstream = new FileOutputStream(new File(classout, new StringBuffer(generatedSchemaName).append(DBSCHEMA_EXTENSION).toString()));
            // XXX Unfortunately, if SchemaElement.save gets an
            // IOException, it prints the stack trace but does not
            // let us handle it :-(
            schemaElement.save(outstream);
        } catch (IOException ex) {
            // Catch FileNotFound, etc.
            throw JDOCodeGeneratorHelper.createGeneratorException("CMG.CannotSaveDBSchema", bundle, // NOI18N
            ex);
        } finally {
            cp.closeConnection();
            try {
                if (outstream != null) {
                    outstream.close();
                }
            } catch (IOException ex) {
                if (logger.isLoggable(Logger.FINE))
                    logger.fine(ex.toString());
            }
        }
    }
}
Also used : SunCmpMapping(com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMapping) Set(java.util.Set) HashSet(java.util.HashSet) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Connection(java.sql.Connection) IOException(java.io.IOException) DatabaseMetaData(java.sql.DatabaseMetaData) LinkedList(java.util.LinkedList) ConnectionProvider(org.netbeans.modules.dbschema.jdbcimpl.ConnectionProvider) SchemaElementImpl(org.netbeans.modules.dbschema.jdbcimpl.SchemaElementImpl) FileOutputStream(java.io.FileOutputStream) SchemaElement(org.netbeans.modules.dbschema.SchemaElement) GeneratorException(com.sun.jdo.spi.persistence.support.ejb.codegen.GeneratorException) MappingFile(com.sun.jdo.api.persistence.mapping.ejb.MappingFile) File(java.io.File) HashSet(java.util.HashSet)

Example 2 with SchemaElementImpl

use of org.netbeans.modules.dbschema.jdbcimpl.SchemaElementImpl in project Payara by payara.

the class MappingGenerator method generateMappingClasses.

/**
 * Create mapping classes and schema based on database vendor name.
 * @param dbName a string for database vendor name
 * @param uniqueTableNames a Boolean to determin if use unique table names
 * during database generation
 * @param userPolicy a property object holding user overrides
 * @param inputFilesPath a directory where sun-cmp-mappings.xml is located
 * @throws IOException
 * @throws Schema2BeansException
 * @throws ModelException
 * @throws DBException
 * @throws ConversionException
 */
public DatabaseGenerator.Results generateMappingClasses(String dbName, Boolean uniqueTableNames, Properties userPolicy, String inputFilesPath) throws IOException, Schema2BeansException, ModelException, DBException, ConversionException {
    // generate mapping classes and dbschema in memory
    SunCmpMappings sunCmpMappings = null;
    // sun-cmp-mappings.xml does not exist, use DatabaseGenerator
    // to generate sun-cmp-mappings.xml, *.dbschema
    List pcClasses = new ArrayList();
    sunCmpMappings = getPartialSunCmpMappings(pcClasses, (uniqueTableNames != null) ? uniqueTableNames.booleanValue() : false);
    // load real jdo model and fake mapping model in memory
    ddHelper.setEnsureValidation(false);
    // create fake schema for partial mapping
    SchemaElement fakeSchema = new SchemaElement(new SchemaElementImpl());
    fakeSchema.setName(DBIdentifier.create(FAKE_NAME));
    // add newly created fake schema to SchemaElement cache
    SchemaElement.addToCache(fakeSchema);
    // pass null as class loader in order for MappingFile to load schema
    // from cache not from disk.
    loadMappingClasses(sunCmpMappings, null);
    DatabaseGenerator.Results results = generateSchema(pcClasses, dbName, uniqueTableNames, userPolicy);
    SchemaElement schema = results.getSchema();
    Set mappingClasses = results.getMappingClasses();
    // remove fake schema from cache since the correct schema is generated.
    SchemaElement.removeFromCache(FAKE_NAME);
    // clean up old version of schema in SchemaElement cache
    // if there is one
    SchemaElement.removeFromCache(schema.getName().getName());
    // add newly created schema to SchemaElement cache
    SchemaElement.addToCache(schema);
    // update mapping classes
    updateMappingClasses(mappingClasses);
    // model before returning the result.
    if (skipGeneratedFields) {
        Iterator iter = mappingClasses.iterator();
        while (iter.hasNext()) {
            MappingClassElement mapClassElt = (MappingClassElement) iter.next();
            if (mapClassElt != null) {
                String className = mapClassElt.getName();
                String ejbName = nameMapper.getEjbNameForPersistenceClass(className);
                PersistenceClassElement pce = (PersistenceClassElement) model.getPersistenceClass(className);
                PersistenceFieldElement[] allFields = pce.getFields();
                if (allFields != null) {
                    List generatedFieldList = new ArrayList();
                    // the generated fields from the model.
                    for (int i = 0; i < allFields.length; i++) {
                        PersistenceFieldElement pfe = allFields[i];
                        if (pfe != null) {
                            String pFieldName = pfe.getName();
                            String ejbFieldName = nameMapper.getEjbFieldForPersistenceField(className, pFieldName);
                            if (nameMapper.isGeneratedField(ejbName, ejbFieldName)) {
                                generatedFieldList.add(pfe);
                            }
                        }
                    }
                    // If the field is a version field, don't remove it
                    // from the model even though it is generated because
                    // it is needed to hold the version column information.
                    Iterator iterator = generatedFieldList.iterator();
                    while (iterator.hasNext()) {
                        PersistenceFieldElement pfe = (PersistenceFieldElement) iterator.next();
                        MappingFieldElement mfe = mapClassElt.getField(pfe.getName());
                        if (mfe != null && (!mfe.isVersion())) {
                            model.removeFieldElement(pfe);
                            mapClassElt.removeField(mfe);
                        }
                    }
                }
            }
        }
    }
    return results;
}
Also used : MappingFieldElement(com.sun.jdo.api.persistence.model.mapping.MappingFieldElement) PersistenceFieldElement(com.sun.jdo.api.persistence.model.jdo.PersistenceFieldElement) MappingClassElement(com.sun.jdo.api.persistence.model.mapping.MappingClassElement) DatabaseGenerator(com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator) PersistenceClassElement(com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement) SchemaElementImpl(org.netbeans.modules.dbschema.jdbcimpl.SchemaElementImpl)

Aggregations

SchemaElementImpl (org.netbeans.modules.dbschema.jdbcimpl.SchemaElementImpl)2 MappingFile (com.sun.jdo.api.persistence.mapping.ejb.MappingFile)1 SunCmpMapping (com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMapping)1 PersistenceClassElement (com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement)1 PersistenceFieldElement (com.sun.jdo.api.persistence.model.jdo.PersistenceFieldElement)1 MappingClassElement (com.sun.jdo.api.persistence.model.mapping.MappingClassElement)1 MappingFieldElement (com.sun.jdo.api.persistence.model.mapping.MappingFieldElement)1 DatabaseGenerator (com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator)1 GeneratorException (com.sun.jdo.spi.persistence.support.ejb.codegen.GeneratorException)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 Connection (java.sql.Connection)1 DatabaseMetaData (java.sql.DatabaseMetaData)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 Set (java.util.Set)1 SchemaElement (org.netbeans.modules.dbschema.SchemaElement)1 ConnectionProvider (org.netbeans.modules.dbschema.jdbcimpl.ConnectionProvider)1