/** * fixes the warning (Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb * .HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.) * * must be called before getting the EntityManagerFactory */ private static void fixDeprecatedHibernateWarning() { PersistenceProviderResolverHolder.setPersistenceProviderResolver(new PersistenceProviderResolver() { private final List<PersistenceProvider> providers_ = Arrays.asList(new PersistenceProvider[]{new HibernatePersistenceProvider()}); @Override public List<PersistenceProvider> getPersistenceProviders() { return providers_; } @Override public void clearCachedProviders() { } }); }
@Override protected void setUp() throws Exception { super.setUp(); URL persistenceProviderUrl = FileUtil.getArchiveRoot(PersistenceProvider.class.getProtectionDomain().getCodeSource().getLocation()); ProtectionDomain domain = Resource.class.getProtectionDomain(); System.out.println("Protection domain: " + domain); CodeSource source = domain.getCodeSource(); System.out.println("Code source: " + source); if (source != null) { URL location = source.getLocation(); System.out.println("Location: " + location); URL resourceUrl = FileUtil.getArchiveRoot(location); addCompileRoots(Arrays.asList(persistenceProviderUrl, resourceUrl)); } else { addCompileRoots(Arrays.asList(persistenceProviderUrl)); } }
private synchronized EntityManager getEntityManager(final PersistenceUnitInfo unit) { if (entityManagers.containsKey(unit.getPersistenceUnitName())) { return entityManagers.get(unit.getPersistenceUnitName()); } final String providerClassName = unit.getPersistenceProviderClassName(); try { final PersistenceProvider provider = (PersistenceProvider) Class.forName(providerClassName).newInstance(); final EntityManagerFactory emf = provider.createContainerEntityManagerFactory(unit, new HashMap()); final EntityManager entityManager = emf.createEntityManager(); entityManagers.put(unit.getPersistenceUnitName(), entityManager); entityManager.getTransaction().begin(); return entityManager; } catch (final IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TestEEfiException("Failed to load persistence provider class " + providerClassName, e); } }
private static Filter createFilter(BundleContext context, PersistenceUnit punit) { String filter; if (punit.getPersistenceProviderClassName() != null) { filter = String.format("(&(objectClass=%s)(%s=%s))", PersistenceProvider.class.getName(), JAVAX_PERSISTENCE_PROVIDER, punit.getPersistenceProviderClassName()); } else { filter = String.format("(objectClass=%s)", PersistenceProvider.class.getName()); } try { return context.createFilter(filter); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e); } }
@Override public StoredPerProvider addingService(ServiceReference<PersistenceProvider> reference) { String providerName = (String)reference.getProperty(JAVAX_PERSISTENCE_PROVIDER); // FIXME should be set when creating the EMF was successful if (punit.getPersistenceProviderClassName() == null) { punit.setProviderClassName(providerName); } StoredPerProvider stored = new StoredPerProvider(); LOGGER.info("Found provider for " + punit.getPersistenceUnitName() + " " + punit.getPersistenceProviderClassName()); PersistenceProvider provider = context.getService(reference); createAndCloseDummyEMF(provider); stored.builder = new AriesEntityManagerFactoryBuilder(context, provider, reference.getBundle(), punit); Dictionary<String, ?> props = AriesEntityManagerFactoryBuilder.createBuilderProperties(punit, punit.getBundle()); stored.reg = context.registerService(EntityManagerFactoryBuilder.class, stored.builder , props); return stored; }
private ServiceTracker<?, ?> createDataSourceTracker(PersistenceProvider provider) { if (usesDataSource()) { synchronized (this) { driver = "Pre Configured DataSource"; } if (!usesDataSourceService()) { LOGGER.warn("Persistence unit " + persistenceUnit.getPersistenceUnitName() + " refers to a non OSGi service DataSource"); return null; } DataSourceTracker dsTracker = new DataSourceTracker(containerContext, this, DataSourceTracker.getDsName(persistenceUnit)); return dsTracker; } else if (usesDSF()) { String jdbcClass = DSFTracker.getDriverName(persistenceUnit); synchronized (this) { driver = jdbcClass; } DSFTracker dsfTracker = new DSFTracker(containerContext, this, jdbcClass); return dsfTracker; } else { LOGGER.debug("Persistence unit " + getPUName() + " does not refer a DataSource. " +"It can only be used with EntityManagerFactoryBuilder."); return null; } }
private void handlePotentialEclipseLink(Bundle b) { if (!ECLIPSELINK_JPA_PROVIDER_BUNDLE_SYMBOLIC_NAME.equals(b.getSymbolicName())) { return; } if (registeredProviders.containsKey(b)) { return; } PersistenceProvider provider = createEclipselinkProvider(b); if (provider == null) { return; } LOG.debug("Adding new EclipseLink provider for bundle {}", b); PersistenceProvider proxiedProvider = new EclipseLinkPersistenceProvider(provider, b); Dictionary<String, Object> props = new Hashtable<String, Object>(); // NOSONAR props.put("org.apache.aries.jpa.container.weaving.packages", getJPAPackages(b)); props.put("javax.persistence.provider", ECLIPSELINK_JPA_PROVIDER_CLASS_NAME); ServiceRegistration<?> reg = context.registerService(PersistenceProvider.class, proxiedProvider, props); ServiceRegistration<?> old = registeredProviders.putIfAbsent(b, reg); if (old != null) { reg.unregister(); } }
/** * Initialize the EntityManagerFactory for the given configuration. * @throws javax.persistence.PersistenceException in case of JPA initialization errors */ @Override protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException { if (logger.isInfoEnabled()) { logger.info("Building JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } PersistenceProvider provider = getPersistenceProvider(); if (provider != null) { // Create EntityManagerFactory directly through PersistenceProvider. EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap()); if (emf == null) { throw new IllegalStateException( "PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" + getPersistenceUnitName() + "'"); } return emf; } else { // Let JPA perform its standard PersistenceProvider autodetection. return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap()); } }
@Override public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo unitInfo, Map properties) { if (properties == null) { properties = new HashMap<String, Object>(); } else { properties = new HashMap<String, Object>(properties); } PersistenceProvider nativePersistenceProvider = createNativePersistenceProvider(unitInfo, properties); if (nativePersistenceProvider == null) { return null; } EntityManagerFactory nativeFactory = nativePersistenceProvider.createContainerEntityManagerFactory(unitInfo, properties); List<String> ormXmlLocations = new ArrayList<String>(unitInfo.getMappingFileNames()); ormXmlLocations.add(DEFAULT_ORM_XML_LOCATION); Class<? extends SecurityContext> securityContextType = createSecurityContextType(unitInfo, properties); Class<? extends AccessRulesProvider> accessRulesProviderType = createAccessRulesProviderType(unitInfo, properties); return new SecureEntityManagerFactory(unitInfo.getPersistenceUnitName(), nativeFactory, ormXmlLocations, securityContextType, accessRulesProviderType); }
private PersistenceProvider createNativePersistenceProvider(String unitName, Map properties, XmlParser xmlParser) { String overriddenPersistenceProviderClassName = (String)properties.get(PERSISTENCE_PROVIDER_PROPERTY); if (isOtherPersistenceProvider(overriddenPersistenceProviderClassName)) { return null; } String persistenceProviderClassName = getPersistenceProviderClassName(unitName, xmlParser); if (isOtherPersistenceProvider(overriddenPersistenceProviderClassName, persistenceProviderClassName)) { return null; } String nativePersistenceProviderClassName = getNativePersistenceProviderClassName(unitName, overriddenPersistenceProviderClassName, persistenceProviderClassName, properties, xmlParser); properties.put(PERSISTENCE_PROVIDER_PROPERTY, nativePersistenceProviderClassName); return createNativePersistenceProvider(nativePersistenceProviderClassName); }
@Override public void start(BundleContext context) throws Exception { this.bundleContext = bundleContext; debugPrintln("Activating ..."); HibernatePersistence persistenceProvider = new HibernatePersistence(); Dictionary<String, String> props = new Hashtable<String, String>(); props.put(JAVAX_PERSISTENCE_PROVIDER_PROP, persistenceProvider .getClass().getName()); serviceRegistration = context .registerService(PersistenceProvider.class.getName(), persistenceProvider, props); debugPrintln("Service: ".concat(PersistenceProvider.class.getName()) .concat(" registered. Bundle activated.")); }
/** * Construit un {@link LocalContainerEntityManagerFactoryBean} à partir d'un ensemble d'options usuelles. */ public static LocalContainerEntityManagerFactoryBean entityManagerFactory(IJpaConfigurationProvider provider) { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); entityManagerFactoryBean.setJpaProperties(getJpaProperties(provider)); entityManagerFactoryBean.setDataSource(provider.getDataSource()); entityManagerFactoryBean.setPackagesToScan(getPackagesToScan(provider.getJpaPackageScanProviders())); PersistenceProvider persistenceProvider = provider.getPersistenceProvider(); if (persistenceProvider != null) { entityManagerFactoryBean.setPersistenceProvider(persistenceProvider); } return entityManagerFactoryBean; }
/** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public EntityManagerFactory createContainerEntityManagerFactory(final PersistenceUnitInfo info, final Map map) { initJpaCounter(); final PersistenceProvider persistenceProvider = findDelegate(map); // on surcharge PersistenceUnitInfo.getPersistenceProviderClassName() // pour retourner le PersistenceProvider délégué et pas nous même final PersistenceUnitInfo proxiedInfo = createPersistentUnitInfoProxy(info, persistenceProvider); final EntityManagerFactory entityManagerFactory = persistenceProvider .createContainerEntityManagerFactory(proxiedInfo, map); if (entityManagerFactory == null) { return null; } return JpaWrapper.createEntityManagerFactoryProxy(entityManagerFactory); }
private void guessDelegate() { // https://issues.apache.org/jira/browse/SIRONA-44 // https://github.com/javamelody/javamelody/issues/460 final List<PersistenceProvider> persistenceProviders = PersistenceProviderResolverHolder .getPersistenceProviderResolver().getPersistenceProviders(); for (final PersistenceProvider persistenceProvider : persistenceProviders) { if (!getClass().isInstance(persistenceProvider)) { delegate = persistenceProvider; break; } } if (delegate == null) { for (final String provider : PROVIDERS) { try { delegate = newPersistence(provider); break; } catch (final Throwable th2) { // NOPMD continue; } } if (delegate == null) { throw new IllegalStateException( new ClassNotFoundException("Can't find a delegate")); } } }
private void create(Bundle bundle, Context context) { Map.Entry<String, PersistenceProvider> pp = provider.get(context.definition.provider); // Do the registration of the service asynchronously. Since it may imply all kinds of // listening actions performed as a result of it, it may block the bundle handling. // However, indicate that we are in the process of the actions by // setting the used provider. context.usedProvider = pp.getKey(); new Thread(() -> { synchronized (context) { if (context.usedProvider != null) { PersistenceUnitInfo info = PersistenceUnitProcessor.getPersistenceUnitInfo(bundle, context.definition, pp.getValue()); context.factory = PersistenceUnitProcessor.createFactory(pp.getValue(), info); Hashtable<String, Object> props = new Hashtable<>(); props.put(EntityManagerFactoryBuilder.JPA_UNIT_NAME, context.definition.name); props.put(PersistenceUnitTransactionType.class.getName(), info.getTransactionType().name()); context.registration = bundle.getBundleContext().registerService( EntityManagerFactory.class, context.factory, props); } } }).start(); }
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { EntityManagerFactory emf = null; List<PersistenceProvider> providers = getProviders(); PersistenceProvider defaultProvider = null; for (PersistenceProvider provider : providers) { if (provider instanceof HibernatePersistence) { defaultProvider = provider; continue; } emf = provider.createEntityManagerFactory(persistenceUnitName, properties); if (emf != null) { break; } } if (emf == null && defaultProvider != null) emf = defaultProvider.createEntityManagerFactory( persistenceUnitName, properties ); if ( emf == null ) { throw new PersistenceException( "No Persistence provider for EntityManager named " + persistenceUnitName ); } return emf; }
@Override public URL getPersistenceUnitRootUrl() { // // Check if we have an override // PersistenceProvider pp = sourceBundle.bridge.persistenceProvider; if (pp instanceof JPABridgePersistenceProvider) { URL rootUrl = ((JPABridgePersistenceProvider) pp).getRootUrl(sourceBundle.bundle, location); return rootUrl; } // // Make one that is OSGi based // String loc = location; int n = loc.lastIndexOf('/'); if (n > 0) { loc = loc.substring(0, n); } if (loc.isEmpty()) loc = "/"; return sourceBundle.bundle.getResource(loc); }
/** * Create and close a dummy EMF to give the PersistenceProvider a chance to call * punit.addTransformer(). This has to occur as early as possible as weaving needs * to be done before the first entity class is loaded. So we can not wait till the * real DataSource is found. */ private void createAndCloseDummyEMF(PersistenceProvider provider) { DataSource dummyDataSource = new DummyDataSource(); punit.setJtaDataSource(dummyDataSource); punit.setNonJtaDataSource(dummyDataSource); try { EntityManagerFactory emf = provider.createContainerEntityManagerFactory(punit, null); emf.close(); } catch (Exception e) { LOGGER.debug("Error while creating the Dummy EntityManagerFactory to allow weaving.", e); } punit.setJtaDataSource(null); punit.setNonJtaDataSource(null); }
@Override public void removedService(ServiceReference<PersistenceProvider> reference, StoredPerProvider stored) { LOGGER.info("Lost provider for " + punit.getPersistenceUnitName() + " " + punit.getPersistenceProviderClassName()); try { stored.reg.unregister(); } catch (Exception e) { LOGGER.debug("An exception occurred unregistering a persistence unit {}", stored.builder.getPUName()); } if (stored.builder != null) { stored.builder.close(); } super.removedService(reference, stored); }
public AriesEntityManagerFactoryBuilder(BundleContext containerContext, PersistenceProvider provider, Bundle providerBundle, PersistenceUnit persistenceUnit) { this.provider = provider; this.providerBundle = providerBundle; this.persistenceUnit = persistenceUnit; this.containerContext = containerContext; this.originalTxType = persistenceUnit.getTransactionType(); this.bundle = persistenceUnit.getBundle(); this.driver = persistenceUnit.getProperties().getProperty(JAVAX_PERSISTENCE_JDBC_DRIVER); this.tracker = createDataSourceTracker(provider); // This must be done separately to avoid an immediate callback seeing the wrong state if(this.tracker != null) { this.tracker.open(); } registerManagedService(containerContext, persistenceUnit); }
@SuppressWarnings("unchecked") private static PersistenceProvider createEclipselinkProvider(Bundle b) { try { Class<? extends PersistenceProvider> providerClass = (Class<? extends PersistenceProvider>)b.loadClass(Activator.ECLIPSELINK_JPA_PROVIDER_CLASS_NAME); Constructor<? extends PersistenceProvider> con = providerClass.getConstructor(); return con.newInstance(); } catch (Exception e) { LOG.debug("Unable to load EclipseLink provider class. Ignoring bundle " + b.getSymbolicName(), e); return null; } }
@Override public void start(BundleContext context) throws Exception { emfResolver = new EMFBuilderServiceResolver(context); tracker = new ServiceTracker<PersistenceProvider, PersistenceProvider>(context, PersistenceProvider.class, null); tracker.open(); PersistenceProviderResolverHolder.setPersistenceProviderResolver(this); }
@Override public List<PersistenceProvider> getPersistenceProviders() { Collection<PersistenceProvider> services = tracker.getTracked().values(); List<PersistenceProvider> providers = new ArrayList<PersistenceProvider>(services.size() + 1); providers.add(emfResolver); providers.addAll(services); return providers; }
@Override public Future<EntityManagerFactory> getEntityManagerFactory(String datasourceName) { Properties properties = createProperties(); PersistenceProvider provider = new HibernatePersistenceProvider(); SmartPersistanceUnitInfo persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(datasourceName); persistenceUnitInfo.setProperties(properties); // Using RESOURCE_LOCAL for manage transactions on DAO side. persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL); Map<Object, Object> configuration = new HashMap<>(); properties.entrySet().stream().forEach(e -> configuration.put(e.getKey(), e.getValue())); synchronized (vertx) { Future<EntityManagerFactory> future = Future.future(); vertx.executeBlocking(f1 -> { config.getJsonArray("annotated_classes", new JsonArray()).stream() .forEach(p -> scanAnnotatedClasses(p.toString(), persistenceUnitInfo)); EntityManagerFactory emf = provider.createContainerEntityManagerFactory(persistenceUnitInfo, configuration); future.complete(emf); }, future.completer()); return future; } }
public Object getProviderSpecificConfigurationObject( PersistenceProvider persistenceProvider) { if (!(persistenceProvider instanceof UnitilsHibernatePersistenceProvider)) { throw new UnitilsException("Make sure that the persistence provider that is used is an instance of " + UnitilsHibernatePersistenceProvider.class.getSimpleName()); } UnitilsHibernatePersistenceProvider hibernatePersistenceProvider = (UnitilsHibernatePersistenceProvider) persistenceProvider; return hibernatePersistenceProvider.getHibernateConfiguration(); }
public EntityManagerFactory getEmf() { Bundle thisBundle = FrameworkUtil.getBundle( EmfUtil.class ); BundleContext context = thisBundle.getBundleContext(); ServiceReference[] refs = null; try { refs = context.getServiceReferences( EntityManagerFactory.class.getName(), "(osgi.unit.name=pluginsPUnit)" ); } catch ( Exception isEx ) { throw new IllegalStateException( "Filter error", isEx ); } if ( refs != null ) { emf = ( EntityManagerFactory ) context.getService( refs[0] ); } if ( emf == null ) { ServiceReference serviceReference = context.getServiceReference( PersistenceProvider.class.getName() ); PersistenceProvider persistenceProvider = ( PersistenceProvider ) context.getService( serviceReference ); emf = persistenceProvider.createEntityManagerFactory( "pluginsPUnit", null ); } return emf; }
private Map<String, String> createPersistenceProviderProperty(Map<String, String> properties, PersistenceProvider persistenceProvider) { if (properties == null) { return Collections.singletonMap(PERSISTENCE_PROVIDER_PROPERTY, persistenceProvider.getClass().getName()); } else { properties = new HashMap<String, String>(properties); properties.put(PERSISTENCE_PROVIDER_PROPERTY, persistenceProvider.getClass().getName()); return properties; } }
public void generateSchema(PersistenceUnitInfo unitInfo, Map properties) { if (properties == null) { properties = new HashMap(); } else { properties = new HashMap<String, Object>(properties); } PersistenceProvider nativePersistenceProvider = createNativePersistenceProvider(unitInfo, properties); if (nativePersistenceProvider == null) { return; } nativePersistenceProvider.generateSchema(unitInfo, properties); }
public boolean generateSchema(String unitName, Map properties) { if (properties == null) { properties = new HashMap(); } else { properties = new HashMap<String, Object>(properties); } PersistenceProvider nativePersistenceProvider = createNativePersistenceProvider(unitName, properties); if (nativePersistenceProvider == null) { return false; } return nativePersistenceProvider.generateSchema(unitName, properties); }
private PersistenceProvider createNativePersistenceProvider(PersistenceUnitInfo persistenceUnitInfo, Map properties) { String overriddenPersistenceProviderClassName = (String)properties.get(PERSISTENCE_PROVIDER_PROPERTY); if (isOtherPersistenceProvider(overriddenPersistenceProviderClassName)) { return null; } String persistenceProviderClassName = persistenceUnitInfo.getPersistenceProviderClassName(); if (isOtherPersistenceProvider(overriddenPersistenceProviderClassName, persistenceProviderClassName)) { return null; } String nativePersistenceProviderClassName = getNativePersistenceProviderClassName(persistenceUnitInfo, overriddenPersistenceProviderClassName, properties); try { if (nativePersistenceProviderClassName == null || nativePersistenceProviderClassName.equals(SecurePersistenceProvider.class.getName())) { throw new PersistenceException( "No persistence provider specified for " + SecureEntityManagerFactory.class.getName() + ". " + "Specify its class name via property \"" + NATIVE_PERSISTENCE_PROVIDER_PROPERTY + "\""); } Class<?> persistenceProviderClass = getClassLoader(persistenceUnitInfo).loadClass(nativePersistenceProviderClassName); properties.put(PERSISTENCE_PROVIDER_PROPERTY, nativePersistenceProviderClassName); return (PersistenceProvider)persistenceProviderClass.newInstance(); } catch (ReflectiveOperationException e) { throw new PersistenceException(e); } }
private PersistenceProvider createNativePersistenceProvider(String unitName, Map properties) { try { Enumeration<URL> persistenceXmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml"); XmlParser parser = new XmlParser(Collections.list(persistenceXmls)); return createNativePersistenceProvider(unitName, properties, parser); } catch (Exception e) { LOG.log(Level.WARNING, "Could not initialize xml parser", e); return null; } }
private PersistenceProvider createNativePersistenceProvider(String persistenceProviderClassName) { try { if (persistenceProviderClassName == null || persistenceProviderClassName.equals(SecurePersistenceProvider.class.getName())) { throw new PersistenceException( "No persistence provider specified for " + SecureEntityManagerFactory.class.getName() + ". " + "Specify its class name via property \"" + NATIVE_PERSISTENCE_PROVIDER_PROPERTY + "\""); } Class<?> persistenceProviderClass = Thread.currentThread().getContextClassLoader().loadClass(persistenceProviderClassName); return (PersistenceProvider)persistenceProviderClass.newInstance(); } catch (ReflectiveOperationException e) { throw new PersistenceException(e); } }
/** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public EntityManagerFactory createEntityManagerFactory(final String unit, final Map map) { initJpaCounter(); final PersistenceProvider persistenceProvider = findDelegate(map); final ClassLoader tccl = tccl(); final ClassLoader hack = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // pour findbugs /** {@inheritDoc} */ @Override public ClassLoader run() { return new JpaOverridePersistenceXmlClassLoader(tccl, persistenceProvider.getClass().getName()); } }); Thread.currentThread().setContextClassLoader(hack); try { final EntityManagerFactory entityManagerFactory = persistenceProvider .createEntityManagerFactory(unit, map); if (entityManagerFactory == null) { return null; } return JpaWrapper.createEntityManagerFactoryProxy(entityManagerFactory); } finally { Thread.currentThread().setContextClassLoader(tccl); } }
/** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public void generateSchema(final PersistenceUnitInfo info, final Map map) { final PersistenceProvider persistenceProvider = findDelegate(map); persistenceProvider.generateSchema(info, map); }
/** {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public boolean generateSchema(final String persistenceUnitName, final Map map) { final PersistenceProvider persistenceProvider = findDelegate(map); return persistenceProvider.generateSchema(persistenceUnitName, map); }
/** * Test de JpaPersistence. */ @Test public void testJpaPersistence() { final PersistenceProvider jpaPersistence = getJpaPersistence(); final ProviderUtil providerUtil = jpaPersistence.getProviderUtil(); assertNotNull("getProviderUtil", providerUtil); // providerUtil == JpaPersistence.DUMMY_PROVIDER_UTIL providerUtil.isLoadedWithoutReference(null, null); providerUtil.isLoadedWithReference(null, null); providerUtil.isLoaded(null); }