HHH-11024 - Exception still thrown when dropping schema with a managed connection

This commit is contained in:
Steve Ebersole 2016-08-06 14:05:03 -05:00
parent 1378708088
commit f025cf9c03
21 changed files with 514 additions and 915 deletions

View File

@ -248,10 +248,10 @@ subprojects { subProject ->
into sourceSets.test.output.classesDir into sourceSets.test.output.classesDir
} }
copy { copy {
ext.targetDir = file( "${buildDir}/resources/test" )
from file('src/test/resources') from file('src/test/resources')
into targetDir into file( "${buildDir}/resources/test" )
filter( ReplaceTokens, tokens: dbBundle[db] ); exclude 'src/test/resources/arquillian.xml'
filter( ReplaceTokens, tokens: dbBundle[db] )
} }
} ) } )
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -75,8 +75,8 @@ dependencies {
testCompile( libraries.classmate ) testCompile( libraries.classmate )
testCompile( libraries.mockito ) testCompile( libraries.mockito )
testCompile( 'joda-time:joda-time:2.3' ) testCompile( 'joda-time:joda-time:2.3' )
testCompile( "org.jboss.weld:weld-core:2.3.4.Final" ) // testCompile( "org.jboss.weld:weld-core:2.3.4.Final" )
testCompile( "org.jboss.arquillian.container:arquillian-weld-ee-embedded-1.1:1.0.0.CR9" ) // testCompile( "org.jboss.arquillian.container:arquillian-weld-ee-embedded-1.1:1.0.0.CR9" )
compile( "javax.enterprise:cdi-api:${cdiVersion}" ) { compile( "javax.enterprise:cdi-api:${cdiVersion}" ) {
// we need to force it to make sure we influence the one coming from arquillian // we need to force it to make sure we influence the one coming from arquillian
force=true force=true
@ -95,7 +95,17 @@ dependencies {
testRuntime( libraries.expression_language_impl ) testRuntime( libraries.expression_language_impl )
testRuntime( 'jaxen:jaxen:1.1' ) testRuntime( 'jaxen:jaxen:1.1' )
testRuntime( libraries.javassist ) testRuntime( libraries.javassist )
testCompile( project( ':hibernate-jpamodelgen' ) ) testCompile( project( ':hibernate-jpamodelgen' ) )
testCompile libraries.arquillian_junit_container
testCompile libraries.arquillian_protocol_servlet
testCompile libraries.shrinkwrap_descriptors_api_javaee
testCompile libraries.shrinkwrap_descriptors_impl_javaee
testCompile libraries.wildfly_arquillian_container_managed
testCompile libraries.jboss_ejb_spec_jar
testCompile libraries.jboss_annotation_spec_jar
} }
mavenPom { mavenPom {
@ -219,3 +229,19 @@ if ( JavaVersion.current().isJava9Compatible() ) {
exclude 'org/hibernate/test/bytecode/enhancement/basic/BasicInSessionTest.class' exclude 'org/hibernate/test/bytecode/enhancement/basic/BasicInSessionTest.class'
} }
} }
processTestResources {
doLast {
copy {
from file( 'src/test/resources' )
into file( "${buildDir}/resources/test" )
include 'arquillian.xml'
include 'org/hibernate/test/wf/ddl/manifest.mf'
expand wildFlyInstallDir: "${rootProject.buildDir.absolutePath}/wildfly-${wildflyVersion}",
hibernateMajorMinorVersion: "${rootProject.hibernateMajorMinorVersion}",
arquillianDeploymentExportDir: "${rootProject.buildDir.absolutePath}/arquillian-deployments"
}
}
}
test.dependsOn ":hibernate-orm-modules:prepareWildFlyForTests"

View File

@ -32,6 +32,7 @@ public class StandardJtaPlatformResolver implements JtaPlatformResolver {
// Initially look for a JtaPlatformProvider // Initially look for a JtaPlatformProvider
for ( JtaPlatformProvider provider : classLoaderService.loadJavaServices( JtaPlatformProvider.class ) ) { for ( JtaPlatformProvider provider : classLoaderService.loadJavaServices( JtaPlatformProvider.class ) ) {
final JtaPlatform providedPlatform = provider.getProvidedJtaPlatform(); final JtaPlatform providedPlatform = provider.getProvidedJtaPlatform();
log.tracef( "Located JtaPlatformProvider [%s] provided JtaPlaform : %s", provider, providedPlatform );
if ( providedPlatform!= null ) { if ( providedPlatform!= null ) {
return providedPlatform; return providedPlatform;
} }

View File

@ -1,8 +1,8 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.jpa.boot.internal; package org.hibernate.jpa.boot.internal;
@ -11,9 +11,11 @@ import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.spi.PersistenceUnitTransactionType; import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
@ -63,6 +65,78 @@ public class PersistenceXmlParser {
PersistenceUnitTransactionType.RESOURCE_LOCAL PersistenceUnitTransactionType.RESOURCE_LOCAL
); );
return new ArrayList<>( parser.doResolve( integration ).values() );
}
public static ParsedPersistenceXmlDescriptor locateIndividualPersistenceUnit(URL persistenceXmlUrl) {
return locateIndividualPersistenceUnit( persistenceXmlUrl, Collections.emptyMap() );
}
public static ParsedPersistenceXmlDescriptor locateIndividualPersistenceUnit(URL persistenceXmlUrl, Map integration) {
return locateIndividualPersistenceUnit( persistenceXmlUrl, PersistenceUnitTransactionType.RESOURCE_LOCAL, integration );
}
public static ParsedPersistenceXmlDescriptor locateIndividualPersistenceUnit(
URL persistenceXmlUrl,
PersistenceUnitTransactionType transactionType,
Map integration) {
final PersistenceXmlParser parser = new PersistenceXmlParser(
ClassLoaderServiceImpl.fromConfigSettings( integration ),
transactionType
);
final Map<String,ParsedPersistenceXmlDescriptor> persistenceUnits = parser.parsePersistenceXml( persistenceXmlUrl, integration );
assert persistenceUnits.size() == 1;
return persistenceUnits.values().iterator().next();
}
public static ParsedPersistenceXmlDescriptor locateNamedPersistenceUnit(URL persistenceXmlUrl, String name) {
return locateNamedPersistenceUnit( persistenceXmlUrl, name, Collections.emptyMap() );
}
public static ParsedPersistenceXmlDescriptor locateNamedPersistenceUnit(URL persistenceXmlUrl, String name, Map integration) {
return locateNamedPersistenceUnit( persistenceXmlUrl, name, PersistenceUnitTransactionType.RESOURCE_LOCAL, integration );
}
public static ParsedPersistenceXmlDescriptor locateNamedPersistenceUnit(
URL persistenceXmlUrl,
String name,
PersistenceUnitTransactionType transactionType,
Map integration) {
assert StringHelper.isNotEmpty( name );
final PersistenceXmlParser parser = new PersistenceXmlParser(
ClassLoaderServiceImpl.fromConfigSettings( integration ),
transactionType
);
final Map<String,ParsedPersistenceXmlDescriptor> persistenceUnits = parser.parsePersistenceXml( persistenceXmlUrl, integration );
assert persistenceUnits.containsKey( name );
return persistenceUnits.get( name );
}
/**
* Intended only for use by Hibernate tests!
* <p/>
* Parses a specific persistence.xml file...
*/
public static Map<String,ParsedPersistenceXmlDescriptor> parse(
URL persistenceXmlUrl,
PersistenceUnitTransactionType transactionType) {
return parse( persistenceXmlUrl, transactionType, Collections.emptyMap() );
}
public static Map<String,ParsedPersistenceXmlDescriptor> parse(
URL persistenceXmlUrl,
PersistenceUnitTransactionType transactionType,
Map integration) {
PersistenceXmlParser parser = new PersistenceXmlParser(
ClassLoaderServiceImpl.fromConfigSettings( integration ),
transactionType
);
return parser.doResolve( integration ); return parser.doResolve( integration );
} }
@ -72,8 +146,8 @@ public class PersistenceXmlParser {
this.defaultTransactionType = defaultTransactionType; this.defaultTransactionType = defaultTransactionType;
} }
public List<ParsedPersistenceXmlDescriptor> doResolve(Map integration) { public Map<String,ParsedPersistenceXmlDescriptor> doResolve(Map integration) {
final List<ParsedPersistenceXmlDescriptor> persistenceUnits = new ArrayList<ParsedPersistenceXmlDescriptor>(); final Map<String,ParsedPersistenceXmlDescriptor> persistenceUnits = new ConcurrentHashMap<>();
final List<URL> xmlUrls = classLoaderService.locateResources( "META-INF/persistence.xml" ); final List<URL> xmlUrls = classLoaderService.locateResources( "META-INF/persistence.xml" );
if ( xmlUrls.isEmpty() ) { if ( xmlUrls.isEmpty() ) {
@ -81,20 +155,20 @@ public class PersistenceXmlParser {
} }
else { else {
for ( URL xmlUrl : xmlUrls ) { for ( URL xmlUrl : xmlUrls ) {
persistenceUnits.addAll( parsePersistenceXml( xmlUrl, integration ) ); persistenceUnits.putAll( parsePersistenceXml( xmlUrl, integration ) );
} }
} }
return persistenceUnits; return persistenceUnits;
} }
private List<ParsedPersistenceXmlDescriptor> parsePersistenceXml(URL xmlUrl, Map integration) { private Map<String,ParsedPersistenceXmlDescriptor> parsePersistenceXml(URL xmlUrl, Map integration) {
LOG.tracef( "Attempting to parse persistence.xml file : %s", xmlUrl.toExternalForm() ); LOG.tracef( "Attempting to parse persistence.xml file : %s", xmlUrl.toExternalForm() );
final Document doc = loadUrl( xmlUrl ); final Document doc = loadUrl( xmlUrl );
final Element top = doc.getDocumentElement(); final Element top = doc.getDocumentElement();
final List<ParsedPersistenceXmlDescriptor> persistenceUnits = new ArrayList<ParsedPersistenceXmlDescriptor>(); final Map<String,ParsedPersistenceXmlDescriptor> persistenceUnits = new ConcurrentHashMap<>();
final NodeList children = top.getChildNodes(); final NodeList children = top.getChildNodes();
for ( int i = 0; i < children.getLength() ; i++ ) { for ( int i = 0; i < children.getLength() ; i++ ) {
@ -127,7 +201,10 @@ public class PersistenceXmlParser {
Properties properties = persistenceUnit.getProperties(); Properties properties = persistenceUnit.getProperties();
ConfigurationHelper.overrideProperties( properties, integration ); ConfigurationHelper.overrideProperties( properties, integration );
persistenceUnits.add( persistenceUnit ); persistenceUnits.put(
persistenceUnit.getName(),
persistenceUnit
);
} }
} }
} }

View File

@ -6,12 +6,15 @@
*/ */
package org.hibernate.jpa.boot.spi; package org.hibernate.jpa.boot.spi;
import java.net.URL;
import java.util.Map; import java.util.Map;
import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
/** /**
* Entry into the bootstrap process. * Entry into the bootstrap process.
@ -29,6 +32,43 @@ public final class Bootstrap {
return new EntityManagerFactoryBuilderImpl( persistenceUnitDescriptor, integration ); return new EntityManagerFactoryBuilderImpl( persistenceUnitDescriptor, integration );
} }
/**
* Intended for use in Hibernate tests
*
* @param persistenceXmlUrl The URL to a persistence.xml
* @param persistenceUnitName The name of the persistence-unit to parse
* @param integration setting overrides
*
* @return The EMFB
*/
public static EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(
URL persistenceXmlUrl,
String persistenceUnitName,
Map integration) {
return getEntityManagerFactoryBuilder( persistenceXmlUrl, persistenceUnitName, PersistenceUnitTransactionType.RESOURCE_LOCAL, integration );
}
/**
* Intended for use in Hibernate tests
*
* @param persistenceXmlUrl The URL to a persistence.xml
* @param persistenceUnitName The name of the persistence-unit to parse
* @param integration setting overrides
*
* @return The EMFB
*/
public static EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(
URL persistenceXmlUrl,
String persistenceUnitName,
PersistenceUnitTransactionType transactionType,
Map integration) {
;
return new EntityManagerFactoryBuilderImpl(
PersistenceXmlParser.parse( persistenceXmlUrl, transactionType, integration ).get( persistenceUnitName ),
integration
);
}
public static EntityManagerFactoryBuilder getEntityManagerFactoryBuilder( public static EntityManagerFactoryBuilder getEntityManagerFactoryBuilder(
PersistenceUnitDescriptor persistenceUnitDescriptor, PersistenceUnitDescriptor persistenceUnitDescriptor,
Map integration, Map integration,

View File

@ -10,18 +10,23 @@ import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import javax.transaction.SystemException; import javax.transaction.SystemException;
import javax.transaction.Transaction; import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.resource.transaction.spi.DdlTransactionIsolator; import org.hibernate.resource.transaction.spi.DdlTransactionIsolator;
import org.hibernate.tool.schema.internal.exec.JdbcContext; import org.hibernate.tool.schema.internal.exec.JdbcContext;
import org.jboss.logging.Logger;
/** /**
* DdlExecutor for use in JTA environments * DdlExecutor for use in JTA environments
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class DdlTransactionIsolatorJtaImpl implements DdlTransactionIsolator { public class DdlTransactionIsolatorJtaImpl implements DdlTransactionIsolator {
private static final Logger log = Logger.getLogger( DdlTransactionIsolatorJtaImpl.class );
private final JdbcContext jdbcContext; private final JdbcContext jdbcContext;
private Transaction suspendedTransaction; private Transaction suspendedTransaction;
@ -39,7 +44,20 @@ public class DdlTransactionIsolatorJtaImpl implements DdlTransactionIsolator {
@Override @Override
public void prepare() { public void prepare() {
try { try {
this.suspendedTransaction = jdbcContext.getServiceRegistry().getService( JtaPlatform.class ).retrieveTransactionManager().suspend(); final JtaPlatform jtaPlatform = jdbcContext.getServiceRegistry().getService( JtaPlatform.class );
log.tracef( "DdlTransactionIsolatorJtaImpl#prepare: JtaPlatform -> %s", jtaPlatform );
final TransactionManager tm = jtaPlatform.retrieveTransactionManager();
if ( tm == null ) {
throw new HibernateException(
"DdlTransactionIsolatorJtaImpl could not locate TransactionManager to suspend any current transaction; " +
"base JtaPlatform impl (" + jtaPlatform.toString() + ")?"
);
}
log.tracef( "DdlTransactionIsolatorJtaImpl#prepare: TransactionManager -> %s", tm );
this.suspendedTransaction = tm.suspend();
log.tracef( "DdlTransactionIsolatorJtaImpl#prepare: suspended Transaction -> %s", this.suspendedTransaction );
} }
catch (SystemException e) { catch (SystemException e) {
throw new HibernateException( "Unable to suspend current JTA transaction in preparation for DDL execution" ); throw new HibernateException( "Unable to suspend current JTA transaction in preparation for DDL execution" );

View File

@ -1,53 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cdi;
import java.util.Map;
import javax.enterprise.inject.spi.BeanManager;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.jboss.arquillian.container.weld.ee.embedded_1_1.mock.TestContainer;
import org.jboss.weld.bootstrap.api.Environments;
/**
* @author Steve Ebersole
*/
public abstract class BaseCdiIntegrationTest extends BaseEntityManagerFunctionalTestCase {
private TestContainer testContainer;
public TestContainer getTestContainer() {
return testContainer;
}
@Override
@SuppressWarnings("unchecked")
protected void addConfigOptions(Map options) {
super.addConfigOptions( options );
testContainer = new TestContainer( getCdiBeans() );
testContainer.getBootstrap().startContainer( Environments.SE, testContainer.getDeployment() );
testContainer.getBootstrap().startInitialization();
testContainer.getBootstrap().deployBeans();
testContainer.getBootstrap().validateBeans().endInitialization();
options.put( AvailableSettings.CDI_BEAN_MANAGER, getBeanManager() );
}
protected BeanManager getBeanManager() {
return testContainer.getBeanManager( testContainer.getDeployment().getBeanDeploymentArchives().iterator().next() );
}
public abstract Class[] getCdiBeans();
@Override
public void releaseResources() {
super.releaseResources(); // closes the EMF
testContainer.stopContainer();
}
}

View File

@ -6,56 +6,93 @@
*/ */
package org.hibernate.jpa.test.cdi; package org.hibernate.jpa.test.cdi;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.PersistenceUnit;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence21.PersistenceDescriptor;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class BasicCdiTest extends BaseCdiIntegrationTest { @RunWith(Arquillian.class)
public class BasicCdiTest {
@Deployment
public static Archive<?> buildDeployment() {
return ShrinkWrap.create( JavaArchive.class, "test.jar" )
.addClass( MyEntity.class )
.addClass( EventQueue.class )
.addClass( Event.class )
.addClass( Monitor.class )
.addAsManifestResource( EmptyAsset.INSTANCE, "beans.xml" )
.addAsManifestResource( new StringAsset( persistenceXml().exportAsString() ), "persistence.xml" );
}
private static PersistenceDescriptor persistenceXml() {
return Descriptors.create( PersistenceDescriptor.class )
.createPersistenceUnit().name( "pu-cdi-basic" )
.clazz( MyEntity.class.getName() )
.excludeUnlistedClasses( true )
.nonJtaDataSource( "java:jboss/datasources/ExampleDS" )
.getOrCreateProperties().createProperty().name( "jboss.as.jpa.providerModule" ).value( "org.hibernate:5.2" ).up().up()
.getOrCreateProperties().createProperty().name( "hibernate.delay_cdi_access" ).value( "true" ).up().up()
.getOrCreateProperties().createProperty().name( "hibernate.hbm2ddl.auto" ).value( "create-drop" ).up().up().up();
}
@PersistenceUnit
EntityManagerFactory emf;
@Resource
private UserTransaction utx;
private static int count; private static int count;
@Override
public Class[] getCdiBeans() {
return new Class[] { EventQueue.class };
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { MyEntity.class };
}
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testIt() { public void testIt() throws Exception {
count = 0; count = 0;
EntityManager em = getOrCreateEntityManager(); utx.begin();
em.getTransaction().begin(); EntityManager em = emf.createEntityManager();
em.persist( new MyEntity( 1 ) ); em.persist( new MyEntity( 1 ) );
em.getTransaction().commit(); utx.commit();
em.close();
assertEquals( 1, count ); assertEquals( 1, count );
em = getOrCreateEntityManager(); utx.begin();
em.getTransaction().begin(); em = emf.createEntityManager();
em.remove( em.getReference( MyEntity.class, 1 ) ); MyEntity it = em.find( MyEntity.class, 1 );
em.getTransaction().commit(); assertNotNull( it );
em.close(); em.remove( it );
utx.commit();
} }
@Entity @Entity
@ -129,7 +166,7 @@ public class BasicCdiTest extends BaseCdiIntegrationTest {
public static class Monitor { public static class Monitor {
private final EventQueue eventQueue; private final EventQueue eventQueue;
@Inject @javax.inject.Inject
public Monitor(EventQueue eventQueue) { public Monitor(EventQueue eventQueue) {
this.eventQueue = eventQueue; this.eventQueue = eventQueue;
} }

View File

@ -1,403 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.el.ELResolver;
import javax.el.ExpressionFactory;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMember;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Decorator;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.InjectionTarget;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.enterprise.inject.spi.InterceptionType;
import javax.enterprise.inject.spi.Interceptor;
import javax.enterprise.inject.spi.ObserverMethod;
import javax.enterprise.inject.spi.ProducerFactory;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import org.hibernate.jpa.AvailableSettings;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class DelayedCdiTest extends BaseCdiIntegrationTest {
private BeanManagerImpl beanManager = new BeanManagerImpl();
private static int count;
@Override
public Class[] getCdiBeans() {
return new Class[] { EventQueue.class };
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { MyEntity.class };
}
@Override
protected void addConfigOptions(Map options) {
options.put( AvailableSettings.DELAY_CDI_ACCESS, "true" );
super.addConfigOptions( options );
}
@Override
protected BeanManager getBeanManager() {
// this is the BeanManager used to bootstrap Hibernate. Here
// we want this to be our custom BeanManagerImpl
return beanManager;
}
@Override
protected void afterEntityManagerFactoryBuilt() {
beanManager.delegate = getTestContainer().getBeanManager( getTestContainer().getDeployment().getBeanDeploymentArchives().iterator().next() );
}
@Test
@SuppressWarnings("unchecked")
public void testIt() {
count = 0;
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( new MyEntity( 1 ) );
em.getTransaction().commit();
em.close();
assertEquals( 1, count );
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.getReference( MyEntity.class, 1 ) );
em.getTransaction().commit();
em.close();
}
@Entity
@EntityListeners( Monitor.class )
@Table(name = "my_entity")
public static class MyEntity {
private Integer id;
private String name;
public MyEntity() {
}
public MyEntity(Integer id) {
this.id = id;
}
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class EventQueue {
private List<Event> events;
public void addEvent(Event anEvent) {
if ( events == null ) {
events = new ArrayList<Event>();
}
events.add( anEvent );
count++;
}
}
public static class Event {
private final String who;
private final String what;
private final String when;
public Event(String who, String what, String when) {
this.who = who;
this.what = what;
this.when = when;
}
public String getWho() {
return who;
}
public String getWhat() {
return what;
}
public String getWhen() {
return when;
}
}
public static class Monitor {
private final EventQueue eventQueue;
@Inject
public Monitor(EventQueue eventQueue) {
this.eventQueue = eventQueue;
}
@PrePersist
public void onCreate(Object entity) {
eventQueue.addEvent(
new Event( entity.toString(), "created", now() )
);
}
private String now() {
return new SimpleDateFormat().format( new Date() );
}
}
public static class BeanManagerImpl implements BeanManager {
private BeanManager delegate;
@Override
public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
return getDelegate().getReference( bean, beanType, ctx );
}
private BeanManager getDelegate() {
if ( delegate == null ) {
throw new RuntimeException( "Real BeanManager not yet known" );
}
return delegate;
}
@Override
public Object getInjectableReference(InjectionPoint ij, CreationalContext<?> ctx) {
return getDelegate().getInjectableReference( ij, ctx );
}
@Override
public <T> CreationalContext<T> createCreationalContext(Contextual<T> contextual) {
return getDelegate().createCreationalContext( contextual );
}
@Override
public Set<Bean<?>> getBeans(Type beanType, Annotation... qualifiers) {
return getDelegate().getBeans( beanType, qualifiers );
}
@Override
public Set<Bean<?>> getBeans(String name) {
return getDelegate().getBeans( name );
}
@Override
public Bean<?> getPassivationCapableBean(String id) {
return getDelegate().getPassivationCapableBean( id );
}
@Override
public <X> Bean<? extends X> resolve(Set<Bean<? extends X>> beans) {
return getDelegate().resolve( beans );
}
@Override
public void validate(InjectionPoint injectionPoint) {
getDelegate().validate( injectionPoint );
}
@Override
public void fireEvent(Object event, Annotation... qualifiers) {
getDelegate().fireEvent( event, qualifiers );
}
@Override
public <T> Set<ObserverMethod<? super T>> resolveObserverMethods(T event, Annotation... qualifiers) {
return getDelegate().resolveObserverMethods( event, qualifiers );
}
@Override
public List<Decorator<?>> resolveDecorators(Set<Type> types, Annotation... qualifiers) {
return getDelegate().resolveDecorators( types, qualifiers );
}
@Override
public List<Interceptor<?>> resolveInterceptors(InterceptionType type, Annotation... interceptorBindings) {
return getDelegate().resolveInterceptors( type, interceptorBindings );
}
@Override
public boolean isScope(Class<? extends Annotation> annotationType) {
return getDelegate().isScope( annotationType );
}
@Override
public boolean isNormalScope(Class<? extends Annotation> annotationType) {
return getDelegate().isNormalScope( annotationType );
}
@Override
public boolean isPassivatingScope(Class<? extends Annotation> annotationType) {
return getDelegate().isPassivatingScope( annotationType );
}
@Override
public boolean isQualifier(Class<? extends Annotation> annotationType) {
return getDelegate().isQualifier( annotationType );
}
@Override
public boolean isInterceptorBinding(Class<? extends Annotation> annotationType) {
return getDelegate().isInterceptorBinding( annotationType );
}
@Override
public boolean isStereotype(Class<? extends Annotation> annotationType) {
return getDelegate().isStereotype( annotationType );
}
@Override
public Set<Annotation> getInterceptorBindingDefinition(Class<? extends Annotation> bindingType) {
return getDelegate().getInterceptorBindingDefinition( bindingType );
}
@Override
public Set<Annotation> getStereotypeDefinition(Class<? extends Annotation> stereotype) {
return getDelegate().getStereotypeDefinition( stereotype );
}
@Override
public boolean areQualifiersEquivalent(Annotation qualifier1, Annotation qualifier2) {
return getDelegate().areQualifiersEquivalent( qualifier1, qualifier2 );
}
@Override
public boolean areInterceptorBindingsEquivalent(Annotation interceptorBinding1, Annotation interceptorBinding2) {
return getDelegate().areInterceptorBindingsEquivalent( interceptorBinding1, interceptorBinding2 );
}
@Override
public int getQualifierHashCode(Annotation qualifier) {
return getDelegate().getQualifierHashCode( qualifier );
}
@Override
public int getInterceptorBindingHashCode(Annotation interceptorBinding) {
return getDelegate().getInterceptorBindingHashCode( interceptorBinding );
}
@Override
public Context getContext(Class<? extends Annotation> scopeType) {
return getDelegate().getContext( scopeType );
}
@Override
public ELResolver getELResolver() {
return getDelegate().getELResolver();
}
@Override
public ExpressionFactory wrapExpressionFactory(ExpressionFactory expressionFactory) {
return getDelegate().wrapExpressionFactory( expressionFactory );
}
@Override
public <T> AnnotatedType<T> createAnnotatedType(Class<T> type) {
return getDelegate().createAnnotatedType( type );
}
@Override
public <T> InjectionTarget<T> createInjectionTarget(AnnotatedType<T> type) {
return getDelegate().createInjectionTarget( type );
}
@Override
public <T> InjectionTargetFactory<T> getInjectionTargetFactory(AnnotatedType<T> annotatedType) {
return getDelegate().getInjectionTargetFactory( annotatedType );
}
@Override
public <X> ProducerFactory<X> getProducerFactory(AnnotatedField<? super X> field, Bean<X> declaringBean) {
return getDelegate().getProducerFactory( field, declaringBean );
}
@Override
public <X> ProducerFactory<X> getProducerFactory(AnnotatedMethod<? super X> method, Bean<X> declaringBean) {
return getDelegate().getProducerFactory( method, declaringBean );
}
@Override
public <T> BeanAttributes<T> createBeanAttributes(AnnotatedType<T> type) {
return getDelegate().createBeanAttributes( type );
}
@Override
public BeanAttributes<?> createBeanAttributes(AnnotatedMember<?> type) {
return getDelegate().createBeanAttributes( type );
}
@Override
public <T> Bean<T> createBean(BeanAttributes<T> attributes, Class<T> beanClass, InjectionTargetFactory<T> injectionTargetFactory) {
return getDelegate().createBean( attributes, beanClass, injectionTargetFactory );
}
@Override
public <T, X> Bean<T> createBean(BeanAttributes<T> attributes, Class<X> beanClass, ProducerFactory<X> producerFactory) {
return getDelegate().createBean( attributes, beanClass, producerFactory );
}
@Override
public InjectionPoint createInjectionPoint(AnnotatedField<?> field) {
return getDelegate().createInjectionPoint( field );
}
@Override
public InjectionPoint createInjectionPoint(AnnotatedParameter<?> parameter) {
return getDelegate().createInjectionPoint( parameter );
}
@Override
public <T extends Extension> T getExtension(Class<T> extensionClass) {
return getDelegate().getExtension( extensionClass );
}
}
}

View File

@ -1,405 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.el.ELResolver;
import javax.el.ExpressionFactory;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMember;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanAttributes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Decorator;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.InjectionTarget;
import javax.enterprise.inject.spi.InjectionTargetFactory;
import javax.enterprise.inject.spi.InterceptionType;
import javax.enterprise.inject.spi.Interceptor;
import javax.enterprise.inject.spi.ObserverMethod;
import javax.enterprise.inject.spi.ProducerFactory;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import org.hibernate.jpa.event.spi.jpa.ExtendedBeanManager;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class ExtendedBeanManagerCdiTest extends BaseCdiIntegrationTest {
ExtendedBeanManagerImpl extendedBeanManager = new ExtendedBeanManagerImpl();
private static int count;
@Override
public Class[] getCdiBeans() {
return new Class[] { EventQueue.class };
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { MyEntity.class };
}
@Override
protected BeanManager getBeanManager() {
// this is the BeanManager used to bootstrap Hibernate. Here
// we want this to be our custom ExtendedBeanManagerImpl
return extendedBeanManager;
}
@Override
protected void afterEntityManagerFactoryBuilt() {
// now come back and do the ExtendedBeanManagerImpl lifecycle callbacks
final BeanManager realBeanManager = getTestContainer().getBeanManager( getTestContainer().getDeployment().getBeanDeploymentArchives().iterator().next() );
for ( ExtendedBeanManager.LifecycleListener lifecycleListener : extendedBeanManager.getLifecycleListeners() ) {
lifecycleListener.beanManagerInitialized( realBeanManager );
}
extendedBeanManager.getLifecycleListeners().clear();
}
@Test
@SuppressWarnings("unchecked")
public void testIt() {
count = 0;
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( new MyEntity( 1 ) );
em.getTransaction().commit();
em.close();
assertEquals( 1, count );
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.getReference( MyEntity.class, 1 ) );
em.getTransaction().commit();
em.close();
}
@Entity
@EntityListeners( Monitor.class )
@Table(name = "my_entity")
public static class MyEntity {
private Integer id;
private String name;
public MyEntity() {
}
public MyEntity(Integer id) {
this.id = id;
}
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class EventQueue {
private List<Event> events;
public void addEvent(Event anEvent) {
if ( events == null ) {
events = new ArrayList<Event>();
}
events.add( anEvent );
count++;
}
}
public static class Event {
private final String who;
private final String what;
private final String when;
public Event(String who, String what, String when) {
this.who = who;
this.what = what;
this.when = when;
}
public String getWho() {
return who;
}
public String getWhat() {
return what;
}
public String getWhen() {
return when;
}
}
public static class Monitor {
private final EventQueue eventQueue;
@Inject
public Monitor(EventQueue eventQueue) {
this.eventQueue = eventQueue;
}
@PrePersist
public void onCreate(Object entity) {
eventQueue.addEvent(
new Event( entity.toString(), "created", now() )
);
}
private String now() {
return new SimpleDateFormat().format( new Date() );
}
}
public class ExtendedBeanManagerImpl implements BeanManager, ExtendedBeanManager {
private List<LifecycleListener> lifecycleListeners = new ArrayList<LifecycleListener>();
@Override
public void registerLifecycleListener(LifecycleListener lifecycleListener) {
lifecycleListeners.add( lifecycleListener );
}
public List<LifecycleListener> getLifecycleListeners() {
return lifecycleListeners;
}
// ~~~~
@Override
public Object getReference(Bean<?> bean, Type beanType, CreationalContext<?> ctx) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Object getInjectableReference(InjectionPoint ij, CreationalContext<?> ctx) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> CreationalContext<T> createCreationalContext(Contextual<T> contextual) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Set<Bean<?>> getBeans(Type beanType, Annotation... qualifiers) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Set<Bean<?>> getBeans(String name) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Bean<?> getPassivationCapableBean(String id) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <X> Bean<? extends X> resolve(Set<Bean<? extends X>> beans) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public void validate(InjectionPoint injectionPoint) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public void fireEvent(Object event, Annotation... qualifiers) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> Set<ObserverMethod<? super T>> resolveObserverMethods(T event, Annotation... qualifiers) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public List<Decorator<?>> resolveDecorators(Set<Type> types, Annotation... qualifiers) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public List<Interceptor<?>> resolveInterceptors(InterceptionType type, Annotation... interceptorBindings) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isScope(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isNormalScope(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isPassivatingScope(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isQualifier(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isInterceptorBinding(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean isStereotype(Class<? extends Annotation> annotationType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Set<Annotation> getInterceptorBindingDefinition(Class<? extends Annotation> bindingType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Set<Annotation> getStereotypeDefinition(Class<? extends Annotation> stereotype) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean areQualifiersEquivalent(Annotation qualifier1, Annotation qualifier2) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public boolean areInterceptorBindingsEquivalent(Annotation interceptorBinding1, Annotation interceptorBinding2) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public int getQualifierHashCode(Annotation qualifier) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public int getInterceptorBindingHashCode(Annotation interceptorBinding) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public Context getContext(Class<? extends Annotation> scopeType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public ELResolver getELResolver() {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public ExpressionFactory wrapExpressionFactory(ExpressionFactory expressionFactory) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> AnnotatedType<T> createAnnotatedType(Class<T> type) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> InjectionTarget<T> createInjectionTarget(AnnotatedType<T> type) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> InjectionTargetFactory<T> getInjectionTargetFactory(AnnotatedType<T> annotatedType) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <X> ProducerFactory<X> getProducerFactory(AnnotatedField<? super X> field, Bean<X> declaringBean) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <X> ProducerFactory<X> getProducerFactory(AnnotatedMethod<? super X> method, Bean<X> declaringBean) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> BeanAttributes<T> createBeanAttributes(AnnotatedType<T> type) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public BeanAttributes<?> createBeanAttributes(AnnotatedMember<?> type) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T> Bean<T> createBean(BeanAttributes<T> attributes, Class<T> beanClass, InjectionTargetFactory<T> injectionTargetFactory) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T, X> Bean<T> createBean(BeanAttributes<T> attributes, Class<X> beanClass, ProducerFactory<X> producerFactory) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public InjectionPoint createInjectionPoint(AnnotatedField<?> field) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public InjectionPoint createInjectionPoint(AnnotatedParameter<?> parameter) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
@Override
public <T extends Extension> T getExtension(Class<T> extensionClass) {
throw new UnsupportedOperationException( "ExtendedBeanManagerImpl here just to gainn access to BeanManager lazily" );
}
}
}

View File

@ -0,0 +1,35 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.wf.ddl;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* Arquillian "component" for testing auto-ddl execution when initiated by the "app"
*
* @author Steve Ebersole
*/
@Stateful
public class WildFlyDdlComponent {
EntityManagerFactory emf;
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
public void start() {
emf = Persistence.createEntityManagerFactory( "pu-wf-ddl" );
}
@Remove
// @TransactionAttribute(TransactionAttributeType.REQUIRED)
public void stop() {
emf.close();
}
}

View File

@ -0,0 +1,20 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.wf.ddl;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Steve Ebersole
*/
@Entity
public class WildFlyDdlEntity {
@Id
Integer id;
String name;
}

View File

@ -0,0 +1,108 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.wf.ddl;
import java.net.URL;
import java.util.Collections;
import javax.annotation.Resource;
import javax.naming.InitialContext;
import javax.persistence.EntityManagerFactory;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor;
import org.hibernate.jpa.boot.internal.PersistenceXmlParser;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.persistence21.PersistenceDescriptor;
import org.jboss.shrinkwrap.descriptor.api.persistence21.PersistenceUnitTransactionType;
import static org.junit.Assert.assertNotNull;
/**
* @author Steve Ebersole
*/
@RunWith( Arquillian.class )
public class WildFlyDdlTest {
public static final String PERSISTENCE_XML_RESOURCE_NAME = "pu-wf-ddl/persistence.xml";
public static final String PERSISTENCE_UNIT_NAME = "pu-wf-ddl";
@Deployment
public static WebArchive buildDeployment() {
WebArchive jar = ShrinkWrap.create( WebArchive.class )
.setManifest( "org/hibernate/test/wf/ddl/manifest.mf" )
.addClass( WildFlyDdlEntity.class )
// .addAsManifestResource( EmptyAsset.INSTANCE, "beans.xml")
.addAsResource( new StringAsset( persistenceXml().exportAsString() ), PERSISTENCE_XML_RESOURCE_NAME )
.addAsResource( "org/hibernate/test/wf/ddl/log4j.properties", "log4j.properties" );
System.out.println( jar.toString(true) );
return jar;
}
private static PersistenceDescriptor persistenceXml() {
final PersistenceDescriptor pd = Descriptors.create( PersistenceDescriptor.class )
.version( "2.1" )
.createPersistenceUnit().name( PERSISTENCE_UNIT_NAME ).transactionType( PersistenceUnitTransactionType._JTA )
.nonJtaDataSource( "java:jboss/datasources/ExampleDS" )
.clazz( WildFlyDdlEntity.class.getName() )
.excludeUnlistedClasses( true )
.getOrCreateProperties().createProperty().name( "jboss.as.jpa.providerModule" ).value( "org.hibernate:5.2" ).up().up()
.getOrCreateProperties().createProperty().name( "hibernate.hbm2ddl.auto" ).value( "create-drop" ).up().up()
// this should not be needed, but...
.getOrCreateProperties().createProperty().name( AvailableSettings.JTA_PLATFORM ).value( JBossAppServerJtaPlatform.class.getName() ).up().up()
.up();
System.out.println( "persistence.xml: " );
pd.exportTo( System.out );
return pd;
}
@ArquillianResource
private InitialContext initialContext;
@Test
public void testCreateThenDrop() throws Exception {
URL persistenceXmlUrl = Thread.currentThread().getContextClassLoader().getResource( PERSISTENCE_XML_RESOURCE_NAME );
if ( persistenceXmlUrl == null ) {
persistenceXmlUrl = Thread.currentThread().getContextClassLoader().getResource( '/' + PERSISTENCE_XML_RESOURCE_NAME );
}
assertNotNull( persistenceXmlUrl );
ParsedPersistenceXmlDescriptor persistenceUnit = PersistenceXmlParser.locateIndividualPersistenceUnit( persistenceXmlUrl );
// creating the EMF causes SchemaCreator to be run...
EntityManagerFactory emf = Bootstrap.getEntityManagerFactoryBuilder( persistenceUnit, Collections.emptyMap() ).build();
// closing the EMF causes the delayed SchemaDropper to be run...
// wrap in a transaction just to see if we can get this to fail in the way the WF report says;
// in my experience however this succeeds with or without the transaction
final TransactionManager tm = emf.unwrap( SessionFactoryImplementor.class ).getServiceRegistry().getService( JtaPlatform.class ).retrieveTransactionManager();
tm.begin();
Transaction txn = tm.getTransaction();
emf.close();
txn.commit();
}
}

View File

@ -0,0 +1,11 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
/**
* Package containing various tests running inside a WildFly container via Arquillian.
*/
package org.hibernate.test.wf;

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later
~ See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
-->
<arquillian
xmlns="http://jboss.org/schema/arquillian"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
<defaultProtocol type="Servlet 3.0" />
<!-- Uncomment in order to inspect deployments -->
<!-- Saves the deployment jar on the filesystem (per this path) for inspection -->
<engine>
<!--<property name="deploymentExportPath">${arquillianDeploymentExportDir}</property>-->
</engine>
<group qualifier="Grid" default="true">
<container qualifier="container.active-1" mode="suite" default="true">
<configuration>
<property name="jbossHome">${wildFlyInstallDir}</property>
<property name="javaVmArguments">
-Djava.net.preferIPv4Stack=true
-Djgroups.bind_addr=127.0.0.1
-Djboss.socket.binding.port-offset=137
<!-- Uncomment for Remote debugging Wildfly -->
<!-- -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y-->
</property>
</configuration>
</container>
</group>
</arquillian>

View File

@ -0,0 +1,23 @@
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later
# See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
#
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=info, stdout
# the test that this is used for is testing DDL execution within WF,
# so for sure we want the schema-tooling logging cranked up...
log4j.logger.org.hibernate.SQL=debug
log4j.logger.org.hibernate.tool.schema=trace
log4j.logger.org.hibernate.tool.hbm2ddl=trace
# low-level "resource" logging is likely to be useful as well
log4j.logger.org.hibernate.resource=trace
log4j.logger.org.hibernate.engine.transaction.jta=trace

View File

@ -0,0 +1 @@
Dependencies: org.hibernate:5.2 services

View File

@ -29,7 +29,16 @@ ext {
moduleXmlStagingDir = file( "$buildDir/tmp/modules" ) moduleXmlStagingDir = file( "$buildDir/tmp/modules" )
wildFlyInstallDir = file( "${rootProject.buildDir}/" ) wildFlyInstallDirBase = rootProject.buildDir
wildFlyInstallDir = "${rootProject.buildDir.absolutePath}/wildfly-${wildflyVersion}"
expandedModuleProperties = [
slot: slot,
minorSlot: minorSlot,
version: rootProject.hibernateTargetVersion,
wildflyVersion: wildflyVersion,
javassistVersion: javassistVersion
];
} }
mavenPom { mavenPom {
@ -43,11 +52,14 @@ configurations {
} }
wildflyDist wildflyDist
javassist
} }
dependencies { dependencies {
jipijapa "org.wildfly:jipijapa-hibernate5:${wildflyVersion}" jipijapa "org.wildfly:jipijapa-hibernate5:${wildflyVersion}"
wildflyDist "org.wildfly:wildfly-dist:${wildflyVersion}@zip" wildflyDist "org.wildfly:wildfly-dist:${wildflyVersion}@zip"
javassist libraries.javassist
testCompile project( ":hibernate-core" ) testCompile project( ":hibernate-core" )
testCompile libraries.junit testCompile libraries.junit
@ -65,8 +77,10 @@ dependencies {
task copyAndExpandModuleXml(type: Copy) { task copyAndExpandModuleXml(type: Copy) {
description 'Performs a copy of the XML files defining the module into a staging directory for the purpose of performing token-replacement' description 'Performs a copy of the XML files defining the module into a staging directory for the purpose of performing token-replacement'
inputs.properties( expandedModuleProperties as Map )
into moduleXmlStagingDir into moduleXmlStagingDir
expand( slot: slot, minorSlot: minorSlot, version: rootProject.hibernateTargetVersion, wildflyVersion: wildflyVersion ) expand( expandedModuleProperties as Map )
into( 'org/hibernate/' + slot ) { into( 'org/hibernate/' + slot ) {
from 'src/main/modules/org/hibernate/core' from 'src/main/modules/org/hibernate/core'
@ -103,6 +117,9 @@ task createModulesZip(type: Zip, dependsOn: [copyAndExpandModuleXml]) {
into( 'org/hibernate/' + slot ) { into( 'org/hibernate/' + slot ) {
from parent.project( 'hibernate-core' ).configurations.archives.allArtifacts.files from parent.project( 'hibernate-core' ).configurations.archives.allArtifacts.files
from parent.project( 'hibernate-envers' ).configurations.archives.allArtifacts.files from parent.project( 'hibernate-envers' ).configurations.archives.allArtifacts.files
// also need Javassist's jar
from configurations.javassist
} }
into( 'org/hibernate/infinispan/' + slot ) { into( 'org/hibernate/infinispan/' + slot ) {
@ -143,21 +160,21 @@ task installWildFly(type: Copy) {
from { from {
configurations.wildflyDist.collect { zipTree(it) } configurations.wildflyDist.collect { zipTree(it) }
} }
into wildFlyInstallDir into wildFlyInstallDirBase
} }
task installHibernateModule( type:Copy, dependsOn: [createModulesZip, installWildFly]) { task installHibernateModule( type:Copy, dependsOn: [createModulesZip, installWildFly]) {
duplicatesStrategy DuplicatesStrategy.EXCLUDE duplicatesStrategy DuplicatesStrategy.EXCLUDE
from zipTree( createModulesZip.archivePath ) from zipTree( createModulesZip.archivePath )
into "${wildFlyInstallDir}/wildfly-${wildflyVersion}/modules" into "${wildFlyInstallDir}/modules"
} }
task prepareWildFlyForTests( dependsOn: [installWildFly, installHibernateModule]) task prepareWildFlyForTests( dependsOn: [installWildFly, installHibernateModule] )
test.dependsOn prepareWildFlyForTests test.dependsOn prepareWildFlyForTests
processTestResources { processTestResources {
expand( buildDir: wildFlyInstallDir, wildflyVersion: wildflyVersion ) expand( wildFlyInstallDir: wildFlyInstallDir, arquillianDeploymentExportDir: "${rootProject.buildDir.absolutePath}/arquillian-deployments" )
} }

View File

@ -9,6 +9,7 @@
<resources> <resources>
<resource-root path="hibernate-core-${version}.jar"/> <resource-root path="hibernate-core-${version}.jar"/>
<resource-root path="hibernate-envers-${version}.jar"/> <resource-root path="hibernate-envers-${version}.jar"/>
<resource-root path="javassist-${javassistVersion}.jar"/>
</resources> </resources>
<dependencies> <dependencies>
@ -23,6 +24,9 @@
<module name="javax.xml.bind.api"/> <module name="javax.xml.bind.api"/>
<module name="org.antlr"/> <module name="org.antlr"/>
<module name="org.dom4j"/> <module name="org.dom4j"/>
<!-- Javassist is handled directly as a resource in order to account for
the likely conflict in Javassist versions
-->
<module name="org.javassist"/> <module name="org.javassist"/>
<module name="org.jboss.as.jpa.spi"/> <module name="org.jboss.as.jpa.spi"/>
<module name="org.jboss.jandex"/> <module name="org.jboss.jandex"/>

View File

@ -15,14 +15,14 @@
<!-- Uncomment in order to inspect deployments --> <!-- Uncomment in order to inspect deployments -->
<!-- <!--
<engine> <engine>
<property name="deploymentExportPath">target/deployments</property> <property name="deploymentExportPath">${arquillianDeploymentExportDir}</property>
</engine> </engine>
--> -->
<group qualifier="Grid" default="true"> <group qualifier="Grid" default="true">
<container qualifier="container.active-1" mode="suite" default="true"> <container qualifier="container.active-1" mode="suite" default="true">
<configuration> <configuration>
<property name="jbossHome">${buildDir}/wildfly-${wildflyVersion}</property> <property name="jbossHome">${wildFlyInstallDir}</property>
<property name="javaVmArguments"> <property name="javaVmArguments">
-Djava.net.preferIPv4Stack=true -Djava.net.preferIPv4Stack=true
-Djgroups.bind_addr=127.0.0.1 -Djgroups.bind_addr=127.0.0.1

View File

@ -18,6 +18,8 @@ ext {
elVersion = '2.2.4' elVersion = '2.2.4'
cdiVersion = '1.1' cdiVersion = '1.1'
javassistVersion = '3.20.0-GA'
// Wildfly version targeted by module ZIP; Arquillian/Shrinkwrap versions used for CDI testing and testing the module ZIP // Wildfly version targeted by module ZIP; Arquillian/Shrinkwrap versions used for CDI testing and testing the module ZIP
wildflyVersion = '10.0.0.Final' wildflyVersion = '10.0.0.Final'
arquillianVersion = '1.1.10.Final' arquillianVersion = '1.1.10.Final'
@ -44,7 +46,7 @@ ext {
dom4j: 'dom4j:dom4j:1.6.1@jar', dom4j: 'dom4j:dom4j:1.6.1@jar',
// Javassist // Javassist
javassist: 'org.javassist:javassist:3.20.0-GA', javassist: "org.javassist:javassist:${javassistVersion}",
// javax // javax
jpa: 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final', jpa: 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final',
@ -132,6 +134,9 @@ ext {
shrinkwrap_descriptors_api_javaee: "org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-javaee:${shrinkwrapDescriptorsVersion}", shrinkwrap_descriptors_api_javaee: "org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-api-javaee:${shrinkwrapDescriptorsVersion}",
shrinkwrap_descriptors_impl_javaee: "org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-impl-javaee:${shrinkwrapDescriptorsVersion}", shrinkwrap_descriptors_impl_javaee: "org.jboss.shrinkwrap.descriptors:shrinkwrap-descriptors-impl-javaee:${shrinkwrapDescriptorsVersion}",
wildfly_arquillian_container_managed: "org.wildfly.arquillian:wildfly-arquillian-container-managed:${wildflyArquillianContainerVersion}" wildfly_arquillian_container_managed: "org.wildfly.arquillian:wildfly-arquillian-container-managed:${wildflyArquillianContainerVersion}",
jboss_ejb_spec_jar : 'org.jboss.spec.javax.ejb:jboss-ejb-api_3.2_spec:1.0.0.Final',
jboss_annotation_spec_jar : 'org.jboss.spec.javax.annotation:jboss-annotations-api_1.2_spec:1.0.0.Final'
] ]
} }