Search in sources :

Example 1 with EntityMappings

use of org.apache.openejb.jee.jpa.EntityMappings in project tomee by apache.

the class CmpJpaConversion method processEntityBean.

/**
 * Generate the CMP mapping data for an individual
 * EntityBean.
 *
 * @param ejbModule      The module containing the bean.
 * @param entityMappings The accumulated set of entity mappings.
 * @param bean           The been we're generating the mapping for.
 */
private void processEntityBean(final EjbModule ejbModule, final EntityMappings entityMappings, final EntityBean bean) {
    // try to add a new persistence-context-ref for cmp
    if (!addPersistenceContextRef(bean)) {
        // which means it has a mapping, so skip this bean
        return;
    }
    // get the real bean class
    final Class ejbClass = loadClass(ejbModule.getClassLoader(), bean.getEjbClass());
    // and generate a name for the subclass that will be generated and handed to the JPA
    // engine as the managed class.
    final String jpaEntityClassName = CmpUtil.getCmpImplClassName(bean.getAbstractSchemaName(), ejbClass.getName());
    // We don't use this mapping directly, instead we pull entries from it
    // the reason being is that we intend to support mappings that aren't
    // exactly correct.  i.e. users should be able to write mappings completely
    // ignorant of the fact that we subclass.  The fact that we subclass means
    // these user supplied mappings might need to be adjusted as the jpa orm.xml
    // file is extremely subclass/supperclass aware and mappings specified in it
    // need to be spot on.
    final EntityMappings userMappings = getUserEntityMappings(ejbModule);
    // chain of the bean looking for any that have user defined mappings.
    for (Class clazz = ejbClass; clazz != null; clazz = clazz.getSuperclass()) {
        final MappedSuperclass mappedSuperclass = removeMappedSuperclass(userMappings, clazz.getName());
        // that the mapping is correct.  Copy it from their mappings to ours
        if (mappedSuperclass != null) {
            entityMappings.getMappedSuperclass().add(mappedSuperclass);
        }
    }
    // Look for an existing mapping using the openejb generated subclass name
    Entity entity = removeEntity(userMappings, jpaEntityClassName);
    // because we are going to ignore all other xml metadata.
    if (entity != null) {
        // XmlMetadataComplete is an OpenEJB specific flag that
        // tells all other legacy descriptor converters to keep
        // their hands off.
        entity.setXmlMetadataComplete(true);
        entityMappings.getEntity().add(entity);
        return;
    }
    if (entity == null) {
        entity = new Entity(jpaEntityClassName);
    }
    // have to check for null everywhere.
    if (entity.getAttributes() == null) {
        entity.setAttributes(new Attributes());
    }
    // add the entity
    entityMappings.getEntity().add(entity);
    // OVERWRITE: description: contains the name of the entity bean
    entity.setDescription(ejbModule.getModuleId() + "#" + bean.getEjbName());
    // PRESERVE has queries: name: the name of the entity in queries
    final String entityName = bean.getAbstractSchemaName();
    entity.setName(entityName);
    entity.setEjbName(bean.getEjbName());
    final ClassLoader classLoader = ejbModule.getClassLoader();
    final Collection<MappedSuperclass> mappedSuperclasses;
    if (bean.getCmpVersion() == CmpVersion.CMP2) {
        // perform the 2.x class mapping.  This really just identifies the primary key and
        // other cmp fields that will be generated for the concrete class and identify them
        // to JPA.
        mappedSuperclasses = mapClass2x(entity, bean, classLoader);
    } else {
        // map the cmp class, but if we are using a mapped super class,
        // generate attribute-override instead of id and basic
        mappedSuperclasses = mapClass1x(bean.getEjbClass(), entity, bean, classLoader);
    }
    // configuration. f
    if (mappedSuperclasses != null) {
        // that will get passed to the JPA engine.
        for (final MappedSuperclass mappedSuperclass : mappedSuperclasses) {
            entityMappings.getMappedSuperclass().add(mappedSuperclass);
        }
    }
    // process queries
    for (final Query query : bean.getQuery()) {
        final NamedQuery namedQuery = new NamedQuery();
        final QueryMethod queryMethod = query.getQueryMethod();
        // todo deployment id could change in one of the later conversions... use entity name instead, but we need to save it off
        final StringBuilder name = new StringBuilder();
        name.append(entityName).append(".").append(queryMethod.getMethodName());
        if (queryMethod.getMethodParams() != null && !queryMethod.getMethodParams().getMethodParam().isEmpty()) {
            name.append('(');
            boolean first = true;
            for (final String methodParam : queryMethod.getMethodParams().getMethodParam()) {
                if (!first) {
                    name.append(",");
                }
                name.append(methodParam);
                first = false;
            }
            name.append(')');
        }
        namedQuery.setName(name.toString());
        namedQuery.setQuery(query.getEjbQl());
        entity.getNamedQuery().add(namedQuery);
    }
    // todo: there should be a common interface between ejb query object and openejb query object
    final OpenejbJar openejbJar = ejbModule.getOpenejbJar();
    final EjbDeployment ejbDeployment = openejbJar.getDeploymentsByEjbName().get(bean.getEjbName());
    if (ejbDeployment != null) {
        for (final org.apache.openejb.jee.oejb3.Query query : ejbDeployment.getQuery()) {
            final NamedQuery namedQuery = new NamedQuery();
            final org.apache.openejb.jee.oejb3.QueryMethod queryMethod = query.getQueryMethod();
            // todo deployment id could change in one of the later conversions... use entity name instead, but we need to save it off
            final StringBuilder name = new StringBuilder();
            name.append(entityName).append(".").append(queryMethod.getMethodName());
            if (queryMethod.getMethodParams() != null && !queryMethod.getMethodParams().getMethodParam().isEmpty()) {
                name.append('(');
                boolean first = true;
                for (final String methodParam : queryMethod.getMethodParams().getMethodParam()) {
                    if (!first) {
                        name.append(",");
                    }
                    name.append(methodParam);
                    first = false;
                }
                name.append(')');
            }
            namedQuery.setName(name.toString());
            namedQuery.setQuery(query.getObjectQl());
            entity.getNamedQuery().add(namedQuery);
        }
    }
}
Also used : Entity(org.apache.openejb.jee.jpa.Entity) Query(org.apache.openejb.jee.Query) NamedQuery(org.apache.openejb.jee.jpa.NamedQuery) QueryMethod(org.apache.openejb.jee.QueryMethod) Attributes(org.apache.openejb.jee.jpa.Attributes) OpenejbJar(org.apache.openejb.jee.oejb3.OpenejbJar) MappedSuperclass(org.apache.openejb.jee.jpa.MappedSuperclass) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) IdClass(org.apache.openejb.jee.jpa.IdClass) EjbDeployment(org.apache.openejb.jee.oejb3.EjbDeployment) NamedQuery(org.apache.openejb.jee.jpa.NamedQuery)

Example 2 with EntityMappings

use of org.apache.openejb.jee.jpa.EntityMappings in project tomee by apache.

the class ReadDescriptors method readCmpOrm.

// package scoped for testing
void readCmpOrm(final EjbModule ejbModule) throws OpenEJBException {
    final Object data = ejbModule.getAltDDs().get("openejb-cmp-orm.xml");
    if (data != null && !(data instanceof EntityMappings)) {
        if (data instanceof URL) {
            final URL url = (URL) data;
            try {
                final EntityMappings entitymappings = (EntityMappings) JaxbJavaee.unmarshal(EntityMappings.class, IO.read(url));
                ejbModule.getAltDDs().put("openejb-cmp-orm.xml", entitymappings);
            } catch (final SAXException e) {
                throw new OpenEJBException("Cannot parse the openejb-cmp-orm.xml file: " + url.toExternalForm(), e);
            } catch (final JAXBException e) {
                throw new OpenEJBException("Cannot unmarshall the openejb-cmp-orm.xml file: " + url.toExternalForm(), e);
            } catch (final IOException e) {
                throw new OpenEJBException("Cannot read the openejb-cmp-orm.xml file: " + url.toExternalForm(), e);
            } catch (final Exception e) {
                throw new OpenEJBException("Encountered unknown error parsing the openejb-cmp-orm.xml file: " + url.toExternalForm(), e);
            }
        }
    }
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) JAXBException(javax.xml.bind.JAXBException) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) IOException(java.io.IOException) URL(java.net.URL) OpenEJBException(org.apache.openejb.OpenEJBException) JAXBException(javax.xml.bind.JAXBException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 3 with EntityMappings

use of org.apache.openejb.jee.jpa.EntityMappings in project tomee by apache.

the class SunCmpConversionTest method convert.

private EntityMappings convert(final String ejbJarFileName, final String sunEjbJarFileName, final String sunCmpMappingsFileName, final String expectedFileName) throws Exception {
    InputStream in = getClass().getClassLoader().getResourceAsStream(ejbJarFileName);
    final EjbJar ejbJar = (EjbJar) JaxbJavaee.unmarshalJavaee(EjbJar.class, new ByteArrayInputStream(readContent(in).getBytes()));
    // create and configure the module
    final EjbModule ejbModule = new EjbModule(getClass().getClassLoader(), "TestModule", null, ejbJar, new OpenejbJar());
    final InitEjbDeployments initEjbDeployments = new InitEjbDeployments();
    initEjbDeployments.deploy(ejbModule);
    final AppModule appModule = new AppModule(getClass().getClassLoader(), "TestModule");
    appModule.getEjbModules().add(ejbModule);
    // add the altDD
    ejbModule.getAltDDs().put("sun-cmp-mappings.xml", getClass().getClassLoader().getResource(sunCmpMappingsFileName));
    ejbModule.getAltDDs().put("sun-ejb-jar.xml", getClass().getClassLoader().getResource(sunEjbJarFileName));
    // convert the cmp declarations into jpa entity declarations
    final CmpJpaConversion cmpJpaConversion = new CmpJpaConversion();
    cmpJpaConversion.deploy(appModule);
    // EntityMappings entityMappings = cmpJpaConversion.generateEntityMappings(ejbModule);
    // // load the sun-cmp-mappings.xml file
    // String sunCmpMappingsXml = readContent(getClass().getClassLoader().getResourceAsStream(sunCmpMappingsFileName));
    // SunCmpMappings sunCmpMappings = (SunCmpMappings) JaxbSun.unmarshal(SunCmpMappings.class, new ByteArrayInputStream(sunCmpMappingsXml.getBytes()));
    // fill in the jpa entity declarations with database mappings from the sun-cmp-mappings.xml file
    final SunConversion sunConversion = new SunConversion();
    // sunCmpConversion.mergeEntityMappings(ejbModule, entityMappings);
    sunConversion.deploy(appModule);
    // compare the results to the expected results
    if (expectedFileName != null) {
        in = getClass().getClassLoader().getResourceAsStream(expectedFileName);
        final String expected = readContent(in);
        // Sun doen't really support generated primary keys, so we need to add them by hand here
        final Set<String> generatedPks = new HashSet<>(Arrays.asList("BasicCmp2", "AOBasicCmp2", "EncCmp2", "Cmp2RmiIiop"));
        final EntityMappings cmpMappings = appModule.getCmpMappings();
        for (final Entity entity : cmpMappings.getEntity()) {
            if (generatedPks.contains(entity.getName())) {
                entity.getAttributes().getId().get(0).setGeneratedValue(new GeneratedValue(GenerationType.IDENTITY));
            }
        }
        final String actual = toString(cmpMappings);
        XMLUnit.setIgnoreWhitespace(true);
        try {
            final Diff myDiff = new DetailedDiff(new Diff(expected, actual));
            assertTrue("Files are not similar " + myDiff, myDiff.similar());
        } catch (final AssertionFailedError e) {
            assertEquals(expected, actual);
        }
    }
    return appModule.getCmpMappings();
}
Also used : Entity(org.apache.openejb.jee.jpa.Entity) DetailedDiff(org.custommonkey.xmlunit.DetailedDiff) DetailedDiff(org.custommonkey.xmlunit.DetailedDiff) Diff(org.custommonkey.xmlunit.Diff) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GeneratedValue(org.apache.openejb.jee.jpa.GeneratedValue) OpenejbJar(org.apache.openejb.jee.oejb3.OpenejbJar) ByteArrayInputStream(java.io.ByteArrayInputStream) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) AssertionFailedError(junit.framework.AssertionFailedError) EjbJar(org.apache.openejb.jee.EjbJar) HashSet(java.util.HashSet)

Example 4 with EntityMappings

use of org.apache.openejb.jee.jpa.EntityMappings in project tomee by apache.

the class LegacyInterfaceTest method testCustomCmpMappings.

public void testCustomCmpMappings() throws Exception {
    System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, InitContextFactory.class.getName());
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();
    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(MySingletonBean.class));
    ejbJar.addEnterpriseBean(new EntityBean(MyBmpBean.class, PersistenceType.BEAN));
    final EntityBean cmp = ejbJar.addEnterpriseBean(new EntityBean(MyCmpBean.class, PersistenceType.CONTAINER));
    cmp.setPrimKeyClass(Integer.class.getName());
    cmp.setPrimkeyField("id");
    cmp.getCmpField().add(new CmpField("id"));
    cmp.getCmpField().add(new CmpField("name"));
    final Query query = new Query();
    query.setQueryMethod(new QueryMethod("findByPrimaryKey", Integer.class.getName()));
    query.setEjbQl("SELECT OBJECT(DL) FROM License DL");
    cmp.getQuery().add(query);
    final List<ContainerTransaction> transactions = ejbJar.getAssemblyDescriptor().getContainerTransaction();
    transactions.add(new ContainerTransaction(TransAttribute.SUPPORTS, null, "MyBmpBean", "*"));
    transactions.add(new ContainerTransaction(TransAttribute.SUPPORTS, null, "MyCmpBean", "*"));
    transactions.add(new ContainerTransaction(TransAttribute.SUPPORTS, null, "MySingletonBean", "*"));
    final File f = new File("test").getAbsoluteFile();
    if (!f.exists() && !f.mkdirs()) {
        throw new Exception("Failed to create test directory: " + f);
    }
    final EntityMappings entityMappings = new EntityMappings();
    final Entity entity = new Entity();
    entity.setClazz("openejb.org.apache.openejb.core.MyCmpBean");
    entity.setName("MyCmpBean");
    entity.setDescription("MyCmpBean");
    entity.setAttributes(new Attributes());
    final NamedQuery namedQuery = new NamedQuery();
    namedQuery.setQuery("SELECT OBJECT(DL) FROM License DL");
    entity.getNamedQuery().add(namedQuery);
    final Id id = new Id();
    id.setName("id");
    entity.getAttributes().getId().add(id);
    final Basic basic = new Basic();
    basic.setName("name");
    final Column column = new Column();
    column.setName("wNAME");
    column.setLength(300);
    basic.setColumn(column);
    entity.getAttributes().getBasic().add(basic);
    entityMappings.getEntity().add(entity);
    final AppModule module = new AppModule(this.getClass().getClassLoader(), f.getAbsolutePath());
    final EjbModule ejbModule = new EjbModule(ejbJar);
    ejbModule.getAltDDs().put("openejb-cmp-orm.xml", entityMappings);
    module.getEjbModules().add(ejbModule);
    assertNull(module.getCmpMappings());
    assembler.createApplication(config.configureApplication(module));
    assertNotNull(module.getCmpMappings());
    final List<Basic> basicList = module.getCmpMappings().getEntityMap().get("openejb.org.apache.openejb.core.MyCmpBean").getAttributes().getBasic();
    assertEquals(1, basicList.size());
    assertEquals(300, basicList.get(0).getColumn().getLength().intValue());
    assertEquals("wNAME", basicList.get(0).getColumn().getName());
}
Also used : Entity(org.apache.openejb.jee.jpa.Entity) Basic(org.apache.openejb.jee.jpa.Basic) AppModule(org.apache.openejb.config.AppModule) NamedQuery(org.apache.openejb.jee.jpa.NamedQuery) Query(org.apache.openejb.jee.Query) QueryMethod(org.apache.openejb.jee.QueryMethod) Attributes(org.apache.openejb.jee.jpa.Attributes) EjbModule(org.apache.openejb.config.EjbModule) InitContextFactory(org.apache.openejb.core.ivm.naming.InitContextFactory) CmpField(org.apache.openejb.jee.CmpField) Column(org.apache.openejb.jee.jpa.Column) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) SecurityServiceInfo(org.apache.openejb.assembler.classic.SecurityServiceInfo) EjbJar(org.apache.openejb.jee.EjbJar) RemoveException(javax.ejb.RemoveException) RemoteException(java.rmi.RemoteException) EJBException(javax.ejb.EJBException) CreateException(javax.ejb.CreateException) SingletonBean(org.apache.openejb.jee.SingletonBean) TransactionServiceInfo(org.apache.openejb.assembler.classic.TransactionServiceInfo) ContainerTransaction(org.apache.openejb.jee.ContainerTransaction) EntityBean(org.apache.openejb.jee.EntityBean) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) Assembler(org.apache.openejb.assembler.classic.Assembler) NamedQuery(org.apache.openejb.jee.jpa.NamedQuery) Id(org.apache.openejb.jee.jpa.Id) File(java.io.File)

Example 5 with EntityMappings

use of org.apache.openejb.jee.jpa.EntityMappings in project tomee by apache.

the class CmpJpaConversion method deploy.

public AppModule deploy(final AppModule appModule) throws OpenEJBException {
    if (!hasCmpEntities(appModule)) {
        return appModule;
    }
    // create mappings if no mappings currently exist
    EntityMappings cmpMappings = appModule.getCmpMappings();
    if (cmpMappings == null) {
        cmpMappings = new EntityMappings();
        cmpMappings.setVersion("1.0");
        appModule.setCmpMappings(cmpMappings);
    }
    final Set<String> definedMappedClasses = new HashSet<>();
    // check for an existing "cmp" persistence unit, and look at existing mappings
    final PersistenceUnit cmpPersistenceUnit = findCmpPersistenceUnit(appModule);
    if (cmpPersistenceUnit != null) {
        if (cmpPersistenceUnit.getMappingFile() != null && cmpPersistenceUnit.getMappingFile().size() > 0) {
            for (final String mappingFile : cmpPersistenceUnit.getMappingFile()) {
                final EntityMappings entityMappings = readEntityMappings(mappingFile, appModule);
                if (entityMappings != null) {
                    definedMappedClasses.addAll(entityMappings.getEntityMap().keySet());
                }
            }
        }
    }
    // app mapping data
    for (final EjbModule ejbModule : appModule.getEjbModules()) {
        final EjbJar ejbJar = ejbModule.getEjbJar();
        // scan for CMP entity beans and merge the data into the collective set
        for (final EnterpriseBean enterpriseBean : ejbJar.getEnterpriseBeans()) {
            if (isCmpEntity(enterpriseBean)) {
                processEntityBean(ejbModule, definedMappedClasses, cmpMappings, (EntityBean) enterpriseBean);
            }
        }
        // if there are relationships defined in this jar, get a list of the defined
        // entities and process the relationship maps.
        final Relationships relationships = ejbJar.getRelationships();
        if (relationships != null) {
            final Map<String, Entity> entitiesByEjbName = new TreeMap<>();
            for (final Entity entity : cmpMappings.getEntity()) {
                entitiesByEjbName.put(entity.getEjbName(), entity);
            }
            for (final EjbRelation relation : relationships.getEjbRelation()) {
                processRelationship(entitiesByEjbName, relation);
            }
        }
        // Let's warn the user about any declarations we didn't end up using
        // so there can be no misunderstandings.
        final EntityMappings userMappings = getUserEntityMappings(ejbModule);
        for (final Entity mapping : userMappings.getEntity()) {
            LOGGER.warning("openejb-cmp-orm.xml mapping ignored: module=" + ejbModule.getModuleId() + ":  <entity class=\"" + mapping.getClazz() + "\">");
        }
        for (final MappedSuperclass mapping : userMappings.getMappedSuperclass()) {
            LOGGER.warning("openejb-cmp-orm.xml mapping ignored: module=" + ejbModule.getModuleId() + ":  <mapped-superclass class=\"" + mapping.getClazz() + "\">");
        }
    }
    if (!cmpMappings.getEntity().isEmpty()) {
        final PersistenceUnit persistenceUnit = getCmpPersistenceUnit(appModule);
        final boolean generatedOrmXmlProvided = appModule.getClassLoader().getResource(GENERATED_ORM_XML) != null;
        if (!persistenceUnit.getMappingFile().contains(GENERATED_ORM_XML)) {
            // explicit check for openejb-cmp-generated-orm, as this is generated and added to <mapping-file>
            if (generatedOrmXmlProvided) {
                LOGGER.warning("App module " + appModule.getModuleId() + " provides " + GENERATED_ORM_XML + ", but does not " + "specify it using <mapping-file> in persistence.xml for the CMP persistence unit, and it may conflict " + "with the generated mapping file. Consider renaming the file and explicitly referencing it in persistence.xml");
            }
            persistenceUnit.getMappingFile().add(GENERATED_ORM_XML);
        } else {
            if (generatedOrmXmlProvided) {
                LOGGER.warning("App module " + appModule.getModuleId() + " provides " + GENERATED_ORM_XML + " and additionally " + cmpMappings.getEntity().size() + "mappings have been generated. Consider renaming the " + GENERATED_ORM_XML + " in " + "your deployment archive to avoid any conflicts.");
            }
        }
        for (final Entity entity : cmpMappings.getEntity()) {
            if (!persistenceUnit.getClazz().contains(entity.getClazz())) {
                persistenceUnit.getClazz().add(entity.getClazz());
            }
        }
    }
    // causes some of the unit tests to fail.  Not sure why.  Should be fixed.
    for (final Entity entity : appModule.getCmpMappings().getEntity()) {
        if (entity.getAttributes() != null && entity.getAttributes().isEmpty()) {
            entity.setAttributes(null);
        }
    }
    return appModule;
}
Also used : Entity(org.apache.openejb.jee.jpa.Entity) EnterpriseBean(org.apache.openejb.jee.EnterpriseBean) TreeMap(java.util.TreeMap) Relationships(org.apache.openejb.jee.Relationships) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) EjbRelation(org.apache.openejb.jee.EjbRelation) MappedSuperclass(org.apache.openejb.jee.jpa.MappedSuperclass) EntityMappings(org.apache.openejb.jee.jpa.EntityMappings) HashSet(java.util.HashSet) EjbJar(org.apache.openejb.jee.EjbJar)

Aggregations

EntityMappings (org.apache.openejb.jee.jpa.EntityMappings)7 Entity (org.apache.openejb.jee.jpa.Entity)5 EjbJar (org.apache.openejb.jee.EjbJar)4 Query (org.apache.openejb.jee.Query)4 QueryMethod (org.apache.openejb.jee.QueryMethod)4 Attributes (org.apache.openejb.jee.jpa.Attributes)4 NamedQuery (org.apache.openejb.jee.jpa.NamedQuery)4 MappedSuperclass (org.apache.openejb.jee.jpa.MappedSuperclass)3 OpenejbJar (org.apache.openejb.jee.oejb3.OpenejbJar)3 File (java.io.File)2 RemoteException (java.rmi.RemoteException)2 HashSet (java.util.HashSet)2 CreateException (javax.ejb.CreateException)2 EJBException (javax.ejb.EJBException)2 RemoveException (javax.ejb.RemoveException)2 AppModule (org.apache.openejb.config.AppModule)2 EjbModule (org.apache.openejb.config.EjbModule)2 CmpField (org.apache.openejb.jee.CmpField)2 ContainerTransaction (org.apache.openejb.jee.ContainerTransaction)2 EntityBean (org.apache.openejb.jee.EntityBean)2