[tx-control] Add XA support for JPA using Hibernate

git-svn-id: https://svn.apache.org/repos/asf/aries/trunk/tx-control@1738630 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/tx-control-api/src/main/java/org/osgi/service/transaction/control/jpa/JPAEntityManagerProviderFactory.java b/tx-control-api/src/main/java/org/osgi/service/transaction/control/jpa/JPAEntityManagerProviderFactory.java
index 483d1e1..5a5fa89 100644
--- a/tx-control-api/src/main/java/org/osgi/service/transaction/control/jpa/JPAEntityManagerProviderFactory.java
+++ b/tx-control-api/src/main/java/org/osgi/service/transaction/control/jpa/JPAEntityManagerProviderFactory.java
@@ -50,6 +50,12 @@
 	 * javax.persistence.jtaDataSource property
 	 */
 	public static final String	TRANSACTIONAL_DB_CONNECTION	= "osgi.jdbc.provider";
+	
+	/**
+	 * The property used to indicate that database connections will be automatically
+	 * enlisted in ongoing transactions without intervention from the JPA provider
+	 */
+	public static final String  PRE_ENLISTED_DB_CONNECTION = "osgi.jdbc.enlisted";
 
 	/**
 	 * Create a private {@link JPAEntityManagerProvider} using an
@@ -74,16 +80,12 @@
 	 * {@link EntityManagerFactory}.
 	 * 
 	 * @param emf
-	 * @param jpaProperties The properties to pass to the
-	 *            {@link EntityManagerFactory} in order to create the underlying
-	 *            {@link EntityManager} instances
 	 * @param resourceProviderProperties Configuration properties to pass to the
 	 *            JDBC Resource Provider runtime
 	 * @return A {@link JPAEntityManagerProvider} that can be used in
 	 *         transactions
 	 */
 	JPAEntityManagerProvider getProviderFor(EntityManagerFactory emf,
-			Map<String,Object> jpaProperties,
 			Map<String,Object> resourceProviderProperties);
 
 }
diff --git a/tx-control-jpa-itests/pom.xml b/tx-control-jpa-itests/pom.xml
index e14040e..aa5e389 100644
--- a/tx-control-jpa-itests/pom.xml
+++ b/tx-control-jpa-itests/pom.xml
@@ -53,6 +53,12 @@
 			<version>0.0.1-SNAPSHOT</version>
 		</dependency>
 		<dependency>
+			<groupId>org.apache.aries.tx-control</groupId>
+			<artifactId>tx-control-service-xa</artifactId>
+			<scope>test</scope>
+			<version>0.0.1-SNAPSHOT</version>
+		</dependency>
+		<dependency>
 			<groupId>org.apache.felix</groupId>
 			<artifactId>org.apache.felix.coordinator</artifactId>
 			<scope>test</scope>
@@ -71,6 +77,12 @@
 			<version>0.0.1-SNAPSHOT</version>
 		</dependency>
 		<dependency>
+			<groupId>org.apache.aries.tx-control</groupId>
+			<artifactId>tx-control-provider-jpa-xa</artifactId>
+			<scope>test</scope>
+			<version>0.0.1-SNAPSHOT</version>
+		</dependency>
+		<dependency>
             <groupId>org.eclipse.persistence</groupId>
             <artifactId>javax.persistence</artifactId>
 			<scope>test</scope>
diff --git a/tx-control-jpa-itests/src/test/java/org/apache/aries/tx/control/itests/AbstractJPATransactionTest.java b/tx-control-jpa-itests/src/test/java/org/apache/aries/tx/control/itests/AbstractJPATransactionTest.java
index a778fd2..9d7bfe7 100644
--- a/tx-control-jpa-itests/src/test/java/org/apache/aries/tx/control/itests/AbstractJPATransactionTest.java
+++ b/tx-control-jpa-itests/src/test/java/org/apache/aries/tx/control/itests/AbstractJPATransactionTest.java
@@ -18,6 +18,7 @@
  */

 package org.apache.aries.tx.control.itests;

 

+import static java.lang.Boolean.getBoolean;

 import static org.ops4j.pax.exam.CoreOptions.junitBundles;

 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;

 import static org.ops4j.pax.exam.CoreOptions.options;

@@ -54,7 +55,9 @@
 @ExamReactorStrategy(PerClass.class)

 public abstract class AbstractJPATransactionTest extends AbstractIntegrationTest {

 

+	protected static final String TX_CONTROL_FILTER = "tx.control.filter";

 	protected static final String ARIES_EMF_BUILDER_TARGET_FILTER = "aries.emf.builder.target.filter";

+	protected static final String IS_XA = "aries.test.is.xa";

 

 	protected TransactionControl txControl;

 

@@ -65,7 +68,7 @@
 	@Before

 	public void setUp() throws Exception {

 		

-		txControl = context().getService(TransactionControl.class, 5000);

+		txControl = context().getService(TransactionControl.class, System.getProperty(TX_CONTROL_FILTER), 5000);

 		

 		server = Server.createTcpServer("-tcpPort", "0");

 		server.start();

@@ -102,7 +105,8 @@
 		

 		ConfigurationAdmin cm = context().getService(ConfigurationAdmin.class, 5000);

 		

-		String pid = "org.apache.aries.tx.control.jpa.local"; 

+		String pid = getBoolean(IS_XA) ? "org.apache.aries.tx.control.jpa.xa" :

+				"org.apache.aries.tx.control.jpa.local"; 

 		

 		System.out.println("Configuring connection provider with pid " + pid);

 		

@@ -180,22 +184,60 @@
 				mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),

 				mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject()

 				

-				,CoreOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005")

+//				,CoreOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005")

+				);

+	}

+

+	@Configuration

+	public Option[] xaTxConfiguration() {

+		String localRepo = System.getProperty("maven.repo.local");

+		if (localRepo == null) {

+			localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository");

+		}

+		

+		return options(junitBundles(), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"),

+				when(localRepo != null)

+				.useOptions(CoreOptions.vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)),

+				mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(),

+				systemProperty(IS_XA).value(Boolean.TRUE.toString()),

+				xaTxControlService(),

+				xaJpaResourceProviderWithH2(),

+				jpaProvider(),

+				ariesJPA(),

+				mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject(),

+				mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(),

+				mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject()

+				

+//				,CoreOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005")

 				);

 	}

 

 	public Option localTxControlService() {

 		return CoreOptions.composite(

+				systemProperty(TX_CONTROL_FILTER).value("(osgi.local.enabled=true)"),

 				mavenBundle("org.apache.felix", "org.apache.felix.coordinator").versionAsInProject(),

 				mavenBundle("org.apache.aries.tx-control", "tx-control-service-local").versionAsInProject());

 	}

 

+	public Option xaTxControlService() {

+		return CoreOptions.composite(

+				systemProperty(TX_CONTROL_FILTER).value("(osgi.xa.enabled=true)"),

+				mavenBundle("org.apache.felix", "org.apache.felix.coordinator").versionAsInProject(),

+				mavenBundle("org.apache.aries.tx-control", "tx-control-service-xa").versionAsInProject());

+	}

+

 	public Option localJpaResourceProviderWithH2() {

 		return CoreOptions.composite(

 				mavenBundle("com.h2database", "h2").versionAsInProject(),

 				mavenBundle("org.apache.aries.tx-control", "tx-control-provider-jpa-local").versionAsInProject());

 	}

 	

+	public Option xaJpaResourceProviderWithH2() {

+		return CoreOptions.composite(

+				mavenBundle("com.h2database", "h2").versionAsInProject(),

+				mavenBundle("org.apache.aries.tx-control", "tx-control-provider-jpa-xa").versionAsInProject());

+	}

+	

 	public Option ariesJPA() {

 		return mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container", ariesJPAVersion());

 	}

diff --git a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAConnectionWrapper.java b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XAConnectionWrapper.java
similarity index 91%
rename from tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAConnectionWrapper.java
rename to tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XAConnectionWrapper.java
index 31c81cd..f1f0812 100644
--- a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAConnectionWrapper.java
+++ b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XAConnectionWrapper.java
@@ -1,4 +1,4 @@
-package org.apache.aries.tx.control.jdbc.xa.impl;
+package org.apache.aries.tx.control.jdbc.xa.connection.impl;
 
 import java.sql.Connection;
 import java.sql.SQLException;
diff --git a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XADataSourceMapper.java b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XADataSourceMapper.java
similarity index 96%
rename from tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XADataSourceMapper.java
rename to tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XADataSourceMapper.java
index 791dcb3..ec38ee6 100644
--- a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XADataSourceMapper.java
+++ b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/connection/impl/XADataSourceMapper.java
@@ -1,4 +1,4 @@
-package org.apache.aries.tx.control.jdbc.xa.impl;
+package org.apache.aries.tx.control.jdbc.xa.connection.impl;
 
 import java.io.PrintWriter;
 import java.sql.Connection;
diff --git a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/JDBCConnectionProviderFactoryImpl.java b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/JDBCConnectionProviderFactoryImpl.java
index fbafd15..d73cc2e 100644
--- a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/JDBCConnectionProviderFactoryImpl.java
+++ b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/JDBCConnectionProviderFactoryImpl.java
@@ -15,6 +15,7 @@
 import javax.sql.XADataSource;
 
 import org.apache.aries.tx.control.jdbc.common.impl.DriverDataSource;
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XADataSourceMapper;
 import org.osgi.service.jdbc.DataSourceFactory;
 import org.osgi.service.transaction.control.TransactionException;
 import org.osgi.service.transaction.control.jdbc.JDBCConnectionProvider;
diff --git a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnection.java b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnection.java
index e6c4978..c62c367 100644
--- a/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnection.java
+++ b/tx-control-provider-jdbc-xa/src/main/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnection.java
@@ -12,6 +12,7 @@
 import org.apache.aries.tx.control.jdbc.common.impl.ConnectionWrapper;
 import org.apache.aries.tx.control.jdbc.common.impl.ScopedConnectionWrapper;
 import org.apache.aries.tx.control.jdbc.common.impl.TxConnectionWrapper;
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XAConnectionWrapper;
 import org.osgi.service.transaction.control.LocalResource;
 import org.osgi.service.transaction.control.TransactionContext;
 import org.osgi.service.transaction.control.TransactionControl;
diff --git a/tx-control-provider-jdbc-xa/src/test/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnectionTest.java b/tx-control-provider-jdbc-xa/src/test/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnectionTest.java
index 9b367f3..b7c5916 100644
--- a/tx-control-provider-jdbc-xa/src/test/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnectionTest.java
+++ b/tx-control-provider-jdbc-xa/src/test/java/org/apache/aries/tx/control/jdbc/xa/impl/XAEnabledTxContextBindingConnectionTest.java
@@ -15,6 +15,7 @@
 import javax.sql.XADataSource;
 import javax.transaction.xa.XAResource;
 
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XADataSourceMapper;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/tx-control-provider-jpa-local/src/main/java/org/apache/aries/tx/control/jpa/local/impl/JPAEntityManagerProviderFactoryImpl.java b/tx-control-provider-jpa-local/src/main/java/org/apache/aries/tx/control/jpa/local/impl/JPAEntityManagerProviderFactoryImpl.java
index 93bb9f0..bc4bc6b 100644
--- a/tx-control-provider-jpa-local/src/main/java/org/apache/aries/tx/control/jpa/local/impl/JPAEntityManagerProviderFactoryImpl.java
+++ b/tx-control-provider-jpa-local/src/main/java/org/apache/aries/tx/control/jpa/local/impl/JPAEntityManagerProviderFactoryImpl.java
@@ -46,7 +46,7 @@
 	}
 
 	@Override
-	public JPAEntityManagerProvider getProviderFor(EntityManagerFactory emf, Map<String, Object> jpaProperties,
+	public JPAEntityManagerProvider getProviderFor(EntityManagerFactory emf,
 			Map<String, Object> resourceProviderProperties) {
 		checkEnlistment(resourceProviderProperties);
 		validateEMF(emf);
diff --git a/tx-control-provider-jpa-xa/.gitignore b/tx-control-provider-jpa-xa/.gitignore
new file mode 100644
index 0000000..b83d222
--- /dev/null
+++ b/tx-control-provider-jpa-xa/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/tx-control-provider-jpa-xa/LICENSE b/tx-control-provider-jpa-xa/LICENSE
new file mode 100644
index 0000000..6b0b127
--- /dev/null
+++ b/tx-control-provider-jpa-xa/LICENSE
@@ -0,0 +1,203 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
diff --git a/tx-control-provider-jpa-xa/NOTICE b/tx-control-provider-jpa-xa/NOTICE
new file mode 100644
index 0000000..424644d
--- /dev/null
+++ b/tx-control-provider-jpa-xa/NOTICE
@@ -0,0 +1,8 @@
+
+Apache Aries
+Copyright 2009-2011 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+
diff --git a/tx-control-provider-jpa-xa/README.md b/tx-control-provider-jpa-xa/README.md
new file mode 100644
index 0000000..043548e
--- /dev/null
+++ b/tx-control-provider-jpa-xa/README.md
@@ -0,0 +1,174 @@
+Sample OSGi Transaction Control JPA Provider (XA)
+-------------------------------------------------
+
+This module is a prototype implementation of the OSGi Transaction Control JPA resource provider. It supports JPA 2.1 using XA transactions, and is tested against Hibernate 5.0.9, EclipseLink 2.6.0 and OpenJPA 2.4.1.
+
+The Transaction Control Service (RFC-221) is an in-progress RFC publicly available from the OSGi Alliance: https://github.com/osgi/design/blob/master/rfcs/rfc0221/rfc-0221-TransactionControl.pdf
+
+Given that the RFC is non-final the OSGi API declared in this project is subject to change at any time up to its official release. Also the behaviour of this implementation may not always be up-to-date with the latest wording in the RFC. The project maintainers will, however try to keep pace with the RFC, and to ensure that the implementations are compliant with any OSGi specifications that result from the RFC.
+
+# When should I use this module?
+
+If two-phase commit is needed across multiple resources then it is best to pair this module with the tx-control-service-xa bundle.
+
+If you wish to use entirely lightweight, resource-local transactions then then the tx-control-service-local and tx-control-provider-jpa-local bundles should be used instead of this bundle
+
+# Using the JPA Provider bundle
+
+This Resource Provider is used in conjunction with a TransactionControl service to provide scoped access to a JPA EntityManager.
+
+## Prerequisites
+
+In order to use scoped JPA access the runtime must contain a JPA provider (for example Hibernate), an implementation of the OSGi JPA service (e.g. Aries JPA), and a persistence bundle.
+
+### Suitable Persistence bundles
+
+OSGi Persistence bundles contain the persistence descriptor (typically an XML file called META-INF/persistence.xml), all of the JPA Entities, and a Meta-Persistence header pointing at the persistence descriptor. (See the JPA service specification for more details).
+
+Unlike "normal" JPA it is usually best not to fully declare the persistence unit in the persistence descriptor. In particular it is a good idea to avoid putting any database configuration in the persistence unit. By not configuring the database inside the bundle the persistence unit remains decoupled, and can be reconfigured for any database at runtime.
+
+For example the following persistence unit:
+
+    <persistence-unit name="test-unit"/>
+
+can be reconfigured to use any database and create/drop tables as appropriate. Configuration for the persistence unit can be provided using Configuration Admin and the EntityManagerFactory Builder.
+
+
+## Creating a resource programmatically
+
+Preparing a resource for use is very simple. Create a JPAEntityManagerProvider using the the JPAEntityManagerProviderFactory, then connect the provider to a TransactionControl service. This will return a thread-safe JPA EntityManager that can then be used in any ongoing scoped work.
+
+The normal inputs to a JPAEntityManagerProviderFactory are an EntityManagerFactoryBuilder, some JPA properties to connect to the database with, and some properties to control the resource provider.
+
+    @Reference
+    TransactionControl txControl;
+
+    @Reference
+    DataSourceFactory dsf;
+
+    @Reference
+    EntityManagerFactoryBuilder emfb;
+
+    @Reference
+    JPAEntityManagerProviderFactory providerFactory;
+
+    EntityManager em;
+
+    @Activate
+    void start(Config config) {
+
+        Properties jdbcProps = new Properties();
+        jdbcProps.put(JDBC_URL, config.url());
+        jdbcProps.put(JDBC_USER, config.user());
+        jdbcProps.put(JDBC_PASSWORD, config._password());
+
+        Map<String, Object> jpaProps = new HashMap<>();
+        jpaProps.put("javax.persistence.nonJtaDataSource", 
+                    dsf.createDataSource(jdbcProps));
+
+        em = providerFactory.getProviderFor(emfb, jpaProps,
+                    null).getResource(txControl);
+    }
+
+    public void findUserName(String id) {
+        txControl.required(() -> {
+                // Use the EntityManager in here
+            });
+    } 
+
+If the JPA EntityManagerFactory is already configured then it can be passed into the JPAEntityManagerProviderFactory instead of an EntityManagerFactoryBuilder and JPA configuration.
+
+
+## Creating a resource using a factory configuration
+
+Whilst it is simple to use a EntityManagerFactoryBuilder it does require some lifecycle code to be written. It is therefore possible to directly create JPA resources using factory configurations. When created, the factory service will listen for an applicable EntityManagerFactoryBuilder and potentially also a DataSourceFactory. Once suitable services are available then a JPAEntityManagerProvider service will be published. 
+
+Configuration properties (except the JPA/JDBC password) are set as service properties for the registered JPAEntityManagerProvider. These properties may therefore be used in filters to select a particular provider.
+
+    @Reference
+    TransactionControl txControl;
+
+    @Reference(target="(osgi.unit.name=test-unit)")
+    JPAEntityManagerProvider provider;
+
+    EntityManager em;
+
+    @Activate
+    void start(Config config) {
+        em = provider.getResource(txControl);
+    }
+
+    public void findUserName(String id) {
+        txControl.required(() -> {
+                // Use the connection in here
+            });
+    } 
+
+
+
+The factory pid is _org.apache.aries.tx.control.jpa.local_ and it may use the following properties (all optional aside from *osgi.unit.name*):
+
+### Resource Provider properties
+
+* *osgi.unit.name* : The name of the persistence unit that this configuration relates to.
+
+* *aries.emf.builder.target.filter* : The target filter to use when searching for an EntityManagerFactoryBuilder. If not specified then any builder for the named persistence unit will be used.
+
+* *aries.jpa.property.names* : The names of the properties to pass to the EntityManagerFactoryBuilder when creating the EntityManagerFactory. By default all properties are copied.
+
+* *aries.dsf.target.filter* : The target filter to use when searching for a DataSourceFactory. If not specified then *osgi.jdbc.driver.class* must be specified.
+
+* *aries.jdbc.property.names* : The names of the properties to pass to the DataSourceFactory when creating the JDBC resources.
+
+* *osgi.jdbc.driver.class* : Used to locate the DataSourceFactory service if the *aries.dsf.target.filter* is not set.
+
+* *osgi.local.enabled* : Defaults to false. If true then resource creation will fail
+
+* *osgi.xa.enabled* : Defaults to true. If false then resource creation will fail
+
+* *osgi.connection.pooling.enabled* : Defaults to true. If true then the Database connections will be pooled.
+
+* *osgi.connection.max* : Defaults to 10. The maximum number of connections that should be kept in the pool
+
+* *osgi.connection.min* : Defaults to 10. The minimum number of connections that should be kept in the pool
+
+* *osgi.connection.timeout* : Defaults to 30,000 (30 seconds). The maximum time in milliseconds to block when waiting for a database connection
+
+* *osgi.idle.timeout* : Defaults to 180,000 (3 minutes). The time in milliseconds before an idle connection is eligible to be closed.
+
+* *osgi.connection.timeout* : Defaults to 10,800,000 (3 hours). The maximum time in milliseconds that a connection may remain open before being closed.
+
+
+### JDBC properties
+
+The following properties will automatically be passed to the DataSourceFactory if they are present. The list of properties may be overridden using the *aries.jdbc.property.names* property if necessary.
+
+* *databaseName* : The name of the database
+
+* *dataSourceName* : The name of the dataSource that will be created
+
+* *description* : A description of the dataSource being created
+
+* *networkProtocol* : The network protocol to use.
+
+* *portNumber* : The port number to use
+
+* *roleName* : The name of the JDBC role
+
+* *serverName* : The name of the database server
+
+* *url* : The JDBC url to use (often used instead of other properties such as *serverName*, *portNumber* and *databaseName*).
+
+* *user* : The JDBC user
+
+* *password* : The JDBC password
+
+
+### JPA properties
+
+The following properties are potentially useful when configuring JPA:
+
+*javax.persistence.schema-generation.database.action* : May be used to automatically create the database tables (see the OSGi spec)
+
+* Other provider specific properties, for example configuring second-level caching.
+
diff --git a/tx-control-provider-jpa-xa/pom.xml b/tx-control-provider-jpa-xa/pom.xml
new file mode 100644
index 0000000..263413f
--- /dev/null
+++ b/tx-control-provider-jpa-xa/pom.xml
@@ -0,0 +1,209 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<parent>
+		<groupId>org.apache.aries</groupId>
+		<artifactId>parent</artifactId>
+		<version>2.0.1</version>
+		<relativePath>../../parent/pom.xml</relativePath>
+	</parent>
+	<groupId>org.apache.aries.tx-control</groupId>
+	<artifactId>tx-control-provider-jpa-xa</artifactId>
+	<packaging>bundle</packaging>
+	<name>OSGi Transaction Control JPA Resource Provider - XA Transactions</name>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<description>
+        This bundle contains a JPA resource provider for use with the OSGi Transaction Control Service that supports XA transactions.
+    </description>
+
+	<scm>
+		<connection>
+            scm:svn:http://svn.apache.org/repos/asf/aries/trunk/tx-control/tx-control-provider-jpa-xa
+        </connection>
+		<developerConnection>
+            scm:svn:https://svn.apache.org/repos/asf/aries/trunk/tx-control/tx-control-provider-jpa-xa
+        </developerConnection>
+		<url>
+            http://svn.apache.org/viewvc/aries/trunk/tx-control/tx-control-provider-jpa-xa
+        </url>
+	</scm>
+
+	<properties>
+		<aries.osgi.activator>
+			org.apache.aries.tx.control.jpa.xa.impl.Activator
+		</aries.osgi.activator>
+		<!-- We keep the versioning from Geronimo as it makes most things work, 
+		     even though everything should use the JavaJPA contract -->
+		<aries.osgi.export.pkg>
+			org.osgi.service.transaction.control.jpa,
+			org.osgi.service.cm,
+			org.osgi.service.jdbc,
+			org.osgi.service.jpa,
+			javax.persistence;version=1.2;jpa=2.1, 
+			javax.persistence.criteria;version=1.2;jpa=2.1, 
+			javax.persistence.metamodel;version=1.2;jpa=2.1, 
+			javax.persistence.spi;version=1.2;jpa=2.1, 
+			javax.persistence;version=2.1, 
+			javax.persistence.criteria;version=2.1, 
+			javax.persistence.metamodel;version=2.1, 
+			javax.persistence.spi;version=2.1
+		</aries.osgi.export.pkg>
+		<aries.osgi.private.pkg>
+			org.apache.aries.tx.control.jdbc.common.impl,
+			org.apache.aries.tx.control.jdbc.xa.connection.impl,
+			org.apache.aries.tx.control.jpa.*,
+			org.apache.geronimo.osgi.locator,
+			org.apache.geronimo.specs.jpa,
+			com.zaxxer.hikari,
+			com.zaxxer.hikari.metrics,
+			com.zaxxer.hikari.pool,
+			com.zaxxer.hikari.util
+		</aries.osgi.private.pkg>
+		<aries.osgi.import.pkg>
+			!com.codahale.*,
+			!com.zaxxer.hikari.metrics.dropwizard,
+			!javassist.*,
+			!javax.transaction,
+			!org.apache.geronimo.osgi.registry.api,
+			!org.hibernate.*,
+			javax.persistence;version="0.0.0",
+			javax.persistence.criteria;version="0.0.0",
+			javax.persistence.metamodel;version="0.0.0",
+			javax.persistence.spi;version="0.0.0",
+			org.osgi.service.transaction.control;version="[0.0.1,0.0.2)",
+			org.osgi.service.transaction.control.jpa;version="[0.0.1,0.0.2)",
+			org.osgi.service.cm,
+			org.osgi.service.jdbc,
+			org.osgi.service.jpa,
+			*
+		</aries.osgi.import.pkg>
+		<lastReleaseVersion>0.0.1-SNAPSHOT</lastReleaseVersion>
+	</properties>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.slf4j</groupId>
+			<artifactId>slf4j-api</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.aries.tx-control</groupId>
+			<artifactId>tx-control-api</artifactId>
+			<version>0.0.1-SNAPSHOT</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.eclipse.persistence</groupId>
+			<artifactId>org.eclipse.persistence.core</artifactId>
+			<version>2.0.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.hibernate</groupId>
+			<artifactId>hibernate-core</artifactId>
+			<version>5.0.0.Final</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.aries.tx-control</groupId>
+			<artifactId>tx-control-provider-jdbc-common</artifactId>
+			<version>0.0.1-SNAPSHOT</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.aries.tx-control</groupId>
+			<artifactId>tx-control-provider-jdbc-xa</artifactId>
+			<version>0.0.1-SNAPSHOT</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.osgi</groupId>
+			<artifactId>org.osgi.service.jdbc</artifactId>
+			<version>1.0.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.geronimo.specs</groupId>
+			<artifactId>geronimo-jpa_2.1_spec</artifactId>
+			<version>1.0-alpha-1</version>
+		</dependency>
+		<dependency>
+			<groupId>org.osgi</groupId>
+			<artifactId>org.osgi.service.jpa</artifactId>
+			<version>1.0.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.osgi</groupId>
+			<artifactId>org.osgi.service.cm</artifactId>
+			<version>1.5.0</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.osgi</groupId>
+			<artifactId>org.osgi.util.tracker</artifactId>
+			<version>1.5.1</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.osgi</groupId>
+			<artifactId>org.osgi.core</artifactId>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>com.zaxxer</groupId>
+			<artifactId>HikariCP</artifactId>
+			<version>2.4.3</version>
+			<scope>provided</scope>
+		</dependency>
+		<dependency>
+			<groupId>junit</groupId>
+			<artifactId>junit</artifactId>
+			<scope>test</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.mockito</groupId>
+			<artifactId>mockito-all</artifactId>
+			<version>1.9.5</version>
+			<scope>test</scope>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<artifactId>maven-compiler-plugin</artifactId>
+				<configuration>
+					<source>1.8</source>
+					<target>1.8</target>
+				</configuration>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.aries.versioning</groupId>
+				<artifactId>org.apache.aries.versioning.plugin</artifactId>
+				<executions>
+					<execution>
+						<id>default-verify</id>
+						<phase>verify</phase>
+						<goals>
+							<goal>version-check</goal>
+						</goals>
+					</execution>
+				</executions>
+			</plugin>
+			<plugin>
+				<groupId>org.apache.felix</groupId>
+				<artifactId>maven-bundle-plugin</artifactId>
+				<!-- We have to use a newer bnd due to a bug in its handling of
+				     provided contract version lists -->
+				<version>3.0.1</version>
+				<configuration>
+					<instructions>
+						<Provide-Capability>osgi.contract;osgi.contract="JavaJPA";version:List&lt;Version&gt;="1.0,2.0,2.1";uses:="javax.persistence,javax.persistence.criteria,javax.persistence.metamodel,javax.persistence.spi"</Provide-Capability>
+						<Require-Capability>osgi.contract;filter:="(&amp;(osgi.contract=JavaJPA)(version=2.1))"</Require-Capability>
+					</instructions>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+</project>
\ No newline at end of file
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/EntityManagerWrapper.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/EntityManagerWrapper.java
new file mode 100644
index 0000000..c6aa020
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/EntityManagerWrapper.java
@@ -0,0 +1,229 @@
+package org.apache.aries.tx.control.jpa.common.impl;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityGraph;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.FlushModeType;
+import javax.persistence.LockModeType;
+import javax.persistence.Query;
+import javax.persistence.StoredProcedureQuery;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaDelete;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.CriteriaUpdate;
+import javax.persistence.metamodel.Metamodel;
+
+public abstract class EntityManagerWrapper implements EntityManager {
+
+	public void persist(Object entity) {
+		getRealEntityManager().persist(entity);
+	}
+
+	public <T> T merge(T entity) {
+		return getRealEntityManager().merge(entity);
+	}
+
+	public void remove(Object entity) {
+		getRealEntityManager().remove(entity);
+	}
+
+	public <T> T find(Class<T> entityClass, Object primaryKey) {
+		return getRealEntityManager().find(entityClass, primaryKey);
+	}
+
+	public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties) {
+		return getRealEntityManager().find(entityClass, primaryKey, properties);
+	}
+
+	public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) {
+		return getRealEntityManager().find(entityClass, primaryKey, lockMode);
+	}
+
+	public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties) {
+		return getRealEntityManager().find(entityClass, primaryKey, lockMode, properties);
+	}
+
+	public <T> T getReference(Class<T> entityClass, Object primaryKey) {
+		return getRealEntityManager().getReference(entityClass, primaryKey);
+	}
+
+	public void flush() {
+		getRealEntityManager().flush();
+	}
+
+	public void setFlushMode(FlushModeType flushMode) {
+		getRealEntityManager().setFlushMode(flushMode);
+	}
+
+	public FlushModeType getFlushMode() {
+		return getRealEntityManager().getFlushMode();
+	}
+
+	public void lock(Object entity, LockModeType lockMode) {
+		getRealEntityManager().lock(entity, lockMode);
+	}
+
+	public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
+		getRealEntityManager().lock(entity, lockMode, properties);
+	}
+
+	public void refresh(Object entity) {
+		getRealEntityManager().refresh(entity);
+	}
+
+	public void refresh(Object entity, Map<String, Object> properties) {
+		getRealEntityManager().refresh(entity, properties);
+	}
+
+	public void refresh(Object entity, LockModeType lockMode) {
+		getRealEntityManager().refresh(entity, lockMode);
+	}
+
+	public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
+		getRealEntityManager().refresh(entity, lockMode, properties);
+	}
+
+	public void clear() {
+		getRealEntityManager().clear();
+	}
+
+	public void detach(Object entity) {
+		getRealEntityManager().detach(entity);
+	}
+
+	public boolean contains(Object entity) {
+		return getRealEntityManager().contains(entity);
+	}
+
+	public LockModeType getLockMode(Object entity) {
+		return getRealEntityManager().getLockMode(entity);
+	}
+
+	public void setProperty(String propertyName, Object value) {
+		getRealEntityManager().setProperty(propertyName, value);
+	}
+
+	public Map<String, Object> getProperties() {
+		return getRealEntityManager().getProperties();
+	}
+
+	public Query createQuery(String qlString) {
+		return getRealEntityManager().createQuery(qlString);
+	}
+
+	public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) {
+		return getRealEntityManager().createQuery(criteriaQuery);
+	}
+
+	public Query createQuery(@SuppressWarnings("rawtypes") CriteriaUpdate updateQuery) {
+		return getRealEntityManager().createQuery(updateQuery);
+	}
+
+	public Query createQuery(@SuppressWarnings("rawtypes") CriteriaDelete deleteQuery) {
+		return getRealEntityManager().createQuery(deleteQuery);
+	}
+
+	public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) {
+		return getRealEntityManager().createQuery(qlString, resultClass);
+	}
+
+	public Query createNamedQuery(String name) {
+		return getRealEntityManager().createNamedQuery(name);
+	}
+
+	public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) {
+		return getRealEntityManager().createNamedQuery(name, resultClass);
+	}
+
+	public Query createNativeQuery(String sqlString) {
+		return getRealEntityManager().createNativeQuery(sqlString);
+	}
+
+	public Query createNativeQuery(String sqlString, @SuppressWarnings("rawtypes") Class resultClass) {
+		return getRealEntityManager().createNativeQuery(sqlString, resultClass);
+	}
+
+	public Query createNativeQuery(String sqlString, String resultSetMapping) {
+		return getRealEntityManager().createNativeQuery(sqlString, resultSetMapping);
+	}
+
+	public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
+		return getRealEntityManager().createNamedStoredProcedureQuery(name);
+	}
+
+	public StoredProcedureQuery createStoredProcedureQuery(String procedureName) {
+		return getRealEntityManager().createStoredProcedureQuery(procedureName);
+	}
+
+	public StoredProcedureQuery createStoredProcedureQuery(String procedureName, @SuppressWarnings("rawtypes") Class... resultClasses) {
+		return getRealEntityManager().createStoredProcedureQuery(procedureName, resultClasses);
+	}
+
+	public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) {
+		return getRealEntityManager().createStoredProcedureQuery(procedureName, resultSetMappings);
+	}
+
+	public void joinTransaction() {
+		getRealEntityManager().joinTransaction();
+	}
+
+	public boolean isJoinedToTransaction() {
+		return getRealEntityManager().isJoinedToTransaction();
+	}
+
+	public <T> T unwrap(Class<T> cls) {
+		return getRealEntityManager().unwrap(cls);
+	}
+
+	public Object getDelegate() {
+		return getRealEntityManager().getDelegate();
+	}
+
+	public void close() {
+		getRealEntityManager().close();
+	}
+
+	public boolean isOpen() {
+		return getRealEntityManager().isOpen();
+	}
+
+	public EntityTransaction getTransaction() {
+		return getRealEntityManager().getTransaction();
+	}
+
+	public EntityManagerFactory getEntityManagerFactory() {
+		return getRealEntityManager().getEntityManagerFactory();
+	}
+
+	public CriteriaBuilder getCriteriaBuilder() {
+		return getRealEntityManager().getCriteriaBuilder();
+	}
+
+	public Metamodel getMetamodel() {
+		return getRealEntityManager().getMetamodel();
+	}
+
+	public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
+		return getRealEntityManager().createEntityGraph(rootType);
+	}
+
+	public EntityGraph<?> createEntityGraph(String graphName) {
+		return getRealEntityManager().createEntityGraph(graphName);
+	}
+
+	public EntityGraph<?> getEntityGraph(String graphName) {
+		return getRealEntityManager().getEntityGraph(graphName);
+	}
+
+	public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
+		return getRealEntityManager().getEntityGraphs(entityClass);
+	}
+
+	protected abstract EntityManager getRealEntityManager();
+
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/ScopedEntityManagerWrapper.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/ScopedEntityManagerWrapper.java
new file mode 100644
index 0000000..38f9232
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/ScopedEntityManagerWrapper.java
@@ -0,0 +1,33 @@
+package org.apache.aries.tx.control.jpa.common.impl;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TransactionRequiredException;
+
+public class ScopedEntityManagerWrapper extends EntityManagerWrapper {
+
+	private final EntityManager entityManager;
+	
+	public ScopedEntityManagerWrapper(EntityManager entityManager) {
+		this.entityManager = entityManager;
+	}
+
+	@Override
+	protected EntityManager getRealEntityManager() {
+		return entityManager;
+	}
+
+	@Override
+	public void close() {
+		// A no op
+	}
+
+	@Override
+	public void joinTransaction() {
+		throw new TransactionRequiredException("This EntityManager is being used in the No Transaction scope. There is no transaction to join.");
+	}
+
+	@Override
+	public boolean isJoinedToTransaction() {
+		return false;
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/TxEntityManagerWrapper.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/TxEntityManagerWrapper.java
new file mode 100644
index 0000000..5989b89
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/common/impl/TxEntityManagerWrapper.java
@@ -0,0 +1,40 @@
+package org.apache.aries.tx.control.jpa.common.impl;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityTransaction;
+
+import org.osgi.service.transaction.control.TransactionException;
+
+public class TxEntityManagerWrapper extends EntityManagerWrapper {
+
+	private final EntityManager entityManager;
+	
+	public TxEntityManagerWrapper(EntityManager entityManager) {
+		this.entityManager = entityManager;
+	}
+
+	@Override
+	protected EntityManager getRealEntityManager() {
+		return entityManager;
+	}
+
+	@Override
+	public void close() {
+		// A no-op
+	}
+
+	@Override
+	public void joinTransaction() {
+		// A no-op
+	}
+
+	@Override
+	public boolean isJoinedToTransaction() {
+		return true;
+	}
+
+	@Override
+	public EntityTransaction getTransaction() {
+		throw new TransactionException("Programmatic transaction management is not supported for a Transactional EntityManager");
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/eclipse/impl/EclipseTxControlPlatform.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/eclipse/impl/EclipseTxControlPlatform.java
new file mode 100644
index 0000000..4d12cac
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/eclipse/impl/EclipseTxControlPlatform.java
@@ -0,0 +1,13 @@
+//package org.apache.aries.tx.control.jpa.xa.eclipse.impl;
+//
+//import org.eclipse.persistence.platform.server.ServerPlatformBase;
+//
+//public class EclipseTxControlPlatform extends ServerPlatformBase {
+//
+//	@Override
+//	public Class getExternalTransactionControllerClass() {
+//		// TODO Auto-generated method stub
+//		return null;
+//	}
+//
+//}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/hibernate/impl/HibernateTxControlPlatform.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/hibernate/impl/HibernateTxControlPlatform.java
new file mode 100644
index 0000000..d63bd2d
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/hibernate/impl/HibernateTxControlPlatform.java
@@ -0,0 +1,275 @@
+package org.apache.aries.tx.control.jpa.xa.hibernate.impl;
+
+import static javax.transaction.Status.STATUS_COMMITTED;
+import static javax.transaction.Status.STATUS_ROLLEDBACK;
+import static javax.transaction.Status.STATUS_UNKNOWN;
+import static org.hibernate.ConnectionAcquisitionMode.AS_NEEDED;
+import static org.hibernate.ConnectionReleaseMode.AFTER_STATEMENT;
+import static org.osgi.service.transaction.control.TransactionStatus.COMMITTED;
+
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import javax.persistence.TransactionRequiredException;
+import javax.transaction.Synchronization;
+
+import org.hibernate.ConnectionAcquisitionMode;
+import org.hibernate.ConnectionReleaseMode;
+import org.hibernate.HibernateException;
+import org.hibernate.engine.transaction.spi.IsolationDelegate;
+import org.hibernate.engine.transaction.spi.TransactionObserver;
+import org.hibernate.jdbc.WorkExecutor;
+import org.hibernate.jdbc.WorkExecutorVisitable;
+import org.hibernate.resource.jdbc.spi.JdbcSessionOwner;
+import org.hibernate.resource.transaction.SynchronizationRegistry;
+import org.hibernate.resource.transaction.TransactionCoordinator;
+import org.hibernate.resource.transaction.TransactionCoordinator.TransactionDriver;
+import org.hibernate.resource.transaction.TransactionCoordinatorBuilder;
+import org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner;
+import org.osgi.service.transaction.control.TransactionContext;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionStatus;
+
+public class HibernateTxControlPlatform implements TransactionCoordinatorBuilder {
+	
+	private static final long serialVersionUID = 1L;
+
+	private final TransactionControl control;
+	
+	
+	public HibernateTxControlPlatform(TransactionControl control) {
+		this.control = control;
+	}
+
+	@Override
+	public TransactionCoordinator buildTransactionCoordinator(TransactionCoordinatorOwner owner, TransactionCoordinatorOptions options) {
+		return new HibernateTxControlCoordinator(owner, options.shouldAutoJoinTransaction());
+	}
+
+	@Override
+	public boolean isJta() {
+		return true;
+	}
+
+	@Override
+	public ConnectionReleaseMode getDefaultConnectionReleaseMode() {
+		return AFTER_STATEMENT;
+	}
+
+	@Override
+	public ConnectionAcquisitionMode getDefaultConnectionAcquisitionMode() {
+		return AS_NEEDED;
+	}
+
+	public class HibernateTxControlCoordinator implements TransactionCoordinator, 
+		SynchronizationRegistry, TransactionDriver, IsolationDelegate {
+		
+		private static final long serialVersionUID = 1L;
+
+		private final List<TransactionObserver> registeredObservers = new ArrayList<>();
+
+		private final TransactionCoordinatorOwner owner;
+
+		private final boolean autoJoin;
+		
+		private boolean joined = false;
+		
+		public HibernateTxControlCoordinator(TransactionCoordinatorOwner owner, boolean autoJoin) {
+			this.owner = owner;
+			this.autoJoin = autoJoin;
+		}
+
+		@Override
+		public void explicitJoin() {
+			if(!joined) {
+				if(!control.activeTransaction()) {
+					throw new TransactionRequiredException("There is no transaction active to join");
+				}
+				
+				internalJoin();
+			}
+		}
+
+		private void internalJoin() {
+			TransactionContext currentContext = control.getCurrentContext();
+			currentContext.preCompletion(this::beforeCompletion);
+			currentContext.postCompletion(this::afterCompletion);
+			joined = true;
+		}
+
+		@Override
+		public boolean isJoined() {
+			return joined;
+		}
+
+		@Override
+		public void pulse() {
+			if (autoJoin && !joined && control.activeTransaction()) {
+				internalJoin();
+			}
+		}
+
+		@Override
+		public TransactionDriver getTransactionDriverControl() {
+			return this;
+		}
+
+		@Override
+		public SynchronizationRegistry getLocalSynchronizations() {
+			return this;
+		}
+
+		@Override
+		public boolean isActive() {
+			return control.activeTransaction();
+		}
+
+		@Override
+		public IsolationDelegate createIsolationDelegate() {
+			return this;
+		}
+
+		@Override
+		public void addObserver(TransactionObserver observer) {
+			registeredObservers.add(observer);
+		}
+
+		@Override
+		public void removeObserver(TransactionObserver observer) {
+			registeredObservers.remove(observer);
+		}
+
+		@Override
+		public TransactionCoordinatorBuilder getTransactionCoordinatorBuilder() {
+			return HibernateTxControlPlatform.this;
+		}
+
+		@Override
+		public void setTimeOut(int seconds) {
+			// TODO How do we support this?
+		}
+
+		@Override
+		public int getTimeOut() {
+			return -1;
+		}
+	
+		@Override
+		public void registerSynchronization(Synchronization synchronization) {
+			TransactionContext currentContext = control.getCurrentContext();
+			currentContext.preCompletion(synchronization::beforeCompletion);
+			currentContext.postCompletion(status -> synchronization.afterCompletion(toIntStatus(status)));
+		}
+
+		private void beforeCompletion() {
+			try {
+				owner.beforeTransactionCompletion();
+			}
+			catch (RuntimeException re) {
+				control.setRollbackOnly();
+				throw re;
+			}
+			finally {
+				registeredObservers.forEach(TransactionObserver::beforeCompletion);
+			}
+		}
+		
+		private void afterCompletion(TransactionStatus status) {
+			if ( owner.isActive() ) {
+				toIntStatus(status);
+				
+				boolean committed = status == COMMITTED;
+				owner.afterTransactionCompletion(committed, false);
+				
+				registeredObservers.forEach(o -> o.afterCompletion(committed, false));
+			}
+		}
+
+		private int toIntStatus(TransactionStatus status) {
+			switch(status) {
+				case COMMITTED:
+					return STATUS_COMMITTED;
+				case ROLLED_BACK:
+					return STATUS_ROLLEDBACK;
+				default:
+					return STATUS_UNKNOWN;
+			}
+		}
+
+		@Override
+		public void begin() {
+			if(!control.activeTransaction()) {
+				throw new IllegalStateException("There is no existing active transaction scope");
+			}
+		}
+
+		@Override
+		public void commit() {
+			if(!control.activeTransaction()) {
+				throw new IllegalStateException("There is no existing active transaction scope");
+			}
+		}
+
+		@Override
+		public void rollback() {
+			if(!control.activeTransaction()) {
+				throw new IllegalStateException("There is no existing active transaction scope");
+			}
+			control.setRollbackOnly();
+		}
+
+		@Override
+		public org.hibernate.resource.transaction.spi.TransactionStatus getStatus() {
+			TransactionStatus status = control.getCurrentContext().getTransactionStatus();
+			switch(status) {
+				case ACTIVE:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.ACTIVE;
+				case COMMITTED:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.COMMITTED;
+				case PREPARING:
+				case PREPARED:
+				case COMMITTING:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.COMMITTING;
+				case MARKED_ROLLBACK:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.MARKED_ROLLBACK;
+				case NO_TRANSACTION:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.NOT_ACTIVE;
+				case ROLLED_BACK:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.ROLLED_BACK;
+				case ROLLING_BACK:
+					return org.hibernate.resource.transaction.spi.TransactionStatus.ROLLING_BACK;
+				default:
+					throw new IllegalStateException("The state " + status + " is unknown");
+			}
+		}
+
+		@Override
+		public void markRollbackOnly() {
+			control.setRollbackOnly();
+		}
+
+		@Override
+		public <T> T delegateWork(WorkExecutorVisitable<T> work, boolean transacted) throws HibernateException {
+			Callable<T> c = () -> {
+			
+				JdbcSessionOwner sessionOwner = owner.getJdbcSessionOwner();
+				Connection conn = sessionOwner.getJdbcConnectionAccess().obtainConnection();
+				
+				try {
+					return work.accept(new WorkExecutor<>(), conn);
+				} finally {
+					sessionOwner.getJdbcConnectionAccess().releaseConnection(conn);
+				}
+			};
+			
+			if(transacted) {
+				return control.requiresNew(c);
+			} else {
+				return control.notSupported(c);
+			}
+				
+		}
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/Activator.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/Activator.java
new file mode 100644
index 0000000..df32dda
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/Activator.java
@@ -0,0 +1,56 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static org.osgi.framework.Constants.SERVICE_PID;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import org.apache.geronimo.specs.jpa.PersistenceActivator;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.cm.ManagedServiceFactory;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProviderFactory;
+
+public class Activator implements BundleActivator {
+
+	private final BundleActivator geronimoActivator;
+	
+	private ServiceRegistration<JPAEntityManagerProviderFactory> reg;
+	private ServiceRegistration<ManagedServiceFactory> factoryReg;
+	
+	public Activator() {
+		geronimoActivator = new PersistenceActivator();
+	}
+	
+	@Override
+	public void start(BundleContext context) throws Exception {
+		geronimoActivator.start(context);
+		
+		reg = context.registerService(JPAEntityManagerProviderFactory.class, 
+				new JPAEntityManagerProviderFactoryImpl(), getProperties());
+		
+		factoryReg = context.registerService(ManagedServiceFactory.class, 
+				new ManagedServiceFactoryImpl(context), getMSFProperties());
+	}
+
+	@Override
+	public void stop(BundleContext context) throws Exception {
+		reg.unregister();
+		factoryReg.unregister();
+		geronimoActivator.stop(context);
+	}
+
+	private Dictionary<String, Object> getProperties() {
+		Dictionary<String, Object> props = new Hashtable<>();
+		props.put("osgi.xa.enabled", Boolean.TRUE);
+		return props;
+	}
+
+	private Dictionary<String, ?> getMSFProperties() {
+		Dictionary<String, Object> props = new Hashtable<>();
+		props.put(SERVICE_PID, "org.apache.aries.tx.control.jpa.xa");
+		return props;
+	}
+
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/DelayedJPAEntityManagerProvider.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/DelayedJPAEntityManagerProvider.java
new file mode 100644
index 0000000..c787df2
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/DelayedJPAEntityManagerProvider.java
@@ -0,0 +1,40 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import java.util.function.Function;
+
+import javax.persistence.EntityManager;
+
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProvider;
+
+public class DelayedJPAEntityManagerProvider implements JPAEntityManagerProvider {
+	
+	private final Function<TransactionControl, JPAEntityManagerProvider> wireToTransactionControl;
+	
+	private JPAEntityManagerProvider delegate;
+	
+	private TransactionControl wiredTxControl;
+
+	public DelayedJPAEntityManagerProvider(Function<TransactionControl, JPAEntityManagerProvider> wireToTransactionControl) {
+		this.wireToTransactionControl = wireToTransactionControl;
+	}
+
+	@Override
+	public EntityManager getResource(TransactionControl txControl) throws TransactionException {
+		synchronized (wireToTransactionControl) {
+			
+			if(wiredTxControl != null && !wiredTxControl.equals(txControl)) {
+				throw new TransactionException("This JPAEntityManagerProvider has already been wired to a different Transaction Control service.");
+			}
+			if(delegate == null) {
+				delegate = wireToTransactionControl.apply(txControl);
+				wiredTxControl = txControl;
+			}
+		}
+		return delegate.getResource(txControl);
+	}
+	
+	
+
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderFactoryImpl.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderFactoryImpl.java
new file mode 100644
index 0000000..95db41f
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderFactoryImpl.java
@@ -0,0 +1,160 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static java.util.Optional.ofNullable;
+import static javax.persistence.spi.PersistenceUnitTransactionType.JTA;
+
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import javax.sql.DataSource;
+
+import org.osgi.service.jpa.EntityManagerFactoryBuilder;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProvider;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProviderFactory;
+
+public class JPAEntityManagerProviderFactoryImpl implements JPAEntityManagerProviderFactory {
+
+	@Override
+	public JPAEntityManagerProvider getProviderFor(EntityManagerFactoryBuilder emfb, Map<String, Object> jpaProperties,
+			Map<String, Object> resourceProviderProperties) {
+		if(checkEnlistment(resourceProviderProperties)) {
+			return new DelayedJPAEntityManagerProvider(tx -> {
+				
+				Map<String, Object> toUse = enlistDataSource(tx, jpaProperties);
+				
+				return internalBuilderCreate(emfb, toUse);
+			});
+		}
+		
+		return internalBuilderCreate(emfb, jpaProperties);
+	}
+
+	private Map<String, Object> enlistDataSource(TransactionControl tx, Map<String, Object> jpaProperties) {
+		Map<String, Object> toReturn = new HashMap<>(jpaProperties);
+		
+		DataSource ds = (DataSource) jpaProperties.get("javax.persistence.jtaDataSource");
+
+		if(!jpaProperties.containsKey("javax.persistence.nonJtaDataSource")) {
+			toReturn.put("javax.persistence.jtaDataSource", ds);
+		}
+		
+		toReturn.put("javax.persistence.jtaDataSource", new EnlistingDataSource(ds));
+		
+		return toReturn;
+	}
+
+	private JPAEntityManagerProvider internalBuilderCreate(EntityManagerFactoryBuilder emfb,
+			Map<String, Object> jpaProperties) {
+		EntityManagerFactory emf = emfb.createEntityManagerFactory(jpaProperties);
+		
+		validateEMF(emf);
+		
+		return new JPAEntityManagerProviderImpl(emf);
+	}
+
+	private void validateEMF(EntityManagerFactory emf) {
+		Object o = emf.getProperties().get("javax.persistence.transactionType");
+		
+		PersistenceUnitTransactionType tranType;
+		if(o instanceof PersistenceUnitTransactionType) {
+			tranType = (PersistenceUnitTransactionType) o;
+		} else if (o instanceof String) {
+			tranType = PersistenceUnitTransactionType.valueOf(o.toString());
+		} else {
+			//TODO log this?
+			tranType = JTA;
+		}
+		
+		if(JTA != tranType) {
+			throw new IllegalArgumentException("The supplied EntityManagerFactory is not declared RESOURCE_LOCAL");
+		}
+	}
+
+	@Override
+	public JPAEntityManagerProvider getProviderFor(EntityManagerFactory emf,
+			Map<String, Object> resourceProviderProperties) {
+		checkEnlistment(resourceProviderProperties);
+		validateEMF(emf);
+		
+		return new JPAEntityManagerProviderImpl(emf);
+	}
+
+	private boolean checkEnlistment(Map<String, Object> resourceProviderProperties) {
+		if (toBoolean(resourceProviderProperties, LOCAL_ENLISTMENT_ENABLED, false)) {
+			throw new TransactionException("This Resource Provider does not support Local transactions");
+		} else if (!toBoolean(resourceProviderProperties, XA_ENLISTMENT_ENABLED, true)) {
+			throw new TransactionException(
+					"This Resource Provider always enlists in XA transactions as it does not support local transactions");
+		}
+		
+		return !toBoolean(resourceProviderProperties, PRE_ENLISTED_DB_CONNECTION, false);
+	}
+	
+	public static boolean toBoolean(Map<String, Object> props, String key, boolean defaultValue) {
+		Object o =  ofNullable(props)
+			.map(m -> m.get(key))
+			.orElse(defaultValue);
+		
+		if (o instanceof Boolean) {
+			return ((Boolean) o).booleanValue();
+		} else if(o instanceof String) {
+			return Boolean.parseBoolean((String) o);
+		} else {
+			throw new IllegalArgumentException("The property " + key + " cannot be converted to a boolean");
+		}
+	}
+	
+	public class EnlistingDataSource implements DataSource {
+		
+		private final DataSource delegate;
+
+		public EnlistingDataSource(DataSource delegate) {
+			this.delegate = delegate;
+		}
+
+		public PrintWriter getLogWriter() throws SQLException {
+			return delegate.getLogWriter();
+		}
+
+		public <T> T unwrap(Class<T> iface) throws SQLException {
+			return delegate.unwrap(iface);
+		}
+
+		public void setLogWriter(PrintWriter out) throws SQLException {
+			delegate.setLogWriter(out);
+		}
+
+		public boolean isWrapperFor(Class<?> iface) throws SQLException {
+			return delegate.isWrapperFor(iface);
+		}
+
+		public Connection getConnection() throws SQLException {
+			return delegate.getConnection();
+		}
+
+		public void setLoginTimeout(int seconds) throws SQLException {
+			delegate.setLoginTimeout(seconds);
+		}
+
+		public Connection getConnection(String username, String password) throws SQLException {
+			return delegate.getConnection(username, password);
+		}
+
+		public int getLoginTimeout() throws SQLException {
+			return delegate.getLoginTimeout();
+		}
+
+		public Logger getParentLogger() throws SQLFeatureNotSupportedException {
+			return delegate.getParentLogger();
+		}
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderImpl.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderImpl.java
new file mode 100644
index 0000000..415423c
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/JPAEntityManagerProviderImpl.java
@@ -0,0 +1,26 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import java.util.UUID;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProvider;
+
+public class JPAEntityManagerProviderImpl implements JPAEntityManagerProvider {
+
+	private final UUID					uuid	= UUID.randomUUID();
+
+	private final EntityManagerFactory 	emf;
+
+	public JPAEntityManagerProviderImpl(EntityManagerFactory emf) {
+		this.emf = emf;
+	}
+
+	@Override
+	public EntityManager getResource(TransactionControl txControl) throws TransactionException {
+		return new XATxContextBindingEntityManager(txControl, emf, uuid);
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/LifecycleAware.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/LifecycleAware.java
new file mode 100644
index 0000000..4fe4757
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/LifecycleAware.java
@@ -0,0 +1,8 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+public interface LifecycleAware {
+
+	public void start();
+	
+	public void stop();
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPADataSourceSetup.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPADataSourceSetup.java
new file mode 100644
index 0000000..023f5d3
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPADataSourceSetup.java
@@ -0,0 +1,222 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static java.util.Optional.ofNullable;
+import static java.util.concurrent.TimeUnit.HOURS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.osgi.framework.Constants.OBJECTCLASS;
+import static org.osgi.service.jdbc.DataSourceFactory.OSGI_JDBC_DRIVER_CLASS;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.CONNECTION_LIFETIME;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.CONNECTION_POOLING_ENABLED;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.CONNECTION_TIMEOUT;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.IDLE_TIMEOUT;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.MAX_CONNECTIONS;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.MIN_CONNECTIONS;
+import static org.osgi.service.transaction.control.jdbc.JDBCConnectionProviderFactory.USE_DRIVER;
+
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.sql.DataSource;
+
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XADataSourceMapper;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.jdbc.DataSourceFactory;
+import org.osgi.service.transaction.control.TransactionException;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+
+public class ManagedJPADataSourceSetup implements LifecycleAware,
+		ServiceTrackerCustomizer<DataSourceFactory, ManagedJPAEMFLocator> {
+
+	private final BundleContext context;
+	private final String pid;
+	private final Properties jdbcProperties;
+	private final Map<String, Object> baseJPAProperties;
+	private final Map<String, Object> providerProperties;
+	
+	private final ServiceTracker<DataSourceFactory, ManagedJPAEMFLocator> dsfTracker;
+	private final AtomicReference<ServiceReference<DataSourceFactory>> activeDsf = new AtomicReference<>();
+
+	public ManagedJPADataSourceSetup(BundleContext context, String pid, Properties jdbcProperties,
+			Map<String, Object> baseJPAProperties, Map<String, Object> providerProperties) throws InvalidSyntaxException, ConfigurationException {
+		this.context = context;
+		this.pid = pid;
+		this.jdbcProperties = jdbcProperties;
+		this.baseJPAProperties = baseJPAProperties;
+		this.providerProperties = providerProperties;
+
+		String targetFilter = (String) providerProperties.get(ManagedServiceFactoryImpl.DSF_TARGET_FILTER);
+		if (targetFilter == null) {
+			String driver = (String) providerProperties.get(OSGI_JDBC_DRIVER_CLASS);
+			if (driver == null) {
+				ManagedServiceFactoryImpl.LOG.error("The configuration {} must specify a target filter or a JDBC driver class", pid);
+				throw new ConfigurationException(OSGI_JDBC_DRIVER_CLASS,
+						"The configuration must specify either a target filter or a JDBC driver class");
+			}
+			targetFilter = "(" + OSGI_JDBC_DRIVER_CLASS + "=" + driver + ")";
+		}
+
+		targetFilter = "(&(" + OBJECTCLASS + "=" + DataSourceFactory.class.getName() + ")" + targetFilter + ")";
+
+		this.dsfTracker = new ServiceTracker<>(context, context.createFilter(targetFilter), this);
+	}
+
+	public void start() {
+		dsfTracker.open();
+	}
+
+	public void stop() {
+		dsfTracker.close();
+	}
+
+	@Override
+	public ManagedJPAEMFLocator addingService(ServiceReference<DataSourceFactory> reference) {
+		DataSourceFactory service = context.getService(reference);
+		ManagedJPAEMFLocator toReturn;
+		try {
+			toReturn = new ManagedJPAEMFLocator(context, pid, 
+					getJPAProperties(service), providerProperties);
+		} catch (Exception e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			return null;
+		}
+		updateService(reference, toReturn);
+		
+		return toReturn;
+	}
+
+	private void updateService(ServiceReference<DataSourceFactory> reference, ManagedJPAEMFLocator locator) {
+		boolean setDsf;
+		synchronized (this) {
+			setDsf = activeDsf.compareAndSet(null, reference);
+		}
+		try {
+			if (setDsf) {
+				locator.start();
+			}
+		} catch (Exception e) {
+			ManagedServiceFactoryImpl.LOG.error("An error occurred when creating the connection provider for {}.", pid, e);
+			activeDsf.compareAndSet(reference, null);
+			throw new IllegalStateException("An error occurred when creating the connection provider", e);
+		}
+	}
+
+	private Map<String, Object> getJPAProperties(DataSourceFactory dsf) {
+		Map<String, Object> props = new HashMap<>(baseJPAProperties);
+		
+		DataSource unpooled;
+		try {
+			if (toBoolean(providerProperties, USE_DRIVER, false)) {
+				throw new TransactionException("The Database must use an XA connection");
+			} else {
+				unpooled = new XADataSourceMapper(dsf.createXADataSource(jdbcProperties));
+			}
+		} catch (SQLException sqle) {
+			throw new TransactionException("Unable to create the JDBC resource provider", sqle);
+		}
+
+		DataSource toUse = poolIfNecessary(providerProperties, unpooled);
+		
+		props.put("javax.persistence.jtaDataSource", toUse);
+		
+		return props;
+	}
+	
+	@Override
+	public void modifiedService(ServiceReference<DataSourceFactory> reference, ManagedJPAEMFLocator service) {
+	}
+
+	@Override
+	public void removedService(ServiceReference<DataSourceFactory> reference, ManagedJPAEMFLocator service) {
+		service.stop();
+
+		if (activeDsf.compareAndSet(reference, null)) {
+			Map<ServiceReference<DataSourceFactory>,ManagedJPAEMFLocator> tracked = dsfTracker.getTracked();
+			if (!tracked.isEmpty()) {
+				Entry<ServiceReference<DataSourceFactory>, ManagedJPAEMFLocator> e = tracked.entrySet().iterator().next();
+				updateService(e.getKey(), e.getValue());
+			}
+		}
+	}
+	
+	private DataSource poolIfNecessary(Map<String, Object> resourceProviderProperties, DataSource unpooled) {
+		DataSource toUse;
+
+		if (toBoolean(resourceProviderProperties, CONNECTION_POOLING_ENABLED, true)) {
+			HikariConfig hcfg = new HikariConfig();
+			hcfg.setDataSource(unpooled);
+
+			// Sizes
+			hcfg.setMaximumPoolSize(toInt(resourceProviderProperties, MAX_CONNECTIONS, 10));
+			hcfg.setMinimumIdle(toInt(resourceProviderProperties, MIN_CONNECTIONS, 10));
+
+			// Timeouts
+			hcfg.setConnectionTimeout(toLong(resourceProviderProperties, CONNECTION_TIMEOUT, SECONDS.toMillis(30)));
+			hcfg.setIdleTimeout(toLong(resourceProviderProperties, IDLE_TIMEOUT, TimeUnit.MINUTES.toMillis(3)));
+			hcfg.setMaxLifetime(toLong(resourceProviderProperties, CONNECTION_LIFETIME, HOURS.toMillis(3)));
+
+			toUse = new HikariDataSource(hcfg);
+
+		} else {
+			toUse = unpooled;
+		}
+		return toUse;
+	}
+
+	private boolean toBoolean(Map<String, Object> props, String key, boolean defaultValue) {
+		Object o =  ofNullable(props)
+			.map(m -> m.get(key))
+			.orElse(defaultValue);
+		
+		if (o instanceof Boolean) {
+			return ((Boolean) o).booleanValue();
+		} else if(o instanceof String) {
+			return Boolean.parseBoolean((String) o);
+		} else {
+			throw new IllegalArgumentException("The property " + key + " cannot be converted to a boolean");
+		}
+	}
+
+	private int toInt(Map<String, Object> props, String key, int defaultValue) {
+		
+		Object o =  ofNullable(props)
+				.map(m -> m.get(key))
+				.orElse(defaultValue);
+		
+		if (o instanceof Number) {
+			return ((Number) o).intValue();
+		} else if(o instanceof String) {
+			return Integer.parseInt((String) o);
+		} else {
+			throw new IllegalArgumentException("The property " + key + " cannot be converted to an int");
+		}
+	}
+
+	private long toLong(Map<String, Object> props, String key, long defaultValue) {
+		
+		Object o =  ofNullable(props)
+				.map(m -> m.get(key))
+				.orElse(defaultValue);
+		
+		if (o instanceof Number) {
+			return ((Number) o).longValue();
+		} else if(o instanceof String) {
+			return Long.parseLong((String) o);
+		} else {
+			throw new IllegalArgumentException("The property " + key + " cannot be converted to a long");
+		}
+	}
+
+}
\ No newline at end of file
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPAEMFLocator.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPAEMFLocator.java
new file mode 100644
index 0000000..6433e88
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedJPAEMFLocator.java
@@ -0,0 +1,250 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static org.apache.aries.tx.control.jpa.xa.impl.ManagedServiceFactoryImpl.EMF_BUILDER_TARGET_FILTER;
+import static org.osgi.framework.Constants.OBJECTCLASS;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_PASSWORD;
+import static org.osgi.service.jpa.EntityManagerFactoryBuilder.JPA_UNIT_NAME;
+import static org.osgi.service.jpa.EntityManagerFactoryBuilder.JPA_UNIT_PROVIDER;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.persistence.spi.PersistenceProvider;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.framework.wiring.BundleWire;
+import org.osgi.framework.wiring.BundleWiring;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.jpa.EntityManagerFactoryBuilder;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.jpa.JPAEntityManagerProvider;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+
+public class ManagedJPAEMFLocator implements LifecycleAware,
+	ServiceTrackerCustomizer<EntityManagerFactoryBuilder, EntityManagerFactoryBuilder> {
+
+	private final BundleContext context;
+	private final String pid;
+	private final Map<String, Object> jpaProperties;
+	private final Map<String, Object> providerProperties;
+	private final ServiceTracker<EntityManagerFactoryBuilder, EntityManagerFactoryBuilder> emfBuilderTracker;
+
+	private final AtomicReference<EntityManagerFactoryBuilder> activeDsf = new AtomicReference<>();
+	private final AtomicReference<ServiceRegistration<JPAEntityManagerProvider>> serviceReg = new AtomicReference<>();
+
+	public ManagedJPAEMFLocator(BundleContext context, String pid, Map<String, Object> jpaProperties,
+			Map<String, Object> providerProperties) throws InvalidSyntaxException, ConfigurationException {
+		this.context = context;
+		this.pid = pid;
+		this.jpaProperties = jpaProperties;
+		this.providerProperties = providerProperties;
+
+		String unitName = (String) providerProperties.get(JPA_UNIT_NAME);
+		if (unitName == null) {
+			ManagedServiceFactoryImpl.LOG.error("The configuration {} must specify a persistence unit name", pid);
+			throw new ConfigurationException(JPA_UNIT_NAME,
+					"The configuration must specify a persistence unit name");
+		}
+		
+		String targetFilter = (String) providerProperties.get(EMF_BUILDER_TARGET_FILTER);
+		if (targetFilter == null) {
+			targetFilter = "(" + JPA_UNIT_NAME + "=" + unitName + ")";
+		}
+
+		targetFilter = "(&(" + OBJECTCLASS + "=" + EntityManagerFactoryBuilder.class.getName() + ")" + targetFilter + ")";
+
+		this.emfBuilderTracker = new ServiceTracker<>(context, context.createFilter(targetFilter), this);
+	}
+
+	public void start() {
+		emfBuilderTracker.open();
+	}
+
+	public void stop() {
+		emfBuilderTracker.close();
+	}
+
+	@Override
+	public EntityManagerFactoryBuilder addingService(ServiceReference<EntityManagerFactoryBuilder> reference) {
+		EntityManagerFactoryBuilder service = context.getService(reference);
+
+		updateService(reference, service);
+		return service;
+	}
+
+	private void updateService(ServiceReference<EntityManagerFactoryBuilder> reference, EntityManagerFactoryBuilder service) {
+		boolean setEMFB;
+		synchronized (this) {
+			setEMFB = activeDsf.compareAndSet(null, service);
+		}
+
+		if (setEMFB) {
+			try {
+				JPAEntityManagerProvider jpaEM = new DelayedJPAEntityManagerProvider(t -> {
+					
+					Map<String, Object> props = new HashMap<String, Object>(jpaProperties);
+					
+					setupTransactionManager(props, t, reference);
+					
+					return new JPAEntityManagerProviderFactoryImpl().getProviderFor(service,
+							props, providerProperties);
+				});
+				ServiceRegistration<JPAEntityManagerProvider> reg = context
+						.registerService(JPAEntityManagerProvider.class, jpaEM, getServiceProperties());
+				if (!serviceReg.compareAndSet(null, reg)) {
+					throw new IllegalStateException("Unable to set the JDBC connection provider registration");
+				}
+			} catch (Exception e) {
+				ManagedServiceFactoryImpl.LOG.error("An error occurred when creating the connection provider for {}.", pid, e);
+				activeDsf.compareAndSet(service, null);
+			}
+		}
+	}
+
+	private void setupTransactionManager(Map<String, Object> props, TransactionControl txControl,
+			ServiceReference<EntityManagerFactoryBuilder> reference) {
+		String provider = (String) reference.getProperty(JPA_UNIT_PROVIDER);
+		
+		ServiceReference<PersistenceProvider> providerRef = getPersistenceProvider(provider);
+		
+		if(providerRef == null) {
+			// TODO log a warning and give up
+			return;
+		}
+
+		Bundle providerBundle = providerRef.getBundle();
+		Bundle txControlProviderBundle = context.getBundle();
+		
+		try {
+			if("org.hibernate.jpa.HibernatePersistenceProvider".equals(provider)) {
+				
+				try{
+					providerBundle.loadClass("org.hibernate.resource.transaction.TransactionCoordinatorBuilder");
+				} catch (Exception e) {
+					BundleWiring wiring = providerBundle.adapt(BundleWiring.class);
+					providerBundle = wiring.getRequiredWires("osgi.wiring.package").stream()
+								.filter(bw -> "org.hibernate".equals(bw.getCapability().getAttributes().get("osgi.wiring.package")))
+								.map(BundleWire::getProviderWiring)
+								.map(BundleWiring::getBundle)
+								.findFirst().get();
+				}
+				
+				ClassLoader pluginLoader = getPluginLoader(providerBundle, txControlProviderBundle);
+				
+				Class<?> pluginClazz = pluginLoader.loadClass("org.apache.aries.tx.control.jpa.xa.hibernate.impl.HibernateTxControlPlatform");
+				Object plugin = pluginClazz.getConstructor(TransactionControl.class)
+					.newInstance(txControl);
+				
+				props.put("hibernate.transaction.coordinator_class", plugin);
+				
+			} else {
+				// TODO log a warning and give up
+				return;
+			} 
+		} catch (Exception e) {
+			//TODO log a warning and give up
+			e.printStackTrace();
+		}
+	}
+
+	private ClassLoader getPluginLoader(Bundle providerBundle, Bundle txControlProviderBundle) {
+		return new ClassLoader() {
+
+			@Override
+			public Class<?> loadClass(String name) throws ClassNotFoundException {
+				if(name.startsWith("org.apache.aries.tx.control.jpa.xa.hibernate")) {
+					String resource = name.replace('.', '/') + ".class";
+					
+					try (InputStream is = txControlProviderBundle.getResource(resource).openStream()) {
+						ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
+						byte[] b = new byte[4096];
+						int read;
+						while ((read = is.read(b)) != -1) {
+							baos.write(b, 0, read);
+						}
+						byte[] clazzBytes = baos.toByteArray();
+						return defineClass(name, clazzBytes, 0, clazzBytes.length, 
+								ManagedJPAEMFLocator.class.getProtectionDomain());
+					} catch (IOException e) {
+						throw new ClassNotFoundException("Unable to load class " + name, e);
+					}
+				}
+				
+				if(name.startsWith("org.apache.aries.tx.control") ||
+						name.startsWith("org.osgi.service.transaction.control")) {
+					return txControlProviderBundle.loadClass(name);
+				}
+				return providerBundle.loadClass(name);
+			}
+		};
+	}
+
+	private ServiceReference<PersistenceProvider> getPersistenceProvider(String provider) {
+		if(provider == null) {
+			return null;
+		}
+		try {
+			return context.getServiceReferences(PersistenceProvider.class, 
+							"(javax.persistence.provider=" + provider + ")").stream()
+								.findFirst()
+								.orElse(null);
+		} catch (InvalidSyntaxException e) {
+			//TODO log a warning
+			return null;
+		} 
+	}
+
+	private Dictionary<String, ?> getServiceProperties() {
+		Hashtable<String, Object> props = new Hashtable<>();
+		providerProperties.keySet().stream().filter(s -> !JDBC_PASSWORD.equals(s))
+				.forEach(s -> props.put(s, providerProperties.get(s)));
+		return props;
+	}
+
+	@Override
+	public void modifiedService(ServiceReference<EntityManagerFactoryBuilder> reference, EntityManagerFactoryBuilder service) {
+	}
+
+	@Override
+	public void removedService(ServiceReference<EntityManagerFactoryBuilder> reference, EntityManagerFactoryBuilder service) {
+		boolean dsfLeft;
+		ServiceRegistration<JPAEntityManagerProvider> oldReg = null;
+		synchronized (this) {
+			dsfLeft = activeDsf.compareAndSet(service, null);
+			if (dsfLeft) {
+				oldReg = serviceReg.getAndSet(null);
+			}
+		}
+
+		if (oldReg != null) {
+			try {
+				oldReg.unregister();
+			} catch (IllegalStateException ise) {
+				ManagedServiceFactoryImpl.LOG.debug("An exception occurred when unregistering a service for {}", pid);
+			}
+		}
+		try {
+			context.ungetService(reference);
+		} catch (IllegalStateException ise) {
+			ManagedServiceFactoryImpl.LOG.debug("An exception occurred when ungetting the service for {}", reference);
+		}
+
+		if (dsfLeft) {
+			EntityManagerFactoryBuilder newEMFBuilder = emfBuilderTracker.getService();
+			if (newEMFBuilder != null) {
+				updateService(reference, newEMFBuilder);
+			}
+		}
+	}
+}
\ No newline at end of file
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedServiceFactoryImpl.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedServiceFactoryImpl.java
new file mode 100644
index 0000000..7191e48
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/ManagedServiceFactoryImpl.java
@@ -0,0 +1,227 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static java.lang.Integer.MAX_VALUE;
+import static java.util.Arrays.asList;
+import static java.util.Optional.ofNullable;
+import static java.util.function.Function.identity;
+import static java.util.stream.Collectors.toMap;
+import static javax.persistence.spi.PersistenceUnitTransactionType.JTA;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_DATABASE_NAME;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_DATASOURCE_NAME;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_DESCRIPTION;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_NETWORK_PROTOCOL;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_PASSWORD;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_PORT_NUMBER;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_ROLE_NAME;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_SERVER_NAME;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_URL;
+import static org.osgi.service.jdbc.DataSourceFactory.JDBC_USER;
+import static org.osgi.service.jdbc.DataSourceFactory.OSGI_JDBC_DRIVER_CLASS;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.cm.ManagedServiceFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ManagedServiceFactoryImpl implements ManagedServiceFactory {
+
+	static final Logger LOG = LoggerFactory.getLogger(ManagedServiceFactoryImpl.class);
+	
+	static final String DSF_TARGET_FILTER = "aries.dsf.target.filter";
+	static final String EMF_BUILDER_TARGET_FILTER = "aries.emf.builder.target.filter";
+	static final String JDBC_PROP_NAMES = "aries.jdbc.property.names";
+	static final List<String> JDBC_PROPERTIES = asList(JDBC_DATABASE_NAME, JDBC_DATASOURCE_NAME,
+			JDBC_DESCRIPTION, JDBC_NETWORK_PROTOCOL, JDBC_PASSWORD, JDBC_PORT_NUMBER, JDBC_ROLE_NAME, JDBC_SERVER_NAME,
+			JDBC_URL, JDBC_USER);
+	static final String JPA_PROP_NAMES = "aries.jpa.property.names";
+
+	private final Map<String, LifecycleAware> managedInstances = new ConcurrentHashMap<>();
+
+	private final BundleContext context;
+
+	public ManagedServiceFactoryImpl(BundleContext context) {
+		this.context = context;
+	}
+
+	@Override
+	public String getName() {
+		return "Aries JPAEntityManagerProvider (Local only) service";
+	}
+
+	@Override
+	public void updated(String pid, Dictionary<String, ?> properties) throws ConfigurationException {
+
+		Map<String, Object> propsMap = new HashMap<>();
+
+		Enumeration<String> keys = properties.keys();
+		while (keys.hasMoreElements()) {
+			String key = keys.nextElement();
+			propsMap.put(key, properties.get(key));
+		}
+
+		Properties jdbcProps = getJdbcProps(pid, propsMap);
+		Map<String, Object> jpaProps = getJPAProps(pid, propsMap);
+
+		try {
+			LifecycleAware worker;
+			if(propsMap.containsKey(OSGI_JDBC_DRIVER_CLASS) ||
+					propsMap.containsKey(DSF_TARGET_FILTER)) {
+				worker = new ManagedJPADataSourceSetup(context, pid, jdbcProps, jpaProps, propsMap);
+			} else {
+				if(!jdbcProps.isEmpty()) {
+					LOG.warn("The configuration {} contains raw JDBC configuration, but no osgi.jdbc.driver.class or aries.dsf.target.filter properties. No DataSourceFactory will be used byt this bundle, so the JPA provider must be able to directly create the datasource, and these configuration properties will likely be ignored. {}",
+								pid, jdbcProps.stringPropertyNames());
+				}
+				worker = new ManagedJPAEMFLocator(context, pid, jpaProps, propsMap);
+			}
+			ofNullable(managedInstances.put(pid, worker)).ifPresent(LifecycleAware::stop);
+			worker.start();
+		} catch (InvalidSyntaxException e) {
+			LOG.error("The configuration {} contained an invalid target filter {}", pid, e.getFilter());
+			throw new ConfigurationException(DSF_TARGET_FILTER, "The target filter was invalid", e);
+		}
+	}
+
+	public void stop() {
+		managedInstances.values().forEach(LifecycleAware::stop);
+	}
+
+	@SuppressWarnings("unchecked")
+	private Properties getJdbcProps(String pid, Map<String, Object> properties) throws ConfigurationException {
+
+		Object object = properties.getOrDefault(JDBC_PROP_NAMES, JDBC_PROPERTIES);
+		Collection<String> propnames;
+		if (object instanceof String) {
+			propnames = Arrays.asList(((String) object).split(","));
+		} else if (object instanceof String[]) {
+			propnames = Arrays.asList((String[]) object);
+		} else if (object instanceof Collection) {
+			propnames = (Collection<String>) object;
+		} else {
+			LOG.error("The configuration {} contained an invalid list of JDBC property names", pid, object);
+			throw new ConfigurationException(JDBC_PROP_NAMES,
+					"The jdbc property names must be a String+ or comma-separated String");
+		}
+
+		Properties p = new Properties();
+
+		propnames.stream().filter(properties::containsKey)
+				.forEach(s -> p.setProperty(s, String.valueOf(properties.get(s))));
+
+		return p;
+	}
+
+	@SuppressWarnings("unchecked")
+	private Map<String, Object> getJPAProps(String pid, Map<String, Object> properties) throws ConfigurationException {
+		
+		Object object = properties.getOrDefault(JPA_PROP_NAMES, new AllCollection());
+		Collection<String> propnames;
+		if (object instanceof String) {
+			propnames = Arrays.asList(((String) object).split(","));
+		} else if (object instanceof String[]) {
+			propnames = Arrays.asList((String[]) object);
+		} else if (object instanceof Collection) {
+			propnames = (Collection<String>) object;
+		} else {
+			LOG.error("The configuration {} contained an invalid list of JPA property names", pid, object);
+			throw new ConfigurationException(JDBC_PROP_NAMES,
+					"The jpa property names must be empty, a String+, or a comma-separated String list");
+		}
+		
+		Map<String, Object> result = properties.keySet().stream()
+			.filter(propnames::contains)
+			.collect(toMap(identity(), properties::get));
+		
+		result.putIfAbsent("javax.persistence.transactionType", JTA.name());
+		
+		return result;
+	}
+
+	@Override
+	public void deleted(String pid) {
+		ofNullable(managedInstances.remove(pid))
+			.ifPresent(LifecycleAware::stop);
+	}
+	
+	private static class AllCollection implements Collection<String> {
+
+		@Override
+		public int size() {
+			return MAX_VALUE;
+		}
+
+		@Override
+		public boolean isEmpty() {
+			return false;
+		}
+
+		@Override
+		public boolean contains(Object o) {
+			return true;
+		}
+
+		@Override
+		public Iterator<String> iterator() {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public Object[] toArray() {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public <T> T[] toArray(T[] a) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public boolean add(String e) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public boolean remove(Object o) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public boolean containsAll(Collection<?> c) {
+			return true;
+		}
+
+		@Override
+		public boolean addAll(Collection<? extends String> c) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public boolean removeAll(Collection<?> c) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public boolean retainAll(Collection<?> c) {
+			throw new UnsupportedOperationException();
+		}
+
+		@Override
+		public void clear() {
+			throw new UnsupportedOperationException();
+		}
+		
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XAEnabledTxContextBindingConnection.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XAEnabledTxContextBindingConnection.java
new file mode 100644
index 0000000..5b7c884
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XAEnabledTxContextBindingConnection.java
@@ -0,0 +1,92 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static org.osgi.service.transaction.control.TransactionStatus.NO_TRANSACTION;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.UUID;
+
+import javax.sql.DataSource;
+import javax.transaction.xa.XAResource;
+
+import org.apache.aries.tx.control.jdbc.common.impl.ConnectionWrapper;
+import org.apache.aries.tx.control.jdbc.common.impl.TxConnectionWrapper;
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XAConnectionWrapper;
+import org.osgi.service.transaction.control.TransactionContext;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+
+public class XAEnabledTxContextBindingConnection extends ConnectionWrapper {
+
+	private final TransactionControl	txControl;
+	private final UUID					resourceId;
+	private final DataSource			dataSource;
+
+	public XAEnabledTxContextBindingConnection(TransactionControl txControl,
+			DataSource dataSource, UUID resourceId, boolean xaEnabled, boolean localEnabled) {
+		this.txControl = txControl;
+		this.dataSource = dataSource;
+		this.resourceId = resourceId;
+	}
+
+	@Override
+	protected final Connection getDelegate() {
+
+		TransactionContext txContext = txControl.getCurrentContext();
+
+		if (txContext == null) {
+			throw new TransactionException("The resource " + dataSource
+					+ " cannot be accessed outside of an active Transaction Context");
+		}
+
+		Connection existing = (Connection) txContext.getScopedValue(resourceId);
+
+		if (existing != null) {
+			return existing;
+		}
+
+		Connection toReturn;
+		Connection toClose;
+
+		try {
+			if (txContext.getTransactionStatus() == NO_TRANSACTION) {
+				throw new TransactionException("The JTA DataSource cannot be used outside a transaction");
+			} else if (txContext.supportsXA()) {
+				toClose = dataSource.getConnection();
+				toReturn = new TxConnectionWrapper(toClose);
+				txContext.registerXAResource(getXAResource(toClose));
+			} else {
+				throw new TransactionException(
+						"There is a transaction active, but it does not support XA participants");
+			}
+		} catch (Exception sqle) {
+			throw new TransactionException(
+					"There was a problem getting hold of a database connection",
+					sqle);
+		}
+
+		
+		txContext.postCompletion(x -> {
+				try {
+					toClose.close();
+				} catch (SQLException sqle) {
+					// TODO log this
+				}
+			});
+		
+		txContext.putScopedValue(resourceId, toReturn);
+		
+		return toReturn;
+	}
+
+	
+	private XAResource getXAResource(Connection conn) throws SQLException {
+		if(conn instanceof XAConnectionWrapper) {
+			return ((XAConnectionWrapper)conn).getXaResource();
+		} else if(conn.isWrapperFor(XAConnectionWrapper.class)){
+			return conn.unwrap(XAConnectionWrapper.class).getXaResource();
+		} else {
+			throw new IllegalArgumentException("The XAResource for the connection cannot be found");
+		}
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManager.java b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManager.java
new file mode 100644
index 0000000..9ef9d55
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/main/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManager.java
@@ -0,0 +1,82 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+import static org.osgi.service.transaction.control.TransactionStatus.NO_TRANSACTION;
+
+import java.util.UUID;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.PersistenceException;
+
+import org.apache.aries.tx.control.jpa.common.impl.EntityManagerWrapper;
+import org.apache.aries.tx.control.jpa.common.impl.ScopedEntityManagerWrapper;
+import org.apache.aries.tx.control.jpa.common.impl.TxEntityManagerWrapper;
+import org.osgi.service.transaction.control.TransactionContext;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+
+public class XATxContextBindingEntityManager extends EntityManagerWrapper {
+
+	private final TransactionControl	txControl;
+	private final UUID					resourceId;
+	private final EntityManagerFactory	emf;
+	
+
+	public XATxContextBindingEntityManager(TransactionControl txControl,
+			EntityManagerFactory emf, UUID resourceId) {
+		this.txControl = txControl;
+		this.emf = emf;
+		this.resourceId = resourceId;
+	}
+
+	@Override
+	protected final EntityManager getRealEntityManager() {
+
+		TransactionContext txContext = txControl.getCurrentContext();
+
+		if (txContext == null) {
+			throw new TransactionException("The resource " + emf
+					+ " cannot be accessed outside of an active Transaction Context");
+		}
+
+		EntityManager existing = (EntityManager) txContext.getScopedValue(resourceId);
+
+		if (existing != null) {
+			return existing;
+		}
+
+		EntityManager toReturn;
+		EntityManager toClose;
+
+		try {
+			if (txContext.getTransactionStatus() == NO_TRANSACTION) {
+				toClose = emf.createEntityManager();
+				toReturn = new ScopedEntityManagerWrapper(toClose);
+			} else if (txContext.supportsXA()) {
+				toClose = emf.createEntityManager();
+				toReturn = new TxEntityManagerWrapper(toClose);
+				toClose.joinTransaction();
+			} else {
+				throw new TransactionException(
+						"There is a transaction active, but it does not support local participants");
+			}
+		} catch (Exception sqle) {
+			throw new TransactionException(
+					"There was a problem getting hold of a database connection",
+					sqle);
+		}
+
+		
+		txContext.postCompletion(x -> {
+				try {
+					toClose.close();
+				} catch (PersistenceException sqle) {
+					// TODO log this
+				}
+			});
+		
+		txContext.putScopedValue(resourceId, toReturn);
+		
+		return toReturn;
+	}
+}
diff --git a/tx-control-provider-jpa-xa/src/test/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManagerTest.java b/tx-control-provider-jpa-xa/src/test/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManagerTest.java
new file mode 100644
index 0000000..cccf7db
--- /dev/null
+++ b/tx-control-provider-jpa-xa/src/test/java/org/apache/aries/tx/control/jpa/xa/impl/XATxContextBindingEntityManagerTest.java
@@ -0,0 +1,193 @@
+package org.apache.aries.tx.control.jpa.xa.impl;
+
+
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.withSettings;
+import static org.osgi.service.transaction.control.TransactionStatus.ACTIVE;
+import static org.osgi.service.transaction.control.TransactionStatus.NO_TRANSACTION;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.sql.XAConnection;
+import javax.transaction.xa.XAResource;
+
+import org.apache.aries.tx.control.jdbc.xa.connection.impl.XAConnectionWrapper;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.osgi.service.transaction.control.TransactionContext;
+import org.osgi.service.transaction.control.TransactionControl;
+import org.osgi.service.transaction.control.TransactionException;
+
+@RunWith(MockitoJUnitRunner.class)
+public class XATxContextBindingEntityManagerTest {
+
+	@Mock
+	TransactionControl control;
+	
+	@Mock
+	TransactionContext context;
+	
+	@Mock
+	EntityManagerFactory emf;
+	
+	@Mock
+	EntityManager rawEm;
+
+	@Mock
+	XAResource xaResource;
+
+	Map<Object, Object> variables = new HashMap<>();
+	
+	UUID id = UUID.randomUUID();
+	
+	XATxContextBindingEntityManager em;
+	
+	@Before
+	public void setUp() throws SQLException {
+		Mockito.when(emf.createEntityManager()).thenReturn(rawEm).thenReturn(null);
+		
+		Mockito.doAnswer(i -> variables.put(i.getArguments()[0], i.getArguments()[1]))
+			.when(context).putScopedValue(Mockito.any(), Mockito.any());
+		Mockito.when(context.getScopedValue(Mockito.any()))
+			.thenAnswer(i -> variables.get(i.getArguments()[0]));
+		
+		em = new XATxContextBindingEntityManager(control, emf, id);
+	}
+	
+	private void setupNoTransaction() {
+		Mockito.when(control.getCurrentContext()).thenReturn(context);
+		Mockito.when(context.getTransactionStatus()).thenReturn(NO_TRANSACTION);
+	}
+
+	private void setupActiveTransaction() {
+		Mockito.when(control.getCurrentContext()).thenReturn(context);
+		Mockito.when(context.supportsXA()).thenReturn(true);
+		Mockito.when(context.getTransactionStatus()).thenReturn(ACTIVE);
+	}
+	
+	
+	@Test(expected=TransactionException.class)
+	public void testUnscoped() throws SQLException {
+		em.isOpen();
+	}
+
+	@Test
+	public void testNoTransaction() throws SQLException {
+		setupNoTransaction();
+		
+		em.isOpen();
+		em.isOpen();
+		
+		Mockito.verify(rawEm, times(2)).isOpen();
+		Mockito.verify(rawEm, times(0)).getTransaction();
+		Mockito.verify(context, times(0)).registerXAResource(Mockito.any());
+		
+		Mockito.verify(context).postCompletion(Mockito.any());
+	}
+
+	@Test
+	public void testActiveTransactionStraightXAConnection() throws SQLException {
+		
+		Connection con = Mockito.mock(Connection.class, withSettings().extraInterfaces(XAConnection.class));
+		Mockito.when(((XAConnection)con).getXAResource()).thenReturn(xaResource);
+		
+		Mockito.when(rawEm.unwrap(Connection.class)).thenReturn(con);
+		
+		setupActiveTransaction();
+		
+		em.isOpen();
+		em.isOpen();
+		
+		Mockito.verify(rawEm, times(2)).isOpen();
+		Mockito.verify(rawEm).joinTransaction();
+		
+		Mockito.verify(context).postCompletion(Mockito.any());
+	}
+
+	@Test
+	public void testActiveTransactionWrappedXAConnection() throws SQLException {
+		
+		XAConnection con = Mockito.mock(XAConnection.class);
+		Connection raw = Mockito.mock(Connection.class);
+		Mockito.when(con.getXAResource()).thenReturn(xaResource);
+		Mockito.when(con.getConnection()).thenReturn(raw);
+		
+		XAConnectionWrapper value = new XAConnectionWrapper(con);
+		
+		Mockito.when(rawEm.unwrap(Connection.class)).thenReturn(value);
+		
+		setupActiveTransaction();
+		
+		em.isOpen();
+		em.isOpen();
+		
+		Mockito.verify(rawEm, times(2)).isOpen();
+		Mockito.verify(rawEm).joinTransaction();
+		
+		Mockito.verify(context).postCompletion(Mockito.any());
+	}
+
+	@Test
+	public void testActiveTransactionUnwrappableXAConnection() throws SQLException {
+		
+		XAConnection xaCon = Mockito.mock(XAConnection.class);
+		Mockito.when(xaCon.getXAResource()).thenReturn(xaResource);
+		Connection con = Mockito.mock(Connection.class);
+		Mockito.when(con.unwrap(XAConnection.class)).thenReturn(xaCon);
+		Mockito.when(con.isWrapperFor(XAConnection.class)).thenReturn(true);
+		
+		Mockito.when(rawEm.unwrap(Connection.class)).thenReturn(con);
+		
+		setupActiveTransaction();
+		
+		em.isOpen();
+		em.isOpen();
+		
+		Mockito.verify(rawEm, times(2)).isOpen();
+		Mockito.verify(rawEm).joinTransaction();
+		
+		Mockito.verify(context).postCompletion(Mockito.any());
+	}
+
+	@Test
+	public void testActiveTransactionUnwrappableXAConnectionWrapper() throws SQLException {
+		
+		XAConnection xaCon = Mockito.mock(XAConnection.class);
+		Mockito.when(xaCon.getXAResource()).thenReturn(xaResource);
+		Connection con = Mockito.mock(Connection.class);
+		XAConnectionWrapper toReturn = new XAConnectionWrapper(xaCon);
+		Mockito.when(con.unwrap(XAConnectionWrapper.class)).thenReturn(toReturn);
+		Mockito.when(con.isWrapperFor(XAConnectionWrapper.class)).thenReturn(true);
+		
+		Mockito.when(rawEm.unwrap(Connection.class)).thenReturn(con);
+		
+		setupActiveTransaction();
+		
+		em.isOpen();
+		em.isOpen();
+		
+		Mockito.verify(rawEm, times(2)).isOpen();
+		Mockito.verify(rawEm).joinTransaction();
+		
+		Mockito.verify(context).postCompletion(Mockito.any());
+	}
+
+	@Test(expected=TransactionException.class)
+	public void testActiveTransactionNoXA() throws SQLException {
+		setupActiveTransaction();
+		
+		Mockito.when(context.supportsXA()).thenReturn(false);
+		em.isOpen();
+	}
+
+}