Search in sources :

Example 1 with MappingClassElement

use of com.sun.jdo.api.persistence.model.mapping.MappingClassElement in project Payara by payara.

the class MappingGenerator method writeSunCmpMappingFile.

/**
 * Writes to sun-cmp-mappings.xml from mappings classes
 * @param mappingClasses a set of mapping classes
 * @param cmpMappingFile corresponds to sun-cmp-mappings.xml
 * @throws IOException
 * @throws ConversionException
 * @throws Schema2BeansException
 */
private void writeSunCmpMappingFile(Set mappingClasses, File cmpMappingFile) throws IOException, ConversionException, Schema2BeansException {
    // Construct the input to MappingFile.fromMappingClasses(): a Map
    // object containing ejbName and MappingClassElement.  Use the
    // elements of iteration and NameMapper to create the input for
    // MappingFile.
    Map mappingMap = new HashMap();
    AbstractNameMapper nameMapper = getNameMapper();
    Iterator iter = mappingClasses.iterator();
    while (iter.hasNext()) {
        MappingClassElement mappingClass = (MappingClassElement) iter.next();
        String ejbName = nameMapper.getEjbNameForPersistenceClass(mappingClass.getName());
        mappingMap.put(ejbName, mappingClass);
    }
    MappingFile mf = new MappingFile();
    OutputStream sunCmpMapping = null;
    try {
        sunCmpMapping = new FileOutputStream(cmpMappingFile);
        mf.fromMappingClasses(sunCmpMapping, mappingMap, getConversionHelper());
    } catch (IOException ex) {
        throw ex;
    } finally {
        try {
            if (sunCmpMapping != null) {
                sunCmpMapping.close();
            }
        } catch (IOException ex) {
            if (logger.isLoggable(Logger.FINE))
                logger.fine(ex.toString());
        }
    }
}
Also used : HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) AbstractNameMapper(com.sun.jdo.api.persistence.mapping.ejb.AbstractNameMapper) Iterator(java.util.Iterator) MappingFile(com.sun.jdo.api.persistence.mapping.ejb.MappingFile) MappingClassElement(com.sun.jdo.api.persistence.model.mapping.MappingClassElement) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with MappingClassElement

use of com.sun.jdo.api.persistence.model.mapping.MappingClassElement 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 3 with MappingClassElement

use of com.sun.jdo.api.persistence.model.mapping.MappingClassElement in project Payara by payara.

the class DatabaseGenerator method generate.

/**
 * Generate database schema and mapping classes.  Iterate over all
 * persistence-capable classes, generating a table for each.  Within each
 * persistence-capable class, iterate over all fields and make columns
 * for each.  Then handle relationships separately, see {@link
 * #addRelationships}.
 * @return A DatabaseGenerator.Results instance which holds the results
 * of generation.
 */
private Results generate() throws DBException, ModelException {
    for (Iterator i = pcClasses.iterator(); i.hasNext(); ) {
        NameTuple nameTuple = (NameTuple) i.next();
        String pcClassName = nameTuple.getPersistenceClassName();
        String desiredTableName = nameTuple.getDesiredTableName();
        PersistenceClassElement pcClass = model.getPersistenceClass(pcClassName);
        String tableName = mappingPolicy.getTableName(desiredTableName, getShortClassName(nameTuple.getHashClassName()));
        TableElement table = DBElementFactory.createAndAttachTable(schema, tableName);
        UniqueKeyElement pKey = DBElementFactory.createAndAttachPrimaryKey(table, mappingPolicy.getPrimaryKeyConstraintName(table.getName().getName()));
        MappingClassElement mappingClass = createMappingClass(pcClass, table);
        PersistenceFieldElement[] fields = pcClass.getFields();
        if (fields != null) {
            for (int j = 0; j < fields.length; j++) {
                PersistenceFieldElement field = fields[j];
                String fieldName = field.getName();
                if (!(field instanceof RelationshipElement)) {
                    String columnName = mappingPolicy.getColumnName(desiredTableName, fieldName, tableName);
                    String fieldType = model.getFieldType(pcClassName, fieldName);
                    String fullFieldName = new StringBuilder(desiredTableName).append(DOT).append(fieldName).toString();
                    JDBCInfo columnType = DBElementFactory.getColumnType(fullFieldName, fieldType, mappingPolicy);
                    if (logger.isLoggable(Logger.FINEST)) {
                        logger.fine(// NOI18N
                        "DBGenerator.generate: " + tableName + "." + columnName + // NOI18N
                        ": " + columnType.toString());
                    }
                    ColumnElement column = DBElementFactory.createAndAttachColumn(columnName, table, columnType);
                    MappingFieldElement mappingField = createAndAttachMappingField(fieldName, mappingClass, column);
                    if (field.isKey()) {
                        column.setNullable(false);
                        pKey.addColumn(column);
                        pKey.getAssociatedIndex().addColumn(column);
                        mappingClass.getTable(tableName).addKeyColumn(column);
                    }
                }
            }
        }
        mappingClasses.put(pcClassName, mappingClass);
    }
    addRelationships();
    return new Results(schema, mappingClasses);
}
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) PersistenceClassElement(com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement) MappingTableElement(com.sun.jdo.api.persistence.model.mapping.MappingTableElement) RelationshipElement(com.sun.jdo.api.persistence.model.jdo.RelationshipElement) MappingRelationshipElement(com.sun.jdo.api.persistence.model.mapping.MappingRelationshipElement)

Example 4 with MappingClassElement

use of com.sun.jdo.api.persistence.model.mapping.MappingClassElement in project Payara by payara.

the class Model method storeMappingClass.

/**
 * Stores the MappingClassElement for the specified class name to an xml
 * file, creating the file if necessary.  The MappingClassElement must be
 * present in the HashMap of classes known by the Model in order to stored.
 * @param className the fully qualified name of the mapping class
 * @exception IOException if there is some error saving the class
 * @see #storeMappingClass
 */
public void storeMappingClass(String className) throws IOException {
    MappingClassElement mappingClass = null;
    synchronized (this._classes) {
        mappingClass = (MappingClassElement) _classes.get(className);
    }
    storeMappingClass(mappingClass);
}
Also used : MappingClassElement(com.sun.jdo.api.persistence.model.mapping.MappingClassElement)

Example 5 with MappingClassElement

use of com.sun.jdo.api.persistence.model.mapping.MappingClassElement in project Payara by payara.

the class RuntimeModel method getMappingClass.

/**
 * Returns the MappingClassElement created for the specified class name.
 * This method looks up the class in the internal cache. If not present
 * it loads the corresponding xml file containing the mapping information.
 * @param className the fully qualified name of the mapping class
 * @param classLoader the class loader used to find mapping information
 * @return the MappingClassElement for className,
 * <code>null</code> if an error occurs or none exists
 * @see com.sun.jdo.api.persistence.model.mapping.impl.MappingClassElementImpl#forName(String, Model)
 */
public MappingClassElement getMappingClass(String className, ClassLoader classLoader) {
    MappingClassElement mappingClass = null;
    // First check class loader. This has to be done before the super call!
    // Method Model.getMappingClass will check the MappingClassElement cache
    // and will find an entry in the case of a multiple class loader for the
    // same class name. So we have to check the multiple class loader first.
    classLoader = findClassLoader(className, classLoader);
    mappingClass = super.getMappingClass(className, classLoader);
    if ((mappingClass != null) && (classLoader != null)) {
        // Lookup the SchemElement connected to mappingClass. This reads
        // the .dbschema file using the specified classLoader and stores the
        // SchemaElement in the SchemaElement cache. Any subsequent
        // SchemaElement.forName or TableElement.forName lookups will use
        // the cached version.
        String databaseRoot = mappingClass.getDatabaseRoot();
        // RuntimeException to notify the user that something is wrong.
        if (!StringHelper.isEmpty(databaseRoot) && (SchemaElement.forName(databaseRoot, classLoader) == null)) {
            throw new RuntimeException(I18NHelper.getMessage(// NOI18N
            getMessages(), // NOI18N
            "dbschema.not_found", databaseRoot, className));
        }
    }
    return mappingClass;
}
Also used : MappingClassElement(com.sun.jdo.api.persistence.model.mapping.MappingClassElement)

Aggregations

MappingClassElement (com.sun.jdo.api.persistence.model.mapping.MappingClassElement)14 PersistenceClassElement (com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement)3 RelationshipElement (com.sun.jdo.api.persistence.model.jdo.RelationshipElement)3 MappingRelationshipElement (com.sun.jdo.api.persistence.model.mapping.MappingRelationshipElement)3 MappingTableElement (com.sun.jdo.api.persistence.model.mapping.MappingTableElement)3 MappingFile (com.sun.jdo.api.persistence.mapping.ejb.MappingFile)2 PersistenceFieldElement (com.sun.jdo.api.persistence.model.jdo.PersistenceFieldElement)2 MappingFieldElement (com.sun.jdo.api.persistence.model.mapping.MappingFieldElement)2 DatabaseGenerator (com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 ResourceReferenceDescriptor (com.sun.enterprise.deployment.ResourceReferenceDescriptor)1 Main (com.sun.jdo.api.persistence.enhancer.generator.Main)1 AbstractNameMapper (com.sun.jdo.api.persistence.mapping.ejb.AbstractNameMapper)1 ConversionException (com.sun.jdo.api.persistence.mapping.ejb.ConversionException)1 SunCmpMappings (com.sun.jdo.api.persistence.mapping.ejb.beans.SunCmpMappings)1 Model (com.sun.jdo.api.persistence.model.Model)1 ModelException (com.sun.jdo.api.persistence.model.ModelException)1 MappingClassElementImpl (com.sun.jdo.api.persistence.model.mapping.impl.MappingClassElementImpl)1