Search in sources :

Example 1 with PersistenceUnit

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

the class CmpJpaConversion method getCmpPersistenceUnit.

private PersistenceUnit getCmpPersistenceUnit(final AppModule appModule) {
    // search for the cmp persistence unit
    PersistenceUnit persistenceUnit = findCmpPersistenceUnit(appModule);
    // if not found create one
    if (persistenceUnit == null) {
        persistenceUnit = new PersistenceUnit();
        persistenceUnit.setName(CMP_PERSISTENCE_UNIT_NAME);
        persistenceUnit.setTransactionType(TransactionType.JTA);
        // Don't set default values here, let the autoconfig do that
        // persistenceUnit.setJtaDataSource("java:openejb/Resource/Default JDBC Database");
        // persistenceUnit.setNonJtaDataSource("java:openejb/Resource/Default Unmanaged JDBC Database");
        // todo paramterize this
        final Properties properties = new Properties();
        final String property = SystemInstance.get().getProperty("openejb.cmp.openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true, Indexes=false, IgnoreErrors=true)");
        if (property != null && !property.isEmpty()) {
            properties.setProperty("openjpa.jdbc.SynchronizeMappings", property);
        }
        // properties.setProperty("openjpa.DataCache", "false");
        properties.setProperty("openjpa.Log", "DefaultLevel=INFO");
        persistenceUnit.setProperties(properties);
        final Persistence persistence = new Persistence();
        persistence.setVersion("1.0");
        persistence.getPersistenceUnit().add(persistenceUnit);
        final PersistenceModule persistenceModule = new PersistenceModule(appModule, getPersistenceModuleId(appModule), persistence);
        appModule.addPersistenceModule(persistenceModule);
    }
    return persistenceUnit;
}
Also used : Persistence(org.apache.openejb.jee.jpa.unit.Persistence) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) Properties(java.util.Properties)

Example 2 with PersistenceUnit

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

the class AutoConfig method processPersistenceRef.

private PersistenceUnit processPersistenceRef(final LinkResolver<PersistenceUnit> persistenceUnits, final PersistenceRef ref, final URI moduleURI, final String componentName, final ValidationContext validation) {
    if (ref.getMappedName() != null && ref.getMappedName().startsWith("jndi:")) {
        return null;
    }
    PersistenceUnit unit = persistenceUnits.resolveLink(ref.getPersistenceUnitName(), moduleURI);
    // Explicitly check if we messed up the "if there's only one,
    // that's what you get" rule by adding our "cmp" unit.
    final Collection<PersistenceUnit> cmpUnits = persistenceUnits.values("cmp");
    if (unit == null && cmpUnits.size() > 0 && persistenceUnits.values().size() - cmpUnits.size() == 1) {
        // We did, there is exactly one non-cmp unit.  Let's find it.
        for (final PersistenceUnit persistenceUnit : persistenceUnits.values()) {
            if (!persistenceUnit.getName().equals("cmp")) {
                // Found it
                unit = persistenceUnit;
                break;
            }
        }
    }
    // try again using the ref name
    if (unit == null) {
        unit = persistenceUnits.resolveLink(ref.getName(), moduleURI);
    }
    // try again using the ref name with any prefix removed
    if (unit == null) {
        final String shortName = ref.getName().replaceFirst(".*/", "");
        unit = persistenceUnits.resolveLink(shortName, moduleURI);
    }
    if (unit != null) {
        ref.setPersistenceUnitName(unit.getName());
        ref.setMappedName(unit.getId());
    } else {
        // ----------------------------------------------
        // Nothing was found.  Let's try and figure out
        // what went wrong and log a validation message
        // ----------------------------------------------
        String refType = "persistence";
        if (ref instanceof PersistenceContextRef) {
            refType += "ContextRef";
        } else {
            refType += "UnitRef";
        }
        String refShortName = ref.getName();
        if (refShortName.matches(".*\\..*/.*")) {
            refShortName = refShortName.replaceFirst(".*/", "");
        }
        final List<String> availableUnits = new ArrayList<>();
        for (final PersistenceUnit persistenceUnit : persistenceUnits.values()) {
            availableUnits.add(persistenceUnit.getName());
        }
        Collections.sort(availableUnits);
        String unitName = ref.getPersistenceUnitName();
        if (availableUnits.size() == 0) {
            // Print a sample persistence.xml using their data
            if (unitName == null) {
                unitName = refShortName;
            }
            validation.fail(componentName, refType + ".noPersistenceUnits", refShortName, unitName);
        } else if ((ref.getPersistenceUnitName() == null || ref.getPersistenceUnitName().length() == 0) && availableUnits.size() > 1) {
            // Print a correct example of unitName in a ref
            // DMB: Idea, the ability to set a default unit-name in openejb-jar.xml via a property
            final String sampleUnitName = availableUnits.get(0);
            validation.fail(componentName, refType + ".noUnitName", refShortName, Join.join(", ", availableUnits), sampleUnitName);
        } else {
            final Collection<PersistenceUnit> vagueMatches = persistenceUnits.values(ref.getPersistenceUnitName());
            if (vagueMatches.size() != 0) {
                // Print the full rootUrls
                final List<String> possibleUnits = new ArrayList<>();
                for (final PersistenceUnit persistenceUnit : persistenceUnits.values()) {
                    try {
                        URI unitURI = URLs.uri(persistenceUnit.getId());
                        unitURI = URISupport.relativize(moduleURI, unitURI);
                        possibleUnits.add(unitURI.toString());
                    } catch (final Exception e) {
                        // id is typically not a valid URI
                        possibleUnits.add(persistenceUnit.getId());
                    }
                }
                Collections.sort(possibleUnits);
                validation.fail(componentName, refType + ".vagueMatches", refShortName, unitName, possibleUnits.size(), Join.join("\n", possibleUnits));
            } else {
                validation.fail(componentName, refType + ".noMatches", refShortName, unitName, Join.join(", ", availableUnits));
            }
        }
    }
    return unit;
}
Also used : PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) PersistenceContextRef(org.apache.openejb.jee.PersistenceContextRef) ArrayList(java.util.ArrayList) Collection(java.util.Collection) Arrays.asList(java.util.Arrays.asList) List(java.util.List) ArrayList(java.util.ArrayList) URI(java.net.URI) OpenEJBException(org.apache.openejb.OpenEJBException)

Example 3 with PersistenceUnit

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

the class ApplicationComposerDeployer method configureModule.

private Object configureModule(final AppModule appModule, final EjbModule ejbModule, final Class<?> clazz, Object instance, final Method m) {
    final int modifiers = m.getModifiers();
    if (!Modifier.isPublic(modifiers)) {
        throw new IllegalArgumentException("@Module should be public");
    }
    final boolean isStatic = Modifier.isStatic(modifiers);
    if (!isStatic) {
        try {
            instance = clazz.newInstance();
        } catch (final Exception e) {
        // no-op
        }
    }
    try {
        final Object result = m.invoke(isStatic ? null : instance);
        if (EjbJar.class.isInstance(result)) {
            ejbModule.setEjbJar(EjbJar.class.cast(result));
        } else if (Persistence.class.isInstance(result)) {
            final Persistence persistence = Persistence.class.cast(result);
            if (!persistence.getPersistenceUnit().isEmpty()) {
                appModule.getPersistenceModules().add(new PersistenceModule(appModule, rootUrl(ejbModule), persistence));
            }
        } else if (PersistenceUnit.class.isInstance(result)) {
            final PersistenceUnit unit = PersistenceUnit.class.cast(result);
            appModule.addPersistenceModule(new PersistenceModule(appModule, rootUrl(ejbModule), new Persistence(unit)));
        } else if (Beans.class.isInstance(result)) {
            final Beans beans = Beans.class.cast(result);
            ejbModule.setBeans(beans);
        } else {
            throw new IllegalArgumentException(result + " not yet supported (" + m + ")");
        }
    } catch (final IllegalAccessException | InvocationTargetException e) {
        throw new IllegalStateException(e);
    }
    return instance;
}
Also used : MalformedURLException(java.net.MalformedURLException) OpenEJBException(org.apache.openejb.OpenEJBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Persistence(org.apache.openejb.jee.jpa.unit.Persistence) Beans(org.apache.openejb.jee.Beans) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) EjbJar(org.apache.openejb.jee.EjbJar)

Example 4 with PersistenceUnit

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

the class PersistenceUnitLinkResolver method tryToResolveForEar.

@Override
protected Collection<PersistenceUnit> tryToResolveForEar(final Collection<PersistenceUnit> values, final URI moduleUri, final String link) {
    if (module == null || module.isStandaloneModule()) {
        // can't help
        return values;
    }
    final WebModule war = extractWebApp(moduleUri);
    if (war != null) {
        // keep only values related to this war
        values.removeIf(persistenceUnit -> !isIn(persistenceUnit, war));
        return values;
    }
    // else remove all webapp info
    final Iterator<PersistenceUnit> it = values.iterator();
    while (it.hasNext()) {
        final PersistenceUnit next = it.next();
        for (final WebModule webModule : module.getWebModules()) {
            if (isIn(next, webModule)) {
                it.remove();
            }
        }
    }
    return values;
}
Also used : PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit)

Example 5 with PersistenceUnit

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

the class ReadDescriptors method deploy.

@SuppressWarnings({ "unchecked" })
public AppModule deploy(final AppModule appModule) throws OpenEJBException {
    for (final EjbModule ejbModule : appModule.getEjbModules()) {
        if (ejbModule.getEjbJar() == null) {
            readEjbJar(ejbModule, appModule);
        }
        if (ejbModule.getOpenejbJar() == null) {
            readOpenejbJar(ejbModule);
        }
        if (ejbModule.getBeans() == null) {
            readBeans(ejbModule);
        }
        readValidationConfigType(ejbModule);
        readCmpOrm(ejbModule);
        readResourcesXml(ejbModule);
    }
    for (final ClientModule clientModule : appModule.getClientModules()) {
        readAppClient(clientModule, appModule);
        readValidationConfigType(clientModule);
        readResourcesXml(clientModule);
    }
    for (final ConnectorModule connectorModule : appModule.getConnectorModules()) {
        readConnector(connectorModule, appModule);
        readValidationConfigType(connectorModule);
        readResourcesXml(connectorModule);
    }
    for (final WebModule webModule : appModule.getWebModules()) {
        readWebApp(webModule, appModule);
        readValidationConfigType(webModule);
        readResourcesXml(webModule);
    }
    final List<Object> persistenceUrls = (List<Object>) appModule.getAltDDs().get("persistence.xml");
    if (persistenceUrls != null) {
        for (final Object persistenceUrl : persistenceUrls) {
            final boolean url = persistenceUrl instanceof URL;
            final Source source = getSource(persistenceUrl);
            final String moduleName;
            final String path;
            final String rootUrl;
            if (url) {
                final URL pUrl = (URL) persistenceUrl;
                File file = URLs.toFile(pUrl);
                path = file.getAbsolutePath();
                if (file.getName().endsWith("persistence.xml")) {
                    final File parentFile = file.getParentFile();
                    final String parent = parentFile.getName();
                    if (parent.equalsIgnoreCase("WEB-INF") || parent.equalsIgnoreCase("META-INF")) {
                        file = parentFile.getParentFile();
                    } else {
                        // we don't really know so simply go back (users will often put persistence.xml in root resource folder with arquillian)
                        file = file.getParentFile();
                    }
                }
                moduleName = file.toURI().toString();
                String tmpRootUrl = moduleName;
                final String extForm = pUrl.toExternalForm();
                if (extForm.contains("WEB-INF/classes/META-INF/")) {
                    if (!ROOT_URL_FROM_WEBINF) {
                        tmpRootUrl = extForm.substring(0, extForm.indexOf("/META-INF"));
                    } else {
                        tmpRootUrl = extForm.substring(0, extForm.indexOf("/classes/META-INF"));
                    }
                }
                if (tmpRootUrl.endsWith(".war")) {
                    tmpRootUrl = tmpRootUrl.substring(0, tmpRootUrl.length() - ".war".length());
                }
                rootUrl = tmpRootUrl;
            } else {
                moduleName = "";
                rootUrl = "";
                path = null;
            }
            try {
                final Persistence persistence = JaxbPersistenceFactory.getPersistence(Persistence.class, source.get());
                final PersistenceModule persistenceModule = new PersistenceModule(appModule, rootUrl, persistence);
                persistenceModule.getWatchedResources().add(moduleName);
                if (url && "file".equals(((URL) persistenceUrl).getProtocol())) {
                    persistenceModule.getWatchedResources().add(path);
                }
                appModule.addPersistenceModule(persistenceModule);
            } catch (final Exception e1) {
                DeploymentLoader.LOGGER.error("Unable to load Persistence Unit from EAR: " + appModule.getJarLocation() + ", module: " + moduleName + ". Exception: " + e1.getMessage(), e1);
            }
        }
    }
    final List<URL> persistenceFragmentUrls = (List<URL>) appModule.getAltDDs().get("persistence-fragment.xml");
    if (persistenceFragmentUrls != null) {
        for (final URL persistenceFragmentUrl : persistenceFragmentUrls) {
            try {
                final PersistenceFragment persistenceFragment = JaxbPersistenceFactory.getPersistence(PersistenceFragment.class, persistenceFragmentUrl);
                // merging
                for (final PersistenceUnitFragment fragmentUnit : persistenceFragment.getPersistenceUnitFragment()) {
                    for (final PersistenceModule persistenceModule : appModule.getPersistenceModules()) {
                        final Persistence persistence = persistenceModule.getPersistence();
                        for (final PersistenceUnit unit : persistence.getPersistenceUnit()) {
                            if (!fragmentUnit.getName().equals(unit.getName())) {
                                continue;
                            }
                            if (!persistenceFragment.getVersion().equals(persistence.getVersion())) {
                                logger.error("persistence unit version and fragment version are different, fragment will be ignored");
                                continue;
                            }
                            if ("file".equals(persistenceFragmentUrl.getProtocol())) {
                                persistenceModule.getWatchedResources().add(URLs.toFile(persistenceFragmentUrl).getAbsolutePath());
                            }
                            for (final String clazz : fragmentUnit.getClazz()) {
                                if (!unit.getClazz().contains(clazz)) {
                                    logger.info("Adding class " + clazz + " to persistence unit " + fragmentUnit.getName());
                                    unit.getClazz().add(clazz);
                                }
                            }
                            for (final String mappingFile : fragmentUnit.getMappingFile()) {
                                if (!unit.getMappingFile().contains(mappingFile)) {
                                    logger.info("Adding mapping file " + mappingFile + " to persistence unit " + fragmentUnit.getName());
                                    unit.getMappingFile().add(mappingFile);
                                }
                            }
                            for (final String jarFile : fragmentUnit.getJarFile()) {
                                if (!unit.getJarFile().contains(jarFile)) {
                                    logger.info("Adding jar file " + jarFile + " to persistence unit " + fragmentUnit.getName());
                                    unit.getJarFile().add(jarFile);
                                }
                            }
                            if (fragmentUnit.isExcludeUnlistedClasses()) {
                                unit.setExcludeUnlistedClasses(true);
                                logger.info("Excluding unlisted classes for persistence unit " + fragmentUnit.getName());
                            }
                        // else let the main persistence unit decide
                        }
                    }
                }
            } catch (final Exception e1) {
                DeploymentLoader.LOGGER.error("Unable to load Persistence Unit Fragment from EAR: " + appModule.getJarLocation() + ", fragment: " + persistenceFragmentUrl.toString() + ". Exception: " + e1.getMessage(), e1);
            }
        }
    }
    return appModule;
}
Also used : URL(java.net.URL) InputSource(org.xml.sax.InputSource) OpenEJBException(org.apache.openejb.OpenEJBException) JAXBException(javax.xml.bind.JAXBException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Persistence(org.apache.openejb.jee.jpa.unit.Persistence) PersistenceUnitFragment(org.apache.openejb.jee.jpa.fragment.PersistenceUnitFragment) PersistenceUnit(org.apache.openejb.jee.jpa.unit.PersistenceUnit) PersistenceFragment(org.apache.openejb.jee.jpa.fragment.PersistenceFragment) List(java.util.List) File(java.io.File)

Aggregations

PersistenceUnit (org.apache.openejb.jee.jpa.unit.PersistenceUnit)48 Persistence (org.apache.openejb.jee.jpa.unit.Persistence)36 Module (org.apache.openejb.testing.Module)19 AppModule (org.apache.openejb.config.AppModule)10 EjbJar (org.apache.openejb.jee.EjbJar)10 AppInfo (org.apache.openejb.assembler.classic.AppInfo)9 ResourceInfo (org.apache.openejb.assembler.classic.ResourceInfo)9 EjbModule (org.apache.openejb.config.EjbModule)9 PersistenceModule (org.apache.openejb.config.PersistenceModule)8 WebApp (org.apache.openejb.jee.WebApp)7 ArrayList (java.util.ArrayList)5 StatelessBean (org.apache.openejb.jee.StatelessBean)5 File (java.io.File)4 Properties (java.util.Properties)4 URL (java.net.URL)3 Collection (java.util.Collection)3 List (java.util.List)3 OpenEJBException (org.apache.openejb.OpenEJBException)3 Assembler (org.apache.openejb.assembler.classic.Assembler)3 PersistenceUnitInfo (org.apache.openejb.assembler.classic.PersistenceUnitInfo)3