Java 类javax.persistence.spi.PersistenceUnitInfo 实例源码

项目:spring-cloud-skipper    文件:SchemaGenerationTests.java   
@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");

}
项目:testee.fi    文件:JpaInjectionServicesImpl.java   
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);
    }
}
项目:lams    文件:DefaultPersistenceUnitManager.java   
@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;
}
项目:jk-db    文件:JKDefaultDataSource.java   
@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;
}
项目:spring4-understanding    文件:DefaultPersistenceUnitManager.java   
@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;
}
项目:spring4-understanding    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:spring4-understanding    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:spring4-understanding    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:spring4-understanding    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:cibet    文件:Provider.java   
@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;
   }
}
项目:cibet    文件:Provider.java   
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);
   }
}
项目:cibet    文件:Provider.java   
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);
      }
   }

}
项目:cibet    文件:JdbcBridgeProvider.java   
@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;
   }
}
项目:cibet    文件:JdbcBridgeProvider.java   
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();
}
项目:jpasecurity    文件:SecurePersistenceProvider.java   
@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);
}
项目:jpasecurity    文件:SecurePersistenceProvider.java   
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);
    }
}
项目:jpasecurity    文件:SecurePersistenceProvider.java   
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);
    }
}
项目:spring-cloud-dataflow    文件:SchemaGenerationTests.java   
@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");

}
项目:metaworks_framework    文件:MergePersistenceUnitManager.java   
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;
}
项目:SparkCommerce    文件:MergePersistenceUnitManager.java   
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;
}
项目:owsi-core-parent    文件:InterceptorAwareHibernatePersistenceProvider.java   
/**
 * 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();
}
项目:javamelody    文件:JpaPersistence.java   
/** {@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);
}
项目:high-performance-java-persistence    文件:AbstractJPAProgrammaticBootstrapTest.java   
@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
    );
}
项目:osgi.ee    文件:JpaBundleChangeListener.java   
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();
}
项目:class-guard    文件:DefaultPersistenceUnitManager.java   
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;
}
项目:class-guard    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:class-guard    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:class-guard    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:class-guard    文件:PersistenceXmlParsingTests.java   
@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());
}
项目:mobile-starting-framework    文件:HomeController.java   
/**
 * 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);
}
项目:HotswapAgent    文件:EntityManagerFactoryProxy.java   
/**
 * 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);
        }
    }
}
项目:HotswapAgent    文件:Hibernate3JPAHelper.java   
/**
 * 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;
}
项目:HotswapAgent    文件:HibernatePersistenceHelper.java   
/**
 * @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;
}
项目:HotswapAgent    文件:EntityManagerFactoryProxy.java   
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);
        }
    }
}
项目:HotswapAgent    文件:EntityManagerFactoryProxy.java   
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);
    }
}
项目:bundles    文件:DatanucleusWrapper.java   
@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);
}
项目:bundles    文件:HibernateBridge.java   
@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);
    }
}
项目:testee.fi    文件:JpaInjectionServicesImpl.java   
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));
}
项目:testee.fi    文件:PlaygroundPersistenceProvider.java   
@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;
}
项目:aries-jpa    文件:AriesEntityManagerFactoryBuilder.java   
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);
}