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

项目:aries-jpa    文件:JPAHandler.java   
@Override
public void startElement(String uri, String localName, String name, Attributes attributes)
    throws SAXException {
    // Do this setting first as we use it later.
    elementName = (localName == null || "".equals(localName)) ? name : localName;

    if ("persistence-unit".equals(elementName)) {
        String tranTypeSt = attributes.getValue("transaction-type");
        PersistenceUnitTransactionType tranType = tranTypeSt == null ? null : PersistenceUnitTransactionType.valueOf(tranTypeSt);
        persistenceUnits.push(new PersistenceUnit(bundle, 
                                                  attributes.getValue("name"), 
                                                  tranType));
    } else if ("exclude-unlisted-classes".equals(elementName))
        persistenceUnits.peek().setExcludeUnlisted(true);
    else if ("property".equals(elementName))
        persistenceUnits.peek().addProperty(attributes.getValue("name"), attributes.getValue("value"));

}
项目:jspare-vertx-ms-blueprint    文件:JDBCProvider.java   
public EntityManagerFactory build() {

        Properties properties = createProperties();

        DefaultPersistenceUnitInfoImpl persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(JSPARE_GATEWAY_DATASOURCE);
        persistenceUnitInfo.setProperties(properties);

        // Using RESOURCE_LOCAL for manage transactions on DAO side.
        persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);

        // Add all entities to configuration
        ClassAnnotationMatchProcessor processor = (c) -> persistenceUnitInfo.addAnnotatedClassName(c);
        ClasspathScannerUtils.scanner(ALL_SCAN_QUOTE).matchClassesWithAnnotation(Entity.class, processor)
                .scan(NUMBER_CLASSPATH_SCANNER_THREADS);

        Map<String, Object> configuration = new HashMap<>();
        properties.forEach((k, v) -> configuration.put((String) k, v));

        EntityManagerFactory entityManagerFactory = persistenceProvider.createContainerEntityManagerFactory(persistenceUnitInfo,
                configuration);
        return entityManagerFactory;
    }
项目:jspare-vertx-ms-blueprint    文件:JDBCProvider.java   
public EntityManagerFactory build() {

        Properties properties = createProperties();

        DefaultPersistenceUnitInfoImpl persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(JSPARE_GATEWAY_DATASOURCE);
        persistenceUnitInfo.setProperties(properties);

        // Using RESOURCE_LOCAL for manage transactions on DAO side.
        persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);

        // Add all entities to configuration
        ClassAnnotationMatchProcessor processor = (c) -> persistenceUnitInfo.addAnnotatedClassName(c);
        ClasspathScannerUtils.scanner(ALL_SCAN_QUOTE).matchClassesWithAnnotation(Entity.class, processor)
                .scan(NUMBER_CLASSPATH_SCANNER_THREADS);

        Map<String, Object> configuration = new HashMap<>();
        properties.forEach((k, v) -> configuration.put((String) k, v));

        EntityManagerFactory entityManagerFactory = persistenceProvider.createContainerEntityManagerFactory(persistenceUnitInfo,
                configuration);
        return entityManagerFactory;
    }
项目:tapestry-jpa-transactions    文件:EclipseLinkJpaTestModule.java   
@Contribute(EntityManagerSource.class)
public static void configurePersistenceUnit(
        MappedConfiguration<String, PersistenceUnitConfigurer> cfg,
        final ObjectLocator objectLocator)
{
    PersistenceUnitConfigurer configurer = new PersistenceUnitConfigurer()
    {
        @Override
        public void configure(TapestryPersistenceUnitInfo unitInfo)
        {
            unitInfo.transactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL)
                    .persistenceProviderClassName("org.eclipse.persistence.jpa.PersistenceProvider")
                    .excludeUnlistedClasses(false)
                    .addProperty("javax.persistence.jdbc.user", "sa")
                    .addProperty("javax.persistence.jdbc.password", "sa")
                    .addProperty("javax.persistence.jdbc.driver", "org.h2.Driver")
                    .addProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:jpatest_eclipselink")
                    .addProperty("eclipselink.ddl-generation", "create-or-extend-tables")
                    .addProperty("eclipselink.logging.level", "FINE");

            unitInfo.getProperties().put("javax.persistence.bean.manager",
                    objectLocator.autobuild(TapestryCDIBeanManagerForJPAEntityListeners.class));
        }
    };
    cfg.add("jpatest", configurer);
}
项目:tapestry-jpa-transactions    文件:HibernateJpaTestModule.java   
@Contribute(EntityManagerSource.class)
public static void configurePersistenceUnit(
        MappedConfiguration<String, PersistenceUnitConfigurer> cfg,
        final ObjectLocator objectLocator)
{
        PersistenceUnitConfigurer configurer = new PersistenceUnitConfigurer()
    {
        @Override
        public void configure(TapestryPersistenceUnitInfo unitInfo)
        {
            unitInfo.transactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL)
                    .persistenceProviderClassName("org.hibernate.jpa.HibernatePersistenceProvider")
                    .excludeUnlistedClasses(false)
                    .addProperty("javax.persistence.jdbc.user", "sa")
                    .addProperty("javax.persistence.jdbc.password", "sa")
                    .addProperty("javax.persistence.jdbc.driver", "org.h2.Driver")
                    .addProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:jpatest_hibernate")
                    .addProperty("hibernate.hbm2ddl.auto", "update")
                    .addProperty("hibernate.show_sql", "true");

            unitInfo.getProperties().put(AvailableSettings.CDI_BEAN_MANAGER,
                    objectLocator.autobuild(TapestryCDIBeanManagerForJPAEntityListeners.class));
        }
    };
    cfg.add("jpatest", configurer);
}
项目:testyourquery    文件:HSQLDBProvider.java   
public HSQLDBProvider() {
    scan.limitSearchingPathTo(full());
    generator = new RuntimePersistenceGenerator("test", PersistenceUnitTransactionType.RESOURCE_LOCAL, getProvider());
    setProperties(generator);

    generateAnnotedClasses();
    for (Class<?> annotatedClass : entities) {
        generator.addAnnotatedClass(annotatedClass);
    }

    if (haveSchema()) {
        try {
            executeStatement("CREATE SCHEMA " + schema + " AUTHORIZATION DBA;");
        } catch (Exception e) {
        }
    }
}
项目:osgi.ee    文件:EntityManagerFactoryTracker.java   
/**
 * Register an entity manager for a factory. Is called during the dynamics
 * (either at start or afterwards) to handle the creation of an entity
 * manager.
 *
 * @param factory The factory used
 * @param properties The service properties of the factory
 */
private synchronized void register(EntityManagerFactory factory, Map<String, Object> properties) {
    if (context == null || transactionManager == null || entityManagers.containsKey(factory)) {
        return;
    }
    String unitName = unitName(properties);
    PersistenceUnitTransactionType type = transactionType(properties);
    // Proxy an entity manager.
    EntityManager manager = proxy(factory, type);
    // Register the proxy as service.
    Hashtable<String, Object> props = new Hashtable<>();
    props.put(UNITNAME, unitName);
    ServiceRegistration<EntityManager> sr = context.registerService(
            EntityManager.class, manager, props);
    entityManagers.put(factory, sr);
}
项目: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();
}
项目:tomee    文件:JpaTest.java   
public void testJta() throws Exception {
    transactionType = PersistenceUnitTransactionType.JTA;
    entityManagerFactory = createEntityManagerFactory();

    final Object jpaTestObject = getClass().getClassLoader().loadClass("org.apache.openejb.core.cmp.jpa.JpaTestObject").newInstance();
    set(jpaTestObject, "EntityManagerFactory", EntityManagerFactory.class, entityManagerFactory);
    set(jpaTestObject, "TransactionManager", TransactionManager.class, transactionManager);
    set(jpaTestObject, "NonJtaDs", DataSource.class, nonJtaDs);

    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    invoke(jpaTestObject, "setUp");
    try {
        invoke(jpaTestObject, "jpaLifecycle");
    } finally {
        invoke(jpaTestObject, "tearDown");
    }
}
项目:tomee    文件:JpaTest.java   
public void testResourceLocal() throws Exception {
    transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
    entityManagerFactory = createEntityManagerFactory();

    final Object jpaTestObject = getClass().getClassLoader().loadClass("org.apache.openejb.core.cmp.jpa.JpaTestObject").newInstance();
    set(jpaTestObject, "EntityManagerFactory", EntityManagerFactory.class, entityManagerFactory);
    set(jpaTestObject, "NonJtaDs", DataSource.class, nonJtaDs);

    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    invoke(jpaTestObject, "setUp");
    try {
        invoke(jpaTestObject, "jpaLifecycle");
    } finally {
        invoke(jpaTestObject, "tearDown");
    }
}
项目:lightmare    文件:PersistenceXmlParserImpl.java   
private void decodeTransactionType(
    ParsedPersistenceXmlDescriptor persistenceUnit) {
// if transaction type is set already
// use that value
// else
// if JTA DS
// use JTA
// else if NOT JTA DS
// use RESOURCE_LOCAL
// else
// use defaultTransactionType
if (persistenceUnit.getTransactionType() != null) {
    return;
}

if (persistenceUnit.getJtaDataSource() != null) {
    persistenceUnit
        .setTransactionType(PersistenceUnitTransactionType.JTA);
} else if (persistenceUnit.getNonJtaDataSource() != null) {
    persistenceUnit
        .setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
} else {
    persistenceUnit.setTransactionType(defaultTransactionType);
}
   }
项目:testee.fi    文件:PersistenceUnitInfoImpl.java   
/**
 * Constructor.
 *
 * @param rootUrl                the URL for the jar file or directory that is the root of the persistence unit.
 * @param provider               provider class name.
 * @param name                   the persistence unit name.
 * @param transactionType        the transaction type.
 * @param jtaDataSource          the JTA data source.
 * @param properties             the properties.
 * @param jarFileUrls            <code>jar-file</code> elements from <code>persistence.xml</code>.
 * @param mappingFileNames       <code>mapping-file</code> elements from <code>persistence.xml</code>.
 * @param managedClassNames      <code>class</code> elements from <code>persistence.xml</code>.
 * @param excludeUnlistedClasses <code>exclude-unlisted-classes</code> element from <code>persistence.xml</code>.
 * @param classLoader            the class loader to use.
 */
public PersistenceUnitInfoImpl(
        final URL rootUrl,
        final String provider,
        final String name,
        final String actualName,
        final PersistenceUnitTransactionType transactionType,
        final DataSource jtaDataSource,
        final Properties properties,
        final List<URL> jarFileUrls,
        final List<String> mappingFileNames,
        final List<String> managedClassNames,
        final boolean excludeUnlistedClasses,
        final ClassLoader classLoader
) {
    this.rootUrl = rootUrl;
    this.provider = provider;
    this.name = name;
    this.actualName = actualName;
    this.transactionType = transactionType;
    this.jtaDataSource = jtaDataSource;
    this.properties = properties;
    this.jarFileUrls = jarFileUrls;
    this.mappingFileNames = mappingFileNames;
    this.managedClassNames = managedClassNames;
    this.excludeUnlistedClasses = excludeUnlistedClasses;
    this.classLoader = classLoader;
}
项目:aries-jpa    文件:PersistenceUnit.java   
public PersistenceUnit(Bundle bundle, String persistenceUnitName,
                       PersistenceUnitTransactionType transactionType) {
    this.bundle = bundle;
    this.persistenceUnitName = persistenceUnitName;
    this.transactionType = transactionType;
    this.props = new Properties();
    this.classLoader = bundle.adapt(BundleWiring.class).getClassLoader();
    this.classNames = new HashSet<String>();
    this.mappingFileNames = new HashSet<String>();
}
项目:aries-jpa    文件:AriesEntityManagerFactoryBuilder.java   
private void dataSourceReady(DataSource ds, Map<String, Object> props) {
    if (persistenceUnit.getTransactionType() == PersistenceUnitTransactionType.JTA) {
        props.put(JAVAX_PERSISTENCE_JTA_DATASOURCE, ds);
    } else {
        props.put(JAVAX_PERSISTENCE_NON_JTA_DATASOURCE, ds);
    }
    createEntityManagerFactory(props);
}
项目:aries-jpa    文件:PropsConfigurationTest.java   
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {

    when(punit.getPersistenceUnitName()).thenReturn("test-props");
    when(punit.getPersistenceProviderClassName())
        .thenReturn(ECLIPSE_PERSISTENCE_PROVIDER);
    when(punit.getTransactionType()).thenReturn(PersistenceUnitTransactionType.JTA);
    when(punit.getBundle()).thenReturn(punitBundle);
    when(punit.getProperties()).thenReturn(punitProperties);

    when(punitBundle.getBundleContext()).thenReturn(punitContext);
    when(punitBundle.getVersion()).thenReturn(Version.parseVersion("1.2.3"));

    when(containerContext.registerService(eq(ManagedService.class), 
            any(ManagedService.class), any(Dictionary.class))).thenReturn(msReg);
    when(containerContext.getService(dsfRef)).thenReturn(dsf);
    when(containerContext.getService(dsRef)).thenReturn(ds);
    when(containerContext.createFilter(Mockito.anyString()))
        .thenAnswer(new Answer<Filter>() {
            @Override
            public Filter answer(InvocationOnMock i) throws Throwable {
                return FrameworkUtil.createFilter(i.getArguments()[0].toString());
            }
        });

    when(punitContext.registerService(eq(EntityManagerFactory.class), any(EntityManagerFactory.class), 
            any(Dictionary.class))).thenReturn(emfReg);

    when(emf.isOpen()).thenReturn(true);


    Properties jdbcProps = new Properties();
    jdbcProps.setProperty("url", JDBC_URL);
    jdbcProps.setProperty("user", JDBC_USER);
    jdbcProps.setProperty("password", JDBC_PASSWORD);

    when(dsf.createDataSource(jdbcProps)).thenReturn(ds);

}
项目:aries-jpa    文件:PropsConfigurationTest.java   
@Test
public void testIncompleteEmfWithoutProps() throws InvalidSyntaxException, ConfigurationException {

    when(provider.createContainerEntityManagerFactory(eq(punit), 
            eq(singletonMap(PersistenceUnitTransactionType.class.getName(), JTA))))
        .thenReturn(emf);

    AriesEntityManagerFactoryBuilder emfb = new AriesEntityManagerFactoryBuilder(
            containerContext, provider, providerBundle, punit);

    assertEquals(ECLIPSE_PERSISTENCE_PROVIDER, emfb.getPersistenceProviderName());
    assertEquals(providerBundle, emfb.getPersistenceProviderBundle());

    try {
        emfb.createEntityManagerFactory(null);
        fail("Should throw an exception as incomplete");
    } catch (IllegalArgumentException iae) {
        // Expected
    }


    // No EMF created as incomplete
    verifyZeroInteractions(emf, emfReg, provider);

    emfb.close();

    verifyZeroInteractions(emf, emfReg, provider);
}
项目:aries-jpa    文件:PropsConfigurationTest.java   
@Test
public void testIncompleteEmfWithDSGetsPassed() throws InvalidSyntaxException, ConfigurationException {

    when(provider.createContainerEntityManagerFactory(eq(punit), 
            eq(singletonMap(PersistenceUnitTransactionType.class.getName(), JTA))))
        .thenReturn(emf);

    Map<String, Object> props = new Hashtable<String, Object>();
    props.put("javax.persistence.dataSource", ds);

    AriesEntityManagerFactoryBuilder emfb = new AriesEntityManagerFactoryBuilder(
            containerContext, provider, providerBundle, punit);

    assertEquals(ECLIPSE_PERSISTENCE_PROVIDER, emfb.getPersistenceProviderName());
    assertEquals(providerBundle, emfb.getPersistenceProviderBundle());

    emfb.createEntityManagerFactory(props);

    verify(punit).setNonJtaDataSource(ds);
    verify(punitContext).registerService(eq(EntityManagerFactory.class),
            any(EntityManagerFactory.class), argThat(servicePropsMatcher(JPA_UNIT_NAME, "test-props")));

    emfb.close();

    verify(emfReg).unregister();
    verify(emf).close();
}
项目:aries-jpa    文件:PropsConfigurationTest.java   
@Test
  public void testIncompleteEmfWithPropsGetsPassed() throws InvalidSyntaxException, ConfigurationException {

    Map<String, Object> providerProps = new HashMap<String, Object>();
    providerProps.put(PersistenceUnitTransactionType.class.getName(), JTA);
    providerProps.put("hibernate.hbm2ddl.auto", "create-drop");

    when(provider.createContainerEntityManagerFactory(eq(punit), 
            eq(providerProps))).thenReturn(emf);

    Map<String, Object> props = new Hashtable<String, Object>();
      props.put("hibernate.hbm2ddl.auto", "create-drop");
      props.put("javax.persistence.dataSource", ds);

      AriesEntityManagerFactoryBuilder emfb = new AriesEntityManagerFactoryBuilder(
            containerContext, provider, providerBundle, punit);
      emfb.createEntityManagerFactory(props);


      verify(punitContext).registerService(eq(EntityManagerFactory.class),
            any(EntityManagerFactory.class), and(argThat(servicePropsMatcher(JPA_UNIT_NAME, "test-props")),
                    argThat(servicePropsMatcher("hibernate.hbm2ddl.auto", "create-drop"))));

      emfb.close();
verify(emfReg).unregister();
verify(emf).close();
  }
项目:aries-jpa    文件:EMFTracker.java   
@SuppressWarnings("unchecked")
@Override
public Object addingService(ServiceReference reference) {
    String unitName = (String)reference.getProperty(JPA_UNIT_NAME);
    if (unitName == null) {
        return null;
    }
    BundleContext puContext = reference.getBundle().getBundleContext();
    TrackedEmf tracked = new TrackedEmf();
    tracked.emf = (EntityManagerFactory)puContext.getService(reference);
    tracked.emSupplier = new EMSupplierImpl(unitName, tracked.emf, coordinator);
    tracked.emSupplierReg = puContext.registerService(EmSupplier.class, tracked.emSupplier,
                                                     getEmSupplierProps(unitName));

    EntityManager emProxy = createProxy(tracked.emSupplier);
    tracked.emProxyReg = puContext.registerService(EntityManager.class, emProxy,
                                                     getEmSupplierProps(unitName));

    if (getTransactionType(tracked.emf) == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
        JpaTemplate txManager = new ResourceLocalJpaTemplate(tracked.emSupplier, coordinator);
        tracked.rlTxManagerReg = puContext.registerService(JpaTemplate.class, txManager,
                                                      rlTxManProps(unitName));
    } else {
        tracked.tmTracker = new TMTracker(puContext, tracked.emSupplier, unitName, coordinator);
        tracked.tmTracker.open();
    }
    return tracked;
}
项目:aries-jpa    文件:EMFTracker.java   
/**
 * 
 * @param emf to get type from
 * @return
 */
private PersistenceUnitTransactionType getTransactionType(EntityManagerFactory emf) {
    try {
        PersistenceUnitTransactionType transactionType = (PersistenceUnitTransactionType) emf.getProperties().get(PersistenceUnitTransactionType.class.getName());
        if (transactionType == PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            return PersistenceUnitTransactionType.RESOURCE_LOCAL;
        }
    } catch (Exception e) {
        LOG.warn("Error while determining the transaction type. Falling back to JTA.", e);
    }
    return PersistenceUnitTransactionType.JTA;
}
项目:aries-jpa    文件:EmfTrackerTest.java   
@SuppressWarnings("unchecked")
@Test
public void testLifecycle() {
    BundleContext context = mock(BundleContext.class);
    Coordinator coordinator = mock(Coordinator.class);
    EMFTracker tracker = new EMFTracker(context, coordinator);
    ServiceReference<EntityManagerFactory> ref = mock(ServiceReference.class);
    Mockito.when(ref.getProperty(EntityManagerFactoryBuilder.JPA_UNIT_NAME)).thenReturn("testunit");
    Mockito.when(ref.getProperty(PersistenceUnitTransactionType.class.getName())).thenReturn("JTA");

    Bundle puBundle = mock(Bundle.class);
    BundleContext puContext = mock(BundleContext.class);
    when(puBundle.getBundleContext()).thenReturn(puContext);
    when(ref.getBundle()).thenReturn(puBundle);
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    when(puContext.getService(ref)).thenReturn(emf);
    ServiceRegistration<?> emSupplierReg = mock(ServiceRegistration.class, "emSupplierReg");
    ServiceRegistration<?> emProxyReg = mock(ServiceRegistration.class, "emProxyReg");
    when(puContext.registerService(any(Class.class), any(), any(Dictionary.class)))
        .thenReturn(emSupplierReg, emProxyReg);

    EMFTracker.TrackedEmf tracked = (TrackedEmf)tracker.addingService(ref);
    Assert.assertEquals(emf, tracked.emf);
    Assert.assertEquals(emSupplierReg, tracked.emSupplierReg);
    Assert.assertEquals(emProxyReg, tracked.emProxyReg);
    Assert.assertNotNull(tracked.tmTracker);
    Assert.assertNull(tracked.rlTxManagerReg);

    tracker.removedService(ref, tracked);
    verify(emSupplierReg, times(1)).unregister();
    verify(emProxyReg, times(1)).unregister();
    verify(puContext, times(1)).ungetService(ref);
}
项目:lams    文件:MutablePersistenceUnitInfo.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (this.transactionType != null) {
        return this.transactionType;
    }
    else {
        return (this.jtaDataSource != null ?
                PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL);
    }
}
项目:vertx-jpa    文件:HibernateEntityManagerFactoryProvider.java   
@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;
  }
}
项目:vertx-jpa    文件:DefaultPersistenceUnitInfoImpl.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
  if (transactionType != null) {
    return transactionType;
  } else {
    return jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL;
  }
}
项目:jspare-vertx-ms-blueprint    文件:DefaultPersistenceUnitInfoImpl.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (transactionType != null) {
        return transactionType;
    } else {
        return jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL;
    }
}
项目:helium    文件:EntityManagerFactoryImpl.java   
@SuppressWarnings( "unchecked" )
public EntityManagerFactoryImpl(
        SessionFactory sessionFactory,
        PersistenceUnitTransactionType transactionType,
        boolean discardOnClose,
        Class<?> sessionInterceptorClass,
        Configuration cfg) {
    this.sessionFactory = sessionFactory;
    this.transactionType = transactionType;
    this.discardOnClose = discardOnClose;
    this.sessionInterceptorClass = sessionInterceptorClass;
    final Iterator<PersistentClass> classes = cfg.getClassMappings();
    List<PersistentClass> persistentClasses = new ArrayList<PersistentClass>();
    while (classes.hasNext()) {
        PersistentClass persistentClass = classes.next();
        // Hardcode jBPM classes for now, but make tidy with a property like "hibernate.ejb.metamodel.excluded.pkgs"
        if (persistentClass.getClassName().startsWith("org.jbpm")) {
           continue;
        } else {
           persistentClasses.add(persistentClass);
        }
    }
    //a safe guard till we are confident that metamodel is wll tested
    if ( !"disabled".equalsIgnoreCase( cfg.getProperty( "hibernate.ejb.metamodel.generation" ) ) ) {
        this.metamodel = MetamodelImpl.buildMetamodel( persistentClasses.iterator(), ( SessionFactoryImplementor ) sessionFactory );
    }
    else {
        this.metamodel = null;
    }
    this.criteriaBuilder = new CriteriaBuilderImpl( this );
    this.util = new HibernatePersistenceUnitUtil( this );

    HashMap<String,Object> props = new HashMap<String, Object>();
    addAll( props, ( (SessionFactoryImplementor) sessionFactory ).getProperties() );
    addAll( props, cfg.getProperties() );
    this.properties = Collections.unmodifiableMap( props );
}
项目:spring4-understanding    文件:MutablePersistenceUnitInfo.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (this.transactionType != null) {
        return this.transactionType;
    }
    else {
        return (this.jtaDataSource != null ?
                PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL);
    }
}
项目:spring4-understanding    文件:LocalContainerEntityManagerFactoryBeanTests.java   
@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
    Object testEntity = new Object();

    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);

    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
    pui.setTransactionType(PersistenceUnitTransactionType.JTA);

    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());

    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

    assertNotSame("EMF must be proxied", mockEmf, emf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertFalse(em.contains(testEntity));

    jpatm.commit(txStatus);

    cefb.destroy();

    verify(mockEm).joinTransaction();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
项目:spring4-understanding    文件:PersistenceXmlParsingTests.java   
@Test
public void testExample4() throws Exception {
    SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
    DataSource ds = new DriverManagerDataSource();
    builder.bind("java:comp/env/jdbc/MyDB", ds);

    PersistenceUnitReader reader = new PersistenceUnitReader(
            new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
    String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
    PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

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

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

    assertEquals(3, info[0].getManagedClassNames().size());
    assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
    assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
    assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));

    assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses());

    assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
    assertEquals(0, info[0].getProperties().keySet().size());

    builder.clear();
}
项目:jspare-container    文件:DefaultPersistenceUnitInfoImpl.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
  if (transactionType != null) {
    return transactionType;
  } else {
    return jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL;
  }
}
项目:jpasecurity    文件:SecurePersistenceProviderTest.java   
private PersistenceUnitInfo createPersistenceUnitInfo() {
    PersistenceUnitInfo persistenceUnitInfo = mock(PersistenceUnitInfo.class);
    when(persistenceUnitInfo.getPersistenceUnitRootUrl()).thenReturn(createPersistenceUnitRootUrl());
    when(persistenceUnitInfo.getPersistenceUnitName()).thenReturn("annotation-based-field-access");
    when(persistenceUnitInfo.getTransactionType())
        .thenReturn(PersistenceUnitTransactionType.RESOURCE_LOCAL);
    when(persistenceUnitInfo.getValidationMode()).thenReturn(ValidationMode.AUTO);
    when(persistenceUnitInfo.getSharedCacheMode()).thenReturn(SharedCacheMode.UNSPECIFIED);
    when(persistenceUnitInfo.getJtaDataSource()).thenReturn(null);
    when(persistenceUnitInfo.getNonJtaDataSource()).thenReturn(null);
    when(persistenceUnitInfo.getNewTempClassLoader()).thenReturn(null);
    when(persistenceUnitInfo.getMappingFileNames()).thenReturn(Collections.<String>emptyList());
    when(persistenceUnitInfo.getJarFileUrls()).thenReturn(Collections.<URL>emptyList());
    when(persistenceUnitInfo.getPersistenceProviderClassName())
        .thenReturn(SecurePersistenceProvider.class.getName());
    when(persistenceUnitInfo.getClassLoader())
        .thenReturn(Thread.currentThread().getContextClassLoader());
    when(persistenceUnitInfo.getManagedClassNames()).thenReturn(Arrays.asList(
        FieldAccessAnnotationTestBean.class.getName(),
        FieldAccessMapKey.class.getName(),
        FieldAccessMapValue.class.getName()
    ));
    when(persistenceUnitInfo.excludeUnlistedClasses()).thenReturn(true);
    Properties properties = new Properties();
    properties.put("org.jpasecurity.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
    properties.put("org.jpasecurity.security.context",
                   "org.jpasecurity.security.authentication.TestSecurityContext");
    properties.put("org.jpasecurity.security.rules.provider",
                   "org.jpasecurity.security.rules.XmlAccessRulesProvider");
    properties.put("hibernate.hbm2ddl.auto", "create-drop");
    properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
    properties.put("hibernate.connection.url", "jdbc:hsqldb:mem:test");
    properties.put("hibernate.connection.username", "sa");
    properties.put("hibernate.connection.password", "");
    when(persistenceUnitInfo.getProperties()).thenReturn(properties);
    return persistenceUnitInfo;
}
项目:jspare-vertx-ms-blueprint    文件:DefaultPersistenceUnitInfoImpl.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (transactionType != null) {
        return transactionType;
    } else {
        return jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL;
    }
}
项目:codenvy    文件:JpaIntegrationTckModule.java   
@Override
protected void configure() {
  final Map<String, String> properties = new HashMap<>();
  properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

  final String dbUrl = System.getProperty("jdbc.url");
  final String dbUser = System.getProperty("jdbc.user");
  final String dbPassword = System.getProperty("jdbc.password");

  waitConnectionIsEstablished(dbUrl, dbUser, dbPassword);

  properties.put(JDBC_URL, dbUrl);
  properties.put(JDBC_USER, dbUser);
  properties.put(JDBC_PASSWORD, dbPassword);
  properties.put(JDBC_DRIVER, System.getProperty("jdbc.driver"));

  JpaPersistModule main = new JpaPersistModule("main");
  main.properties(properties);
  install(main);
  final PGSimpleDataSource dataSource = new PGSimpleDataSource();
  dataSource.setUser(dbUser);
  dataSource.setPassword(dbPassword);
  dataSource.setUrl(dbUrl);
  bind(SchemaInitializer.class)
      .toInstance(new FlywaySchemaInitializer(dataSource, "che-schema", "codenvy-schema"));
  bind(DBInitializer.class).asEagerSingleton();
  bind(TckResourcesCleaner.class).to(JpaCleaner.class);

  bind(new TypeLiteral<TckRepository<InviteImpl>>() {})
      .toInstance(new JpaTckRepository<>(InviteImpl.class));
  bind(new TypeLiteral<TckRepository<OrganizationImpl>>() {})
      .toInstance(new JpaTckRepository<>(OrganizationImpl.class));
  bind(new TypeLiteral<TckRepository<WorkspaceImpl>>() {})
      .toInstance(new JpaTckRepository<>(WorkspaceImpl.class));

  bind(InviteDao.class).to(JpaInviteDao.class);
}
项目:testyourquery    文件:RuntimePersistenceGenerator.java   
public RuntimePersistenceGenerator(String unitName, PersistenceUnitTransactionType transactionType, String providerName) {
    this.unitName = unitName;
    this.transactionType = transactionType;
    this.providerName = providerName;
    try {
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(createProxy(originalClassLoader));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:osgi.ee    文件:OurPersistenceProvider.java   
@Override
public EntityManagerFactory createContainerEntityManagerFactory(
        PersistenceUnitInfo info, @SuppressWarnings("rawtypes") Map properties) {
    Map<String, Object> props = new HashMap<>();
    if (properties != null) {
        props.putAll(props);
    }
    // Check if we are using JTA. If so, overwrite the platform.
    if (PersistenceUnitTransactionType.JTA.equals(info.getTransactionType())) {
        props.put(PersistenceUnitProperties.TARGET_SERVER, OurPlatForm.class.getName());
    }
    return super.createContainerEntityManagerFactory(info, props);
}
项目:osgi.ee    文件:EntityManagerFactoryTracker.java   
/**
 * Get the persistence unit transaction type from the service properties.
 *
 * @param props The properties
 * @return The transaction type
 */
private static PersistenceUnitTransactionType transactionType(Map<String, Object> props) {
    Object value = props.get(PersistenceUnitTransactionType.class.getName());
    if (value == null) {
        return null;
    }
    return PersistenceUnitTransactionType.valueOf(value.toString());
}
项目:osgi.ee    文件:EntityManagerFactoryTracker.java   
/**
 * This method creates a proxy for an entity manager.
 *
 * @param factory The entity manager factory to create the proxy for
 * @param type The transaction type for this unit
 * @return The entity manager proxy
 */
private EntityManager proxy(EntityManagerFactory factory, PersistenceUnitTransactionType type) {
    InvocationHandler handler = new EntityProxyInvocationHandler(factory,
            transactionManager, type);
    try {
        EntityManager manager = (EntityManager) proxy.getConstructor(
                InvocationHandler.class).newInstance(handler);
        return manager;
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }
}
项目:osgi.ee    文件:EntityProxyInvocationHandler.java   
/**
 * Create an proxy invocation handler for a factory and a transaction manager.
 *
 * @param f The entity manager factory
 * @param m The transaction manager
 * @param type The persistence unit transaction type
 */
EntityProxyInvocationHandler(EntityManagerFactory f, TransactionManager m, PersistenceUnitTransactionType type) {
    factory = f;
    local = new ThreadLocal<>();
    transactionManager = m;
    if (PersistenceUnitTransactionType.JTA.equals(type)) {
        synchronizer = (a, b, c) -> registerEntityManagerJTA(a, b, c);
    }
    else if (PersistenceUnitTransactionType.RESOURCE_LOCAL.equals(type)) {
        synchronizer = (a, b, c) -> registerEntityManagerResourceLocal(a, b, c);
    }
    else {
        synchronizer = (a, b, c) -> registerEntityManagerUnknown(a, b, c);
    }
}
项目:osgi.ee    文件:PersistenceUnitInfoImpl.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (definition.transactionType.isEmpty()) {
        return PersistenceUnitTransactionType.JTA;
    }
    PersistenceUnitTransactionType type = 
            PersistenceUnitTransactionType.valueOf(definition.transactionType);
    return type;
}
项目:wisdom-jdbc    文件:PersistenceUnitComponent.java   
@Override
public PersistenceUnitTransactionType getTransactionType() {
    if (persistenceUnitXml.getTransactionType() ==
            org.wisdom.framework.jpa.model.PersistenceUnitTransactionType
                    .RESOURCE_LOCAL) {
        return PersistenceUnitTransactionType.RESOURCE_LOCAL;
    } else {
        return PersistenceUnitTransactionType.JTA;
    }
}