Java Code Examples for javax.persistence.spi.PersistenceUnitInfo

The following are top voted examples for showing how to use javax.persistence.spi.PersistenceUnitInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: high-performance-java-persistence   File: AbstractJPAProgrammaticBootstrapTest.java   View source code 7 votes vote down vote up
@Before
public void init() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());

    Map<String, Object> configuration = new HashMap<>();

    Integrator integrator = integrator();
    if (integrator != null) {
        configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
    }

    emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
        persistenceUnitInfo,
        configuration
    );
}
 
Example 2
Project: spring-cloud-skipper   File: SchemaGenerationTests.java   View source code 6 votes vote down vote up
@Test
public void generateSchemaDdlFiles() throws Exception {

	final PersistenceUnitInfo persistenceUnitInfo = fb.getPersistenceUnitInfo();
	final File tempDir = Files.createTempDirectory("skipper-sql-").toFile();
	final List<String> supportedHibernateDialects = new ArrayList<>();

	supportedHibernateDialects.add("H2");
	supportedHibernateDialects.add("HSQL");
	supportedHibernateDialects.add("MySQL5");
	supportedHibernateDialects.add("Oracle10g");
	supportedHibernateDialects.add("PostgreSQL94");
	supportedHibernateDialects.add("DB2");
	supportedHibernateDialects.add("SQLServer2012");

	logger.info(
		"\n\nGenerating DDL scripts for the following dialects:\n\n"
			+ supportedHibernateDialects.stream().map((db) -> db + "Dialect").collect(Collectors.joining("\n")) + "\n");

	for (String supportedHibernateDialect : supportedHibernateDialects) {
		generateDdlFiles(supportedHibernateDialect, tempDir, persistenceUnitInfo);
	}

	logger.info("\n\nYou can find the DDL scripts in directory: " + tempDir.getAbsolutePath() + "\n");

}
 
Example 3
Project: testee.fi   File: JpaInjectionServicesImpl.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 4
Project: lams   File: DefaultPersistenceUnitManager.java   View source code 6 votes vote down vote up
@Override
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
	if (this.persistenceUnitInfoNames.isEmpty()) {
		throw new IllegalStateException("No persistence units parsed from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations));
	}
	if (this.persistenceUnitInfos.isEmpty()) {
		throw new IllegalStateException("All persistence units from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations) + " already obtained");
	}
	if (this.persistenceUnitInfos.size() > 1) {
		return obtainPersistenceUnitInfo(this.defaultPersistenceUnitName);
	}
	PersistenceUnitInfo pui = this.persistenceUnitInfos.values().iterator().next();
	this.persistenceUnitInfos.clear();
	return pui;
}
 
Example 5
Project: jk-db   File: JKDefaultDataSource.java   View source code 6 votes vote down vote up
@Override
public EntityManagerFactory getEntityManagerFactory(String name) {
	logger.debug("getEntityManagerFactory() ", name);
	EntityManagerFactory emf = getCache().get(name, EntityManagerFactory.class);
	if (emf == null) {
		logger.debug("EMF not loaded, loading now...");
		Properties prop = new Properties();
		prop.setProperty(JKPersistenceUnitProperties.JDBC_DRIVER, getDriverName());
		prop.setProperty(JKPersistenceUnitProperties.JDBC_PASSWORD, getPassword());
		prop.setProperty(JKPersistenceUnitProperties.JDBC_URL, getDatabaseUrl());
		prop.setProperty(JKPersistenceUnitProperties.JDBC_USER, getUsername());
		PersistenceUnitInfo persisitnceUnitInfo = getPersisitnceUnitInfo(name, prop, getEntitiesPackages());
		emf = JKEntityManagerFactory.createEntityManagerFactory(persisitnceUnitInfo);
		logger.debug("add to emf cache ");
		getCache().cache(name, emf, EntityManagerFactory.class);
	}
	return emf;
}
 
Example 6
Project: spring4-understanding   File: DefaultPersistenceUnitManager.java   View source code 6 votes vote down vote up
@Override
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
	if (this.persistenceUnitInfoNames.isEmpty()) {
		throw new IllegalStateException("No persistence units parsed from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations));
	}
	if (this.persistenceUnitInfos.isEmpty()) {
		throw new IllegalStateException("All persistence units from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations) + " already obtained");
	}
	if (this.persistenceUnitInfos.size() > 1) {
		return obtainPersistenceUnitInfo(this.defaultPersistenceUnitName);
	}
	PersistenceUnitInfo pui = this.persistenceUnitInfos.values().iterator().next();
	this.persistenceUnitInfos.clear();
	return pui;
}
 
Example 7
Project: spring4-understanding   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 8
Project: spring4-understanding   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample2() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);

	assertEquals("OrderManagement2", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 9
Project: spring4-understanding   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample3() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement3", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals(0, info[0].getProperties().keySet().size());
	assertNull(info[0].getJtaDataSource());
	assertNull(info[0].getNonJtaDataSource());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 10
Project: spring4-understanding   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample5() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example5.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement5", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getMappingFileNames().size());
	assertEquals("order1.xml", info[0].getMappingFileNames().get(0));
	assertEquals("order2.xml", info[0].getMappingFileNames().get(1));

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName());
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 11
Project: cibet   File: Provider.java   View source code 6 votes vote down vote up
@Override
public EntityManagerFactory createEntityManagerFactory(String unitName, Map map) {
   PersistenceUnitInfo info = createPersistenceUnitInfo(unitName);
   if (info == null) {
      log.info("no persistence unit found with name " + unitName);
      return null;
   }

   if (getClass().getName().equals(info.getPersistenceProviderClassName())
         || (map != null && getClass().getName().equals(map.get(PERSISTENCE_PROVIDER_PROPERTY)))) {
      log.info("create resource_local EntityManagerFactory");
      logInfo(info, map);

      boolean loadEager = isLoadEager(info, map);
      persistenceProvider = createNativePersistenceProvider(info, map);
      map = createPersistenceProviderProperty(map, persistenceProvider);
      EntityManagerFactory nativeEntityManagerFactory = persistenceProvider.createEntityManagerFactory(unitName,
            map);
      return new CibetEntityManagerFactory(nativeEntityManagerFactory, loadEager);
   } else {
      log.debug(this.getClass().getName() + " does not match provider for persistence unit " + unitName);
      return null;
   }
}
 
Example 12
Project: cibet   File: Provider.java   View source code 6 votes vote down vote up
protected PersistenceUnitInfo createPersistenceUnitInfo(String persistenceUnitName) {
   try {
      PersistenceXmlParser persistenceXmlParser = new PersistenceXmlParser();
      for (Enumeration<URL> persistenceFiles = Thread.currentThread().getContextClassLoader()
            .getResources(PERSISTENCE_FILE); persistenceFiles.hasMoreElements();) {
         URL persistenceFile = persistenceFiles.nextElement();
         persistenceXmlParser.parse(persistenceFile);
         if (persistenceXmlParser.containsPersistenceUnitInfo(persistenceUnitName)) {
            PersistenceUnitInfo persistenceUnitInfo = persistenceXmlParser
                  .getPersistenceUnitInfo(persistenceUnitName);
            return persistenceUnitInfo;
         }
      }
      return null;
   } catch (IOException e) {
      throw new PersistenceException(e);
   }
}
 
Example 13
Project: cibet   File: Provider.java   View source code 6 votes vote down vote up
protected void logInfo(PersistenceUnitInfo info, Map map) {
   if (log.isDebugEnabled()) {
      if (map != null && map.size() > 0) {
         log.debug(this + " properties: ---------------------");
         Iterator<Map.Entry<?, ?>> it = map.entrySet().iterator();
         while (it.hasNext()) {
            Map.Entry<?, ?> entry = it.next();
            log.debug(entry.getKey() + " = " + entry.getValue());
         }
      }

      if (log.isDebugEnabled()) {
         log.debug("PersistenceUnitInfo properties: ---------------------");
         log.debug(info);
      }
   }

}
 
Example 14
Project: cibet   File: JdbcBridgeProvider.java   View source code 6 votes vote down vote up
@Override
public EntityManagerFactory createEntityManagerFactory(String unitName, Map map) {
   registerCibetDriver();

   PersistenceUnitInfo info = createPersistenceUnitInfo(unitName);
   if (info == null) {
      log.info("no persistence unit found with name " + unitName);
      return null;
   }

   if (getClass().getName().equals(info.getPersistenceProviderClassName())
         || (map != null && getClass().getName().equals(map.get(PERSISTENCE_PROVIDER_PROPERTY)))) {
      log.info("create resource-local JdbcBridgeEntityManagerFactory");
      logInfo(info, map);

      return new JdbcBridgeEntityManagerFactory(resolveDataSource(info));

   } else {
      log.debug(this.getClass().getName() + " does not match provider for persistence unit " + unitName);
      return null;
   }
}
 
Example 15
Project: cibet   File: JdbcBridgeProvider.java   View source code 6 votes vote down vote up
private DataSource resolveDataSource(PersistenceUnitInfo info) {
   String url = null;
   String user = null;
   String password = null;

   if (info.getProperties().containsKey(HIBERNATE_URL)) {
      url = info.getProperties().getProperty(HIBERNATE_URL);
      user = info.getProperties().getProperty(HIBERNATE_USER);
      password = info.getProperties().getProperty(HIBERNATE_PASSWORD);
      return new DefaultDataSource(url, user, password);
   }

   if (info.getProperties().containsKey(JAVAX_URL)) {
      url = info.getProperties().getProperty(JAVAX_URL);
      user = info.getProperties().getProperty(JAVAX_USER);
      password = info.getProperties().getProperty(JAVAX_PASSWORD);
      return new DefaultDataSource(url, user, password);
   }

   return info.getNonJtaDataSource();
}
 
Example 16
Project: jpasecurity   File: SecurePersistenceProvider.java   View source code 6 votes vote down vote up
@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);
}
 
Example 17
Project: jpasecurity   File: SecurePersistenceProvider.java   View source code 6 votes vote down vote up
private Class<? extends SecurityContext> createSecurityContextType(PersistenceUnitInfo persistenceUnitInfo,
                                                                   Map properties) {
    String securityContextClassName = (String)properties.get(SECURITY_CONTEXT_PROPERTY);
    if (securityContextClassName == null) {
        securityContextClassName = (String)persistenceUnitInfo.getProperties().get(SECURITY_CONTEXT_PROPERTY);
    }
    if (securityContextClassName == null) {
        securityContextClassName = DEFAULT_SECURITY_CONTEXT_PROPERTY;
    }
    try {
        return (Class<? extends SecurityContext>)getClassLoader(persistenceUnitInfo)
                .loadClass(securityContextClassName);
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    }
}
 
Example 18
Project: jpasecurity   File: SecurePersistenceProvider.java   View source code 6 votes vote down vote up
private Class<? extends AccessRulesProvider> createAccessRulesProviderType(PersistenceUnitInfo persistenceUnitInfo,
                                                                           Map properties) {
    String accessRulesProviderClassName = (String)properties.get(ACCESS_RULES_PROVIDER_PROPERTY);
    if (accessRulesProviderClassName == null) {
        accessRulesProviderClassName
            = (String)persistenceUnitInfo.getProperties().get(ACCESS_RULES_PROVIDER_PROPERTY);
    }
    if (accessRulesProviderClassName == null) {
        accessRulesProviderClassName = DEFAULT_ACCESS_RULES_PROVIDER_CLASS;
    }
    try {
        return (Class<? extends AccessRulesProvider>)getClassLoader(persistenceUnitInfo)
                .loadClass(accessRulesProviderClassName);
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    }
}
 
Example 19
Project: spring-cloud-dataflow   File: SchemaGenerationTests.java   View source code 6 votes vote down vote up
@Test
public void generateSchemaDdlFiles() throws Exception {

	final PersistenceUnitInfo persistenceUnitInfo = fb.getPersistenceUnitInfo();
	final File tempDir = Files.createTempDirectory("scdf-sql-").toFile();
	final List<String> supportedHibernateDialects = new ArrayList<>();

	supportedHibernateDialects.add("H2");
	supportedHibernateDialects.add("HSQL");
	supportedHibernateDialects.add("MySQL5");
	supportedHibernateDialects.add("Oracle10g");
	supportedHibernateDialects.add("PostgreSQL94");
	supportedHibernateDialects.add("DB2");
	supportedHibernateDialects.add("SQLServer2012");

	logger.info(
		"\n\nGenerating DDL scripts for the following dialects:\n\n"
			+ supportedHibernateDialects.stream().map((db) -> db + "Dialect").collect(Collectors.joining("\n")) + "\n");

	for (String supportedHibernateDialect : supportedHibernateDialects) {
		generateDdlFiles(supportedHibernateDialect, tempDir, persistenceUnitInfo);
	}

	logger.info("\n\nYou can find the DDL scripts in directory: " + tempDir.getAbsolutePath() + "\n");

}
 
Example 20
Project: metaworks_framework   File: MergePersistenceUnitManager.java   View source code 6 votes vote down vote up
private PersistenceUnitInfo createPersistenceUnit(PersistenceUnitInfo mPui) throws IllegalArgumentException, SecurityException {
    InvocationHandler jpa2PersistenceUnitInfoDecorator = null;
    Class<?>[] classes = getClass().getSuperclass().getDeclaredClasses();
    for (Class<?> clz : classes) {
        if ("org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager$Jpa2PersistenceUnitInfoDecorator".equals(clz.getName())) {
            Constructor<?> constructor;
            try {
                constructor = clz.getConstructor(Class.forName("org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo"));
                constructor.setAccessible(true);
                jpa2PersistenceUnitInfoDecorator = (InvocationHandler) constructor.newInstance(mPui);
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
            break;
        }
    }

    PersistenceUnitInfo puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
            new Class[] { SmartPersistenceUnitInfo.class }, jpa2PersistenceUnitInfoDecorator);
    return puiToStore;
}
 
Example 21
Project: SparkCommerce   File: MergePersistenceUnitManager.java   View source code 6 votes vote down vote up
private PersistenceUnitInfo createPersistenceUnit(PersistenceUnitInfo mPui) throws IllegalArgumentException, SecurityException {
    InvocationHandler jpa2PersistenceUnitInfoDecorator = null;
    Class<?>[] classes = getClass().getSuperclass().getDeclaredClasses();
    for (Class<?> clz : classes) {
        if ("org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager$Jpa2PersistenceUnitInfoDecorator".equals(clz.getName())) {
            Constructor<?> constructor;
            try {
                constructor = clz.getConstructor(Class.forName("org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo"));
                constructor.setAccessible(true);
                jpa2PersistenceUnitInfoDecorator = (InvocationHandler) constructor.newInstance(mPui);
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
            break;
        }
    }

    PersistenceUnitInfo puiToStore = (PersistenceUnitInfo) Proxy.newProxyInstance(SmartPersistenceUnitInfo.class.getClassLoader(),
            new Class[] { SmartPersistenceUnitInfo.class }, jpa2PersistenceUnitInfoDecorator);
    return puiToStore;
}
 
Example 22
Project: owsi-core-parent   File: InterceptorAwareHibernatePersistenceProvider.java   View source code 6 votes vote down vote up
/**
 * 2017-05-24 · reworked from SpringHibernateJpaPersistenceProvider so that we can inject a custom
 * {@link EntityManagerFactoryBuilderImpl}; previous implementation that overrides
 * {@link InterceptorAwareHibernatePersistenceProvider#getEntityManagerFactoryBuilder} no longer works
 * as there are several paths with various arguments and the overloaded one was no longer called.
 */
@Override
@SuppressWarnings("rawtypes")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(info), properties) {
		@Override
		protected void populate(SessionFactoryBuilder sfBuilder, StandardServiceRegistry ssr) {
			super.populate(sfBuilder, ssr);
			
			if (InterceptorAwareHibernatePersistenceProvider.this.interceptor != null) {
				LOGGER.warn("Installing our Spring managed interceptor.");
				sfBuilder.applyInterceptor(InterceptorAwareHibernatePersistenceProvider.this.interceptor);
			}
		}
	}.build();
}
 
Example 23
Project: javamelody   File: JpaPersistence.java   View source code 6 votes vote down vote up
/** {@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);
}
 
Example 24
Project: osgi.ee   File: JpaBundleChangeListener.java   View source code 6 votes vote down vote up
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();
}
 
Example 25
Project: class-guard   File: DefaultPersistenceUnitManager.java   View source code 6 votes vote down vote up
public PersistenceUnitInfo obtainDefaultPersistenceUnitInfo() {
	if (this.persistenceUnitInfoNames.isEmpty()) {
		throw new IllegalStateException("No persistence units parsed from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations));
	}
	if (this.persistenceUnitInfos.isEmpty()) {
		throw new IllegalStateException("All persistence units from " +
				ObjectUtils.nullSafeToString(this.persistenceXmlLocations) + " already obtained");
	}
	if (this.persistenceUnitInfos.size() > 1) {
		return obtainPersistenceUnitInfo(this.defaultPersistenceUnitName);
	}
	PersistenceUnitInfo pui = this.persistenceUnitInfos.values().iterator().next();
	this.persistenceUnitInfos.clear();
	return pui;
}
 
Example 26
Project: class-guard   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testMetaInfCase() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/META-INF/persistence.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 27
Project: class-guard   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample2() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example2.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);

	assertEquals("OrderManagement2", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("mappings.xml", info[0].getMappingFileNames().get(0));
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 28
Project: class-guard   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample3() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example3.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement3", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals(0, info[0].getProperties().keySet().size());
	assertNull(info[0].getJtaDataSource());
	assertNull(info[0].getNonJtaDataSource());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 29
Project: class-guard   File: PersistenceXmlParsingTests.java   View source code 6 votes vote down vote up
@Test
public void testExample5() throws Exception {
	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example5.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement5", info[0].getPersistenceUnitName());

	assertEquals(2, info[0].getMappingFileNames().size());
	assertEquals("order1.xml", info[0].getMappingFileNames().get(0));
	assertEquals("order2.xml", info[0].getMappingFileNames().get(1));

	assertEquals(2, info[0].getJarFileUrls().size());
	assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0));
	assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1));

	assertEquals("com.acme.AcmePersistence", info[0].getPersistenceProviderClassName());
	assertEquals(0, info[0].getProperties().keySet().size());

	assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses());
}
 
Example 30
Project: mobile-starting-framework   File: HomeController.java   View source code 6 votes vote down vote up
/**
 * Controller method to download a ddl.
 */
@Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
@RequestMapping(value = "ddl", method = RequestMethod.GET)
public void exportDatabaseSchema(HttpServletRequest request, HttpServletResponse response, Model uiModel) {
	PersistenceUnitInfo persistenceUnitInfo = getEntityManagerFactory().getPersistenceUnitInfo();

	Map jpaPropertyMap = getEntityManagerFactory().getJpaPropertyMap();
	jpaPropertyMap.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
	Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap).getHibernateConfiguration();

	SchemaExport schema = new SchemaExport(configuration);
	schema.setFormat(true);
	schema.setDelimiter(";");
	schema.setOutputFile("/tmp/schema.sql");
	schema.create(false, false);
}
 
Example 31
Project: HotswapAgent   File: EntityManagerFactoryProxy.java   View source code 6 votes vote down vote up
/**
 * Refresh proxied factory version43 or greater.
 */
public void refreshProxiedFactoryVersion43OrGreater() {
    if (info == null) {
        currentInstance = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
    } else {
        try {
            Class<?> bootstrapClazz = loadClass("org.hibernate.jpa.boot.spi.Bootstrap");
            Class<?> builderClazz = loadClass("org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder");

            Object builder = ReflectionHelper.invoke(null, bootstrapClazz, "getEntityManagerFactoryBuilder",
                    new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);

            currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builderClazz, "build",
                    new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Unable to reload persistence unit {}", info, e);
        }
    }
}
 
Example 32
Project: HotswapAgent   File: Hibernate3JPAHelper.java   View source code 6 votes vote down vote up
/**
 * Creates the container entity manager factory proxy.
 *
 * @param info            persistent unit definition
 * @param properties            properties to create entity manager factory
 * @param original            entity manager factory
 * @return proxy of entity manager
 */
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(PersistenceUnitInfo info,
		Map<?,?> properties, EntityManagerFactory original) {
	// ensure only once
	if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName())){
		return original;
	}
	wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());

	EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
	EntityManagerFactory proxy = wrapper.proxy(original, info.getPersistenceUnitName(), info, properties);

	initPlugin(original);

	LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(),
			original);
	return proxy;
}
 
Example 33
Project: HotswapAgent   File: HibernatePersistenceHelper.java   View source code 6 votes vote down vote up
/**
 * @param info       persistent unit definition
 * @param properties properties to create entity manager factory
 * @param original   entity manager factory
 * @return proxy of entity manager
 */
public static EntityManagerFactory createContainerEntityManagerFactoryProxy(Object builder, PersistenceUnitInfo info, Map properties,
                                                                            EntityManagerFactory original) {
    // ensure only once
    if (wrappedPersistenceUnitNames.contains(info.getPersistenceUnitName()))
        return original;
    wrappedPersistenceUnitNames.add(info.getPersistenceUnitName());

    EntityManagerFactoryProxy wrapper = EntityManagerFactoryProxy.getWrapper(info.getPersistenceUnitName());
    EntityManagerFactory proxy = wrapper.proxy(builder, original, info.getPersistenceUnitName(), info, properties);

    initPlugin(original);

    LOGGER.debug("Returning container EntityManager proxy {} instead of EntityManager {}", proxy.getClass(), original);
    return proxy;
}
 
Example 34
Project: HotswapAgent   File: EntityManagerFactoryProxy.java   View source code 6 votes vote down vote up
public void refreshProxiedFactoryVersion43OrGreater() {
    if (info == null) {
        currentInstance = Persistence.createEntityManagerFactory(persistenceUnitName, properties);
    } else {
        try {
            Class bootstrapClazz = loadClass("org.hibernate.jpa.boot.spi.Bootstrap");
            Class builderClazz = loadClass("org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder");

            Object builder = ReflectionHelper.invoke(null, bootstrapClazz, "getEntityManagerFactoryBuilder",
                    new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);

            currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(builder, builderClazz, "build",
                    new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Unable to reload persistence unit {}", info, e);
        }
    }
}
 
Example 35
Project: HotswapAgent   File: EntityManagerFactoryProxy.java   View source code 6 votes vote down vote up
private void buildFreshEntityManagerFactory() {
    try {
        Class ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
        LOGGER.trace("new Ejb3Configuration()");
        Object cfg = ejb3ConfigurationClazz.newInstance();

        LOGGER.trace("cfg.configure( info, properties );");

        if (info != null) {
            ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
                    new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
        }
        else {
            ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
                    new Class[]{String.class, Map.class}, persistenceUnitName, properties);
        }

        LOGGER.trace("configured.buildEntityManagerFactory()");
        currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
                new Class[]{});


    } catch (Exception e) {
        LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
    }
}
 
Example 36
Project: bundles   File: DatanucleusWrapper.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	properties.put("datanucleus.jpa.addClassTransformer", "false");
	properties.put("datanucleus.plugin.pluginRegistryClassName", "org.datanucleus.plugin.OSGiPluginRegistry");

	info.addTransformer(new ClassTransformer() {

		@Override
		public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
				ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

			// TODO Auto-generated method stub
			return null;
		}
	});
	return pp.createContainerEntityManagerFactory(info, properties);
}
 
Example 37
Project: bundles   File: HibernateBridge.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
	ClassLoader previous = Thread.currentThread().getContextClassLoader();
	try {
		//
		// This is necessary to ensure the imports?
		//
		info.addTransformer(null);

		Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
		properties.put("hibernate.jdbc.use_get_generated_keys", "true");
		properties.put("hibernate.hbm2ddl.auto", "create");
		final EntityManagerFactory emf = pp.createContainerEntityManagerFactory(info, properties);
		return new DelegatedEntityManagerFactory(emf) {

		};
	} finally {
		Thread.currentThread().setContextClassLoader(previous);
	}
}
 
Example 38
Project: testee.fi   File: JpaInjectionServicesImpl.java   View source code 5 votes vote down vote up
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(final String unitName) {
    LOG.debug("Creating persistence context for unit '{}'", unitName);
    final PersistenceUnitInfo unit = persistenceUnitDiscovery.findByUnitName(unitName);
    if (unit == null) {
        throw new IllegalStateException("Unknown persistence unit: " + unitName);
    }
    final EntityManager entityManager = ProxyUtils.lazy(
            () -> getEntityManager(unit),
            EntityManager.class
    );
    return () -> new SimpleResourceReference<>(safeguard(entityManager));
}
 
Example 39
Project: testee.fi   File: PlaygroundPersistenceProvider.java   View source code 5 votes vote down vote up
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
    final EntityManagerFactory emf = mock(EntityManagerFactory.class);
    final EntityManager em = mock(EntityManager.class);
    when(emf.createEntityManager()).thenReturn(em);
    final EntityTransaction tx = mock(EntityTransaction.class);
    when(em.getTransaction()).thenReturn(tx);
    return emf;
}
 
Example 40
Project: aries-jpa   File: AriesEntityManagerFactoryBuilder.java   View source code 5 votes vote down vote up
private void registerManagedService(BundleContext containerContext, PersistenceUnitInfo persistenceUnit) {
	Dictionary<String, Object> configuration = new Hashtable<String, Object>(); // NOSONAR
	configuration.put(Constants.SERVICE_PID, JPA_CONFIGURATION_PREFIX + persistenceUnit.getPersistenceUnitName());
	configReg = containerContext.registerService(ManagedService.class, 
			new ManagedEMF(this, persistenceUnit.getPersistenceUnitName()), configuration);
}