Search in sources :

Example 16 with PersistenceProvider

use of javax.persistence.spi.PersistenceProvider in project OpenAttestation by OpenAttestation.

the class PersistenceManager method createEntityManagerFactory.

/**
     * The new form of this method.  The old form simply wraps this one now.
     * Loads persistence.xml from the classpath and creates an entity manager
     * with those settings, which can now include Apache Commons Pool and JDBC.
     * 
     * @param persistenceUnitName
     * @param properties
     * @return 
     */
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Properties jpaProperties) {
    log.debug("Loading database driver {} for persistence unit {}", new String[] { jpaProperties.getProperty("javax.persistence.jdbc.driver"), persistenceUnitName });
    try {
        Class.forName(jpaProperties.getProperty("javax.persistence.jdbc.driver"));
    } catch (ClassNotFoundException ex) {
        log.error("Cannot load JDBC Driver for persistence unit", ex);
    }
    PersistenceUnitInfo persistenceUnitInfo = null;
    try {
        persistenceUnitInfo = getPersistenceUnitInfo(persistenceUnitName, jpaProperties);
    } catch (IOException e) {
        throw new PersistenceException("Cannot load PersistenceUnit named " + persistenceUnitName, e);
    }
    if (persistenceUnitInfo == null) {
        throw new PersistenceException("Cannot find PersistenceUnit named " + persistenceUnitName);
    }
    EntityManagerFactory emf = null;
    PersistenceProviderResolver resolver = PersistenceProviderResolverHolder.getPersistenceProviderResolver();
    List<PersistenceProvider> providers = resolver.getPersistenceProviders();
    // check if we have the requested provider
    if (persistenceUnitInfo.getPersistenceProviderClassName() != null) {
        log.info("Looking for specific JPA provider: {}", persistenceUnitInfo.getPersistenceProviderClassName());
        for (PersistenceProvider provider : providers) {
            log.info("Looking at provider: {}", provider.getClass().getName());
            if (provider.getClass().getName().equals(persistenceUnitInfo.getPersistenceProviderClassName())) {
                // important: must use the properties as returned by the persistenceUnitInfo because it may have altered them... specifically:  remove user and password entries after creating datasource to force eclipselink to call getConnection() instead of getConnection(user,password)
                emf = provider.createContainerEntityManagerFactory(persistenceUnitInfo, persistenceUnitInfo.getProperties());
                if (emf != null) {
                    log.info("Found requested persistence provider");
                    return emf;
                }
            }
        }
    }
    // check if any other provider can accomodate the persistence unit
    log.info("Looking for any compatible JPA provider");
    for (PersistenceProvider provider : providers) {
        log.info("Looking at provider: {}", provider.getClass().getName());
        // important: must use the properties as returned by the persistenceUnitInfo because it may have altered them... specifically:  remove user and password entries after creating datasource to force eclipselink to call getConnection() instead of getConnection(user,password)
        emf = provider.createContainerEntityManagerFactory(persistenceUnitInfo, persistenceUnitInfo.getProperties());
        if (emf != null) {
            log.info("Found compatible persistence provider");
            return emf;
        }
    }
    throw new PersistenceException("No Persistence provider for EntityManager named " + persistenceUnitName);
}
Also used : PersistenceProviderResolver(javax.persistence.spi.PersistenceProviderResolver) EntityManagerFactory(javax.persistence.EntityManagerFactory) PersistenceProvider(javax.persistence.spi.PersistenceProvider) PersistenceException(javax.persistence.PersistenceException) IOException(java.io.IOException) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo)

Example 17 with PersistenceProvider

use of javax.persistence.spi.PersistenceProvider in project Payara by payara.

the class PersistenceUnitLoader method loadPU.

/**
 * Loads an individual PersistenceUnitDescriptor and registers the
 * EntityManagerFactory in appropriate DOL structure.
 *
 * @param pud PersistenceUnitDescriptor to be loaded.
 */
private EntityManagerFactory loadPU(PersistenceUnitDescriptor pud) {
    checkForUpgradeFromTopLinkEssentials(pud);
    checkForDataSourceOverride(pud);
    calculateDefaultDataSource(pud);
    PersistenceUnitInfo pInfo = new PersistenceUnitInfoImpl(pud, providerContainerContractInfo);
    String applicationLocation = providerContainerContractInfo.getApplicationLocation();
    final boolean fineMsgLoggable = logger.isLoggable(Level.FINE);
    if (fineMsgLoggable) {
        logger.fine("Loading persistence unit for application: \"" + applicationLocation + "\"pu Root is: " + pud.getPuRoot());
        // NOI18N
        logger.fine("PersistenceInfo for this pud is :\n" + pInfo);
    }
    PersistenceProvider provider;
    try {
        // See we use application CL as opposed to system CL to loadPU
        // provider. This allows user to get hold of provider specific
        // implementation classes in their code. But this also means
        // provider must not use appserver implementation classes directly
        // because once we implement isolation in our class loader hierarchy
        // the only classes available to application class loader would be
        // our appserver interface classes. By Sahoo
        provider = PersistenceProvider.class.cast(providerContainerContractInfo.getClassLoader().loadClass(pInfo.getPersistenceProviderClassName()).newInstance());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    Map<String, Object> schemaGenerationOverrides;
    schemaGenerationProcessor = SchemaGenerationProcessorFactory.createSchemaGenerationProcessor(pud);
    if (providerContainerContractInfo.isJava2DBRequired()) {
        schemaGenerationProcessor.init(pud, providerContainerContractInfo.getDeploymentContext());
        schemaGenerationOverrides = schemaGenerationProcessor.getOverridesForSchemaGeneration();
    } else {
        // schema generation is not required if this EMF is being created for
        // -appserver restarting or,
        // -on an instance or,
        // -appclient
        // Suppress schema generation in this case
        schemaGenerationOverrides = schemaGenerationProcessor.getOverridesForSuppressingSchemaGeneration();
    }
    Map<String, Object> overRides = new HashMap<String, Object>(integrationProperties);
    if (schemaGenerationOverrides != null) {
        overRides.putAll(schemaGenerationOverrides);
    }
    // Check if the persistence unit requires Bean Validation
    ValidationMode validationMode = getValidationMode(pud);
    if (validationMode == ValidationMode.AUTO || validationMode == ValidationMode.CALLBACK) {
        overRides.put(VALIDATOR_FACTORY, providerContainerContractInfo.getValidatorFactory());
    }
    if (!providerContainerContractInfo.isWeavingEnabled()) {
        // NOI18N
        overRides.put(ECLIPSELINK_WEAVING_PROPERTY, System.getProperty(ECLIPSELINK_WEAVING_PROPERTY, "false"));
    }
    EntityManagerFactory emf = provider.createContainerEntityManagerFactory(pInfo, overRides);
    if (fineMsgLoggable) {
        // NOI18N
        logger.logp(// NOI18N
        Level.FINE, // NOI18N
        "PersistenceUnitLoader", // NOI18N
        "loadPU", "emf = {0}", // NOI18N
        emf);
    }
    PersistenceUnitsDescriptor parent = pud.getParent();
    RootDeploymentDescriptor containingBundle = parent.getParent();
    providerContainerContractInfo.registerEMF(pInfo.getPersistenceUnitName(), pud.getPuRoot(), containingBundle, emf);
    if (fineMsgLoggable) {
        logger.fine(// NOI18N
        "Finished loading persistence unit for application: " + applicationLocation);
    }
    return emf;
}
Also used : HashMap(java.util.HashMap) PersistenceProvider(javax.persistence.spi.PersistenceProvider) ValidationMode(javax.persistence.ValidationMode) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) PersistenceUnitsDescriptor(com.sun.enterprise.deployment.PersistenceUnitsDescriptor) RootDeploymentDescriptor(org.glassfish.deployment.common.RootDeploymentDescriptor) EntityManagerFactory(javax.persistence.EntityManagerFactory)

Example 18 with PersistenceProvider

use of javax.persistence.spi.PersistenceProvider in project opencast by opencast.

the class PersistenceUtil method newEntityManagerFactory.

/**
 * Create a new entity manager factory with the persistence unit name <code>emName</code>. A
 * {@link PersistenceProvider} named <code>persistence</code> has to be registered as an OSGi service. If you want to
 * configure the factory please also register a map containing all properties under the name
 * <code>persistenceProps</code>. See {@link PersistenceProvider#createEntityManagerFactory(String, Map)} for more
 * information about config maps.
 */
public static EntityManagerFactory newEntityManagerFactory(ComponentContext cc, String emName) {
    PersistenceProvider persistenceProvider = (PersistenceProvider) cc.locateService("persistence");
    final Map persistenceProps;
    Map pp = (Map) cc.locateService("persistenceProps");
    persistenceProps = pp != null ? pp : Collections.emptyMap();
    return persistenceProvider.createEntityManagerFactory(emName, persistenceProps);
}
Also used : PersistenceProvider(javax.persistence.spi.PersistenceProvider) Map(java.util.Map)

Example 19 with PersistenceProvider

use of javax.persistence.spi.PersistenceProvider in project wildfly by wildfly.

the class PersistenceUnitServiceHandler method addPuService.

/**
 * Add one PU service per top level deployment that represents
 *
 * @param phaseContext
 * @param puList
 * @param startEarly
 * @param platform
 * @throws DeploymentUnitProcessingException
 */
private static void addPuService(final DeploymentPhaseContext phaseContext, final ArrayList<PersistenceUnitMetadataHolder> puList, final boolean startEarly, final Platform platform) throws DeploymentUnitProcessingException {
    if (!puList.isEmpty()) {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
        final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
        final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
        final ModuleClassLoader classLoader = module.getClassLoader();
        for (PersistenceUnitMetadataHolder holder : puList) {
            setAnnotationIndexes(holder, deploymentUnit);
            for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
                // only start the persistence unit if JPA_CONTAINER_MANAGED is true
                String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
                boolean deployPU = (jpaContainerManaged == null ? true : Boolean.parseBoolean(jpaContainerManaged));
                if (deployPU) {
                    final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(deploymentUnit);
                    final PersistenceProvider provider = lookupProvider(pu, persistenceProviderDeploymentHolder, deploymentUnit);
                    final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor(pu, persistenceProviderDeploymentHolder, deploymentUnit, provider, platform);
                    final boolean twoPhaseBootStrapCapable = (adaptor instanceof TwoPhaseBootstrapCapable) && Configuration.allowTwoPhaseBootstrap(pu);
                    if (startEarly) {
                        if (twoPhaseBootStrapCapable) {
                            deployPersistenceUnitPhaseOne(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, adaptor);
                        } else if (false == Configuration.needClassFileTransformer(pu)) {
                            // will start later when startEarly == false
                            ROOT_LOGGER.tracef("persistence unit %s in deployment %s is configured to not need class transformer to be set, no class rewriting will be allowed", pu.getPersistenceUnitName(), deploymentUnit.getName());
                        } else {
                            // we need class file transformer to work, don't allow Jakarta Contexts and Dependency Injection bean manager to be access since that
                            // could cause application classes to be loaded (workaround by setting jboss.as.jpa.classtransformer to false).  WFLY-1463
                            final boolean allowCdiBeanManagerAccess = false;
                            deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor, allowCdiBeanManagerAccess);
                        }
                    } else {
                        // !startEarly
                        if (twoPhaseBootStrapCapable) {
                            deployPersistenceUnitPhaseTwo(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor);
                        } else if (false == Configuration.needClassFileTransformer(pu)) {
                            final boolean allowCdiBeanManagerAccess = true;
                            // PUs that have Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false will start during INSTALL phase
                            deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor, allowCdiBeanManagerAccess);
                        }
                    }
                } else {
                    ROOT_LOGGER.tracef("persistence unit %s in deployment %s is not container managed (%s is set to false)", pu.getPersistenceUnitName(), deploymentUnit.getName(), Configuration.JPA_CONTAINER_MANAGED);
                }
            }
        }
    }
}
Also used : PersistenceUnitMetadataHolder(org.jboss.as.jpa.config.PersistenceUnitMetadataHolder) ModuleClassLoader(org.jboss.modules.ModuleClassLoader) ServiceTarget(org.jboss.msc.service.ServiceTarget) PersistenceProvider(javax.persistence.spi.PersistenceProvider) EEModuleDescription(org.jboss.as.ee.component.EEModuleDescription) PersistenceUnitMetadata(org.jipijapa.plugin.spi.PersistenceUnitMetadata) Module(org.jboss.modules.Module) PersistenceProviderDeploymentHolder(org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) TwoPhaseBootstrapCapable(org.jipijapa.plugin.spi.TwoPhaseBootstrapCapable) PersistenceProviderAdaptor(org.jipijapa.plugin.spi.PersistenceProviderAdaptor)

Example 20 with PersistenceProvider

use of javax.persistence.spi.PersistenceProvider in project wildfly by wildfly.

the class PersistenceUnitServiceHandler method nextPhaseDependsOnPersistenceUnit.

/**
 * The sub-deployment phases run in parallel, ensure that no deployment/sub-deployment moves past
 * Phase.FIRST_MODULE_USE, until the applications persistence unit services are started.
 *
 * Note that some application persistence units will not be created until the Phase.INSTALL, in which case
 * NEXT_PHASE_DEPS is not needed.
 */
private static void nextPhaseDependsOnPersistenceUnit(final DeploymentPhaseContext phaseContext, final Platform platform) throws DeploymentUnitProcessingException {
    final DeploymentUnit topDeploymentUnit = DeploymentUtils.getTopDeploymentUnit(phaseContext.getDeploymentUnit());
    final PersistenceUnitsInApplication persistenceUnitsInApplication = topDeploymentUnit.getAttachment(PersistenceUnitsInApplication.PERSISTENCE_UNITS_IN_APPLICATION);
    for (final PersistenceUnitMetadataHolder holder : persistenceUnitsInApplication.getPersistenceUnitHolders()) {
        for (final PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
            String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
            boolean deployPU = (jpaContainerManaged == null ? true : Boolean.parseBoolean(jpaContainerManaged));
            if (deployPU) {
                final ServiceName puServiceName = PersistenceUnitServiceImpl.getPUServiceName(pu);
                final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(phaseContext.getDeploymentUnit());
                final PersistenceProvider provider = lookupProvider(pu, persistenceProviderDeploymentHolder, phaseContext.getDeploymentUnit());
                final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor(pu, persistenceProviderDeploymentHolder, phaseContext.getDeploymentUnit(), provider, platform);
                final boolean twoPhaseBootStrapCapable = (adaptor instanceof TwoPhaseBootstrapCapable) && Configuration.allowTwoPhaseBootstrap(pu);
                // only add the next phase dependency, if the persistence unit service is starting early.
                if (Configuration.needClassFileTransformer(pu) && !Configuration.allowApplicationDefinedDatasource(pu)) {
                    // wait until the persistence unit service is started before starting the next deployment phase
                    phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, twoPhaseBootStrapCapable ? puServiceName.append(FIRST_PHASE) : puServiceName);
                }
            }
        }
    }
}
Also used : PersistenceUnitMetadataHolder(org.jboss.as.jpa.config.PersistenceUnitMetadataHolder) PersistenceUnitsInApplication(org.jboss.as.jpa.config.PersistenceUnitsInApplication) ServiceName(org.jboss.msc.service.ServiceName) PersistenceProvider(javax.persistence.spi.PersistenceProvider) PersistenceUnitMetadata(org.jipijapa.plugin.spi.PersistenceUnitMetadata) PersistenceProviderDeploymentHolder(org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) TwoPhaseBootstrapCapable(org.jipijapa.plugin.spi.TwoPhaseBootstrapCapable) PersistenceProviderAdaptor(org.jipijapa.plugin.spi.PersistenceProviderAdaptor)

Aggregations

PersistenceProvider (javax.persistence.spi.PersistenceProvider)25 EntityManagerFactory (javax.persistence.EntityManagerFactory)9 HashMap (java.util.HashMap)8 ModuleClassLoader (org.jboss.modules.ModuleClassLoader)6 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 Properties (java.util.Properties)4 PersistenceUnitInfo (javax.persistence.spi.PersistenceUnitInfo)4 DeploymentUnit (org.jboss.as.server.deployment.DeploymentUnit)4 ServiceReference (org.osgi.framework.ServiceReference)4 IOException (java.io.IOException)3 EntityManager (javax.persistence.EntityManager)3 PersistenceProviderDeploymentHolder (org.jboss.as.jpa.config.PersistenceProviderDeploymentHolder)3 Module (org.jboss.modules.Module)3 PersistenceProviderAdaptor (org.jipijapa.plugin.spi.PersistenceProviderAdaptor)3 Bundle (org.osgi.framework.Bundle)3 ClassFileTransformer (java.lang.instrument.ClassFileTransformer)2 ValidationMode (javax.persistence.ValidationMode)2 TempClassLoader (org.apache.openejb.core.TempClassLoader)2 PersistenceClassLoaderHandler (org.apache.openejb.persistence.PersistenceClassLoaderHandler)2