Search in sources :

Example 1 with SchemaElement

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

the class MappingGenerator method generateMapping.

/**
 * This method will load mapping classes if there is sun-cmp-mappings.xml,
 * otherwise it will call the database generation backend to create
 * mapping classes and schema.  It also generates *.dbschema and
 * sun-cmp-mappings.xml in application dir if it is
 * in creating mapping classes mode.
 * @param ctx an object containing CLI options for
 * the database generation backend
 * @param inputFilesPath the directory where sun-cmp-mappings.xml is located
 * @param generatedXmlsPath the directory where the generated files are located
 * @param classout the directory where the classes are located
 * @param ignoreSunDeploymentDescriptors use java2db generation if set to <code>true</code>.
 * @return a SchemaElement for mapping classes mapped to
 * @throws IOException
 * @throws DBException
 * @throws ModelException
 * @throws Schema2BeansException
 * @throws SQLException
 * @throws GeneratorException
 * @throws ConversionException
 */
public SchemaElement generateMapping(DeploymentContext ctx, String inputFilesPath, String generatedXmlsPath, File classout, boolean ignoreSunDeploymentDescriptors) throws IOException, DBException, ModelException, Schema2BeansException, SQLException, GeneratorException, ConversionException {
    SchemaElement schema = null;
    if (ctx == null)
        isVerifyFlag = true;
    File cmpMappingFile = getSunCmpMappingFile(inputFilesPath);
    boolean mappedBeans = !ignoreSunDeploymentDescriptors && cmpMappingFile.exists();
    ResourceReferenceDescriptor cmpResource = checkOrCreateCMPResource(mappedBeans);
    // Remember whether or not this mapping was created by Java2DB.
    isJavaToDatabaseFlag = DeploymentHelper.isJavaToDatabase(cmpResource.getSchemaGeneratorProperties());
    // We *must* get a vendor name if either the beans are not mapped, or
    // they are mapped and the javaToDatabase flag is set.
    boolean mustHaveDBVendorName = !mappedBeans || (mappedBeans && isJavaToDatabaseFlag);
    // Read deployment settings from the deployment descriptor
    // and CLI options.
    Results deploymentArguments = getDeploymentArguments(ctx, cmpResource, mustHaveDBVendorName);
    dbVendorName = deploymentArguments.getDatabaseVendorName();
    if (mappedBeans) {
        // If it is from verify, skip deployment arguments check.
        if (!isVerifyFlag) {
            // Warning for user, if required.
            String warning = null;
            if (isJavaToDatabaseFlag) {
                // as per the mapping.
                if (deploymentArguments.hasUniqueTableNames()) {
                    warning = I18NHelper.getMessage(messages, // NOI18N
                    "EXC_DisallowJava2DBUniqueTableNames", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle));
                    logger.warning(warning);
                }
            } else if (deploymentArguments.hasJavaToDatabaseArgs()) {
                // If beans are already mapped but the user gave any Java2DB
                // command line arguments, warn the user that these args
                // should not be used when module is already mapped.
                warning = I18NHelper.getMessage(messages, // NOI18N
                "EXC_DisallowJava2DBCLIOverrides", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle));
                logger.warning(warning);
            }
            if (warning != null) {
                ActionReport subActionReport = ctx.getActionReport().addSubActionsReport();
                // Propagte warning to client side so that the deployer can see the warning.
                Java2DBProcessorHelper.warnUser(subActionReport, warning);
            }
        }
        // Sun-cmp-mapping.xml exists, use normal MappingClass loading
        SunCmpMappings sunCmpMappings = getSunCmpMappings(cmpMappingFile);
        // Ensure that there is a dbschema for each element of
        // sunCmpMappings.
        ensureDBSchemaExistence(cmpResource, sunCmpMappings, inputFilesPath, classout);
        // load real mapping model and jdo model in memory
        Map mappingClasses = loadMappingClasses(sunCmpMappings, getClassLoader());
        // Get schema from one of the mapping classes.
        // The mapping class element may be null if there is inconsistency
        // in sun-cmp-mappings.xml and ejb-jar.xml. For example,
        // the bean has mapping information in sun-cmp-mappings.xml but
        // no definition in the ejb-jar.xml.
        // So iterate over the mappings until the 1st non-null is found.
        MappingClassElement mc = null;
        Iterator iter = mappingClasses.values().iterator();
        while (iter.hasNext()) {
            mc = (MappingClassElement) iter.next();
            if (mc != null) {
                schema = SchemaElement.forName(mc.getDatabaseRoot());
                break;
            }
        }
        if (logger.isLoggable(Logger.FINE)) {
            logger.fine(// NOI18N
            "Loaded mapped beans for " + cmpResource.getJndiName() + ", isJavaToDatabase=" + // NOI18N
            isJavaToDatabaseFlag);
        }
    } else {
        // Generate mapping file and dbschema, since either
        // sun-cmp-mappings.xml does not exist (e.g. user didn't yet map)
        // or DeploymentContext is null (e.g. running under auspices of AVK).
        DatabaseGenerator.Results results = generateMappingClasses(dbVendorName, deploymentArguments.getUseUniqueTableNames(), deploymentArguments.getUserPolicy(), inputFilesPath);
        // java2db from verifier should not save anything to disk
        if (!isVerifyFlag) {
            // save SunCmpMapping to sun-cmp-mappings.xml
            // in generated XML dir
            writeSunCmpMappingFile(results.getMappingClasses(), getSunCmpMappingFile(generatedXmlsPath));
            schema = results.getSchema();
            // save schema to dbschema file in generated XML dir
            writeSchemaFile(schema, classout);
            setJavaToDatabase(cmpResource, true);
        }
    }
    return schema;
}
Also used : MappingClassElement(com.sun.jdo.api.persistence.model.mapping.MappingClassElement) ActionReport(org.glassfish.api.ActionReport) DatabaseGenerator(com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator) Iterator(java.util.Iterator) SchemaElement(org.netbeans.modules.dbschema.SchemaElement) ResourceReferenceDescriptor(com.sun.enterprise.deployment.ResourceReferenceDescriptor) MappingFile(com.sun.jdo.api.persistence.mapping.ejb.MappingFile) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) SunCmpMappings(com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMappings)

Example 2 with SchemaElement

use of org.netbeans.modules.dbschema.SchemaElement 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)

Aggregations

MappingFile (com.sun.jdo.api.persistence.mapping.ejb.MappingFile)2 File (java.io.File)2 SchemaElement (org.netbeans.modules.dbschema.SchemaElement)2 ResourceReferenceDescriptor (com.sun.enterprise.deployment.ResourceReferenceDescriptor)1 SunCmpMapping (com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMapping)1 SunCmpMappings (com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMappings)1 MappingClassElement (com.sun.jdo.api.persistence.model.mapping.MappingClassElement)1 DatabaseGenerator (com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator)1 GeneratorException (com.sun.jdo.spi.persistence.support.ejb.codegen.GeneratorException)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 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Set (java.util.Set)1