You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@aries.apache.org by ga...@apache.org on 2010/06/16 02:52:47 UTC
svn commit: r955102 [3/10] - in /incubator/aries/trunk/jpa: ./ jpa-api/
jpa-api/src/main/java/org/apache/aries/jpa/container/
jpa-api/src/main/java/org/apache/aries/jpa/container/context/
jpa-api/src/main/java/org/apache/aries/jpa/container/parsing/ jp...
Modified: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java?rev=955102&r1=955101&r2=955102&view=diff
==============================================================================
--- incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java (original)
+++ incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java Wed Jun 16 00:52:45 2010
@@ -1,354 +1,354 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 WARRANTIESOR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.aries.jpa.container.context.transaction.impl;
-
-import java.util.Map;
-
-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.TransactionRequiredException;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.metamodel.Metamodel;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A <code>PersistenceContextType.TRANSACTION</code> {@link EntityManager} instance
- */
-public class JTAEntityManager implements EntityManager {
- /** Logger */
- private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.jpa.container.context");
-
- /** The {@link EntityManagerFactory} that can create new {@link EntityManager} instances */
- private final EntityManagerFactory emf;
- /** The map of properties to pass when creating EntityManagers */
- private final Map<String, Object> props;
- /** A registry for creating new persistence contexts */
- private final JTAPersistenceContextRegistry reg;
- /**
- * The entity manager to use when there is no transaction. Note that there is one of these
- * per injection site.
- */
- private EntityManager detachedManager = null;
-
- public JTAEntityManager(EntityManagerFactory factory,
- Map<String, Object> properties, JTAPersistenceContextRegistry registry) {
- emf = factory;
- props = properties;
- reg = registry;
- }
-
- /**
- * Get the target persistence context
- * @param forceTransaction Whether the returned entity manager needs to be bound to a transaction
- * @throws TransactionRequiredException if forceTransaction is true and no transaction is available
- * @return
- */
- private EntityManager getPersistenceContext(boolean forceTransaction)
- {
- if (forceTransaction) {
- return reg.getCurrentPersistenceContext(emf, props);
- } else {
- if (reg.isTransactionActive()) {
- return reg.getCurrentPersistenceContext(emf, props);
- } else {
- if(!!!reg.jtaIntegrationAvailable() && _logger.isDebugEnabled())
- _logger.debug("No integration with JTA transactions is available. No transaction context is active.");
-
- if (detachedManager == null) {
- EntityManager temp = emf.createEntityManager(props);
-
- synchronized (this) {
- if (detachedManager == null) {
- detachedManager = temp;
- temp = null;
- }
- }
-
- if (temp != null)
- temp.close();
- }
- return detachedManager;
- }
- }
- }
-
- /**
- * Called reflectively by blueprint
- */
- public void internalClose() {
- EntityManager temp = null;
-
- synchronized (this) {
- temp = detachedManager;
- detachedManager = null;
- }
-
- if (temp != null)
- temp.close();
- }
-
- public void clear()
- {
- getPersistenceContext(false).clear();
- }
-
- public void close()
- {
- //TODO add a message here
- throw new IllegalStateException("It is forbidden to call close on a container managed EntityManager");
- }
-
- public boolean contains(Object arg0)
- {
- return getPersistenceContext(false).contains(arg0);
- }
-
- public Query createNamedQuery(String arg0)
- {
- return getPersistenceContext(false).createNamedQuery(arg0);
- }
-
- public Query createNativeQuery(String arg0)
- {
- return getPersistenceContext(false).createNativeQuery(arg0);
- }
-
- @SuppressWarnings("unchecked")
- public Query createNativeQuery(String arg0, Class arg1)
- {
- return getPersistenceContext(false).createNativeQuery(arg0, arg1);
- }
-
- public Query createNativeQuery(String arg0, String arg1)
- {
- return getPersistenceContext(false).createNativeQuery(arg0, arg1);
- }
-
- public Query createQuery(String arg0)
- {
- return getPersistenceContext(false).createQuery(arg0);
- }
-
- public <T> T find(Class<T> arg0, Object arg1)
- {
- return getPersistenceContext(false).find(arg0, arg1);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void flush()
- {
- getPersistenceContext(true).flush();
- }
-
- public Object getDelegate()
- {
- return getPersistenceContext(false).getDelegate();
- }
-
- public FlushModeType getFlushMode()
- {
- return getPersistenceContext(false).getFlushMode();
- }
-
- public <T> T getReference(Class<T> arg0, Object arg1)
- {
- return getPersistenceContext(false).getReference(arg0, arg1);
- }
-
- public EntityTransaction getTransaction()
- {
- throw new IllegalStateException("Transaction management is not available for container managed EntityManagers");
- }
-
- public boolean isOpen()
- {
- return true;
- }
-
- public void joinTransaction()
- {
- //This should be a no-op for a JTA entity manager
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void lock(Object arg0, LockModeType arg1)
- {
- getPersistenceContext(true).lock(arg0, arg1);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public <T> T merge(T arg0)
- {
- return getPersistenceContext(true).merge(arg0);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void persist(Object arg0)
- {
- getPersistenceContext(true).persist(arg0);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void refresh(Object arg0)
- {
- getPersistenceContext(true).refresh(arg0);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void remove(Object arg0)
- {
- getPersistenceContext(true).remove(arg0);
- }
-
- public void setFlushMode(FlushModeType arg0)
- {
- getPersistenceContext(false).setFlushMode(arg0);
- }
-
- public <T> TypedQuery<T> createNamedQuery(String arg0, Class<T> arg1)
- {
- return getPersistenceContext(false).createNamedQuery(arg0, arg1);
- }
-
- public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0)
- {
- return getPersistenceContext(false).createQuery(arg0);
- }
-
- public <T> TypedQuery<T> createQuery(String arg0, Class<T> arg1)
- {
- return getPersistenceContext(false).createQuery(arg0, arg1);
- }
-
- public void detach(Object arg0)
- {
- getPersistenceContext(false).detach(arg0);
- }
-
- public <T> T find(Class<T> arg0, Object arg1, Map<String, Object> arg2)
- {
- return getPersistenceContext(false).find(arg0, arg1, arg2);
- }
-
- /**
- * @throws TransactionRequiredException if lock mode is not NONE
- */
- public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2)
- {
- return getPersistenceContext(arg2 != LockModeType.NONE).find(arg0, arg1, arg2);
- }
-
- /**
- * @throws TransactionRequiredException if lock mode is not NONE
- */
- public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String, Object> arg3)
- {
- return getPersistenceContext(arg2 != LockModeType.NONE).find(arg0, arg1, arg2, arg3);
- }
-
- public CriteriaBuilder getCriteriaBuilder()
- {
- return getPersistenceContext(false).getCriteriaBuilder();
- }
-
- public EntityManagerFactory getEntityManagerFactory()
- {
- return emf;
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public LockModeType getLockMode(Object arg0)
- {
- return getPersistenceContext(true).getLockMode(arg0);
- }
-
- public Metamodel getMetamodel()
- {
- return getPersistenceContext(false).getMetamodel();
- }
-
- public Map<String, Object> getProperties()
- {
- return getPersistenceContext(false).getProperties();
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void lock(Object arg0, LockModeType arg1, Map<String, Object> arg2)
- {
- getPersistenceContext(true).lock(arg0, arg1, arg2);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void refresh(Object arg0, Map<String, Object> arg1)
- {
- getPersistenceContext(true).refresh(arg0, arg1);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void refresh(Object arg0, LockModeType arg1)
- {
- getPersistenceContext(true).refresh(arg0, arg1);
- }
-
- /**
- * @throws TransactionRequiredException
- */
- public void refresh(Object arg0, LockModeType arg1, Map<String, Object> arg2)
- {
- getPersistenceContext(true).refresh(arg0, arg1, arg2);
- }
-
- public void setProperty(String arg0, Object arg1)
- {
- getPersistenceContext(false).setProperty(arg0, arg1);
- }
-
- public <T> T unwrap(Class<T> arg0)
- {
- return getPersistenceContext(false).unwrap(arg0);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.jpa.container.context.transaction.impl;
+
+import java.util.Map;
+
+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.TransactionRequiredException;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.metamodel.Metamodel;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A <code>PersistenceContextType.TRANSACTION</code> {@link EntityManager} instance
+ */
+public class JTAEntityManager implements EntityManager {
+ /** Logger */
+ private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.jpa.container.context");
+
+ /** The {@link EntityManagerFactory} that can create new {@link EntityManager} instances */
+ private final EntityManagerFactory emf;
+ /** The map of properties to pass when creating EntityManagers */
+ private final Map<String, Object> props;
+ /** A registry for creating new persistence contexts */
+ private final JTAPersistenceContextRegistry reg;
+ /**
+ * The entity manager to use when there is no transaction. Note that there is one of these
+ * per injection site.
+ */
+ private EntityManager detachedManager = null;
+
+ public JTAEntityManager(EntityManagerFactory factory,
+ Map<String, Object> properties, JTAPersistenceContextRegistry registry) {
+ emf = factory;
+ props = properties;
+ reg = registry;
+ }
+
+ /**
+ * Get the target persistence context
+ * @param forceTransaction Whether the returned entity manager needs to be bound to a transaction
+ * @throws TransactionRequiredException if forceTransaction is true and no transaction is available
+ * @return
+ */
+ private EntityManager getPersistenceContext(boolean forceTransaction)
+ {
+ if (forceTransaction) {
+ return reg.getCurrentPersistenceContext(emf, props);
+ } else {
+ if (reg.isTransactionActive()) {
+ return reg.getCurrentPersistenceContext(emf, props);
+ } else {
+ if(!!!reg.jtaIntegrationAvailable() && _logger.isDebugEnabled())
+ _logger.debug("No integration with JTA transactions is available. No transaction context is active.");
+
+ if (detachedManager == null) {
+ EntityManager temp = emf.createEntityManager(props);
+
+ synchronized (this) {
+ if (detachedManager == null) {
+ detachedManager = temp;
+ temp = null;
+ }
+ }
+
+ if (temp != null)
+ temp.close();
+ }
+ return detachedManager;
+ }
+ }
+ }
+
+ /**
+ * Called reflectively by blueprint
+ */
+ public void internalClose() {
+ EntityManager temp = null;
+
+ synchronized (this) {
+ temp = detachedManager;
+ detachedManager = null;
+ }
+
+ if (temp != null)
+ temp.close();
+ }
+
+ public void clear()
+ {
+ getPersistenceContext(false).clear();
+ }
+
+ public void close()
+ {
+ //TODO add a message here
+ throw new IllegalStateException("It is forbidden to call close on a container managed EntityManager");
+ }
+
+ public boolean contains(Object arg0)
+ {
+ return getPersistenceContext(false).contains(arg0);
+ }
+
+ public Query createNamedQuery(String arg0)
+ {
+ return getPersistenceContext(false).createNamedQuery(arg0);
+ }
+
+ public Query createNativeQuery(String arg0)
+ {
+ return getPersistenceContext(false).createNativeQuery(arg0);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Query createNativeQuery(String arg0, Class arg1)
+ {
+ return getPersistenceContext(false).createNativeQuery(arg0, arg1);
+ }
+
+ public Query createNativeQuery(String arg0, String arg1)
+ {
+ return getPersistenceContext(false).createNativeQuery(arg0, arg1);
+ }
+
+ public Query createQuery(String arg0)
+ {
+ return getPersistenceContext(false).createQuery(arg0);
+ }
+
+ public <T> T find(Class<T> arg0, Object arg1)
+ {
+ return getPersistenceContext(false).find(arg0, arg1);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void flush()
+ {
+ getPersistenceContext(true).flush();
+ }
+
+ public Object getDelegate()
+ {
+ return getPersistenceContext(false).getDelegate();
+ }
+
+ public FlushModeType getFlushMode()
+ {
+ return getPersistenceContext(false).getFlushMode();
+ }
+
+ public <T> T getReference(Class<T> arg0, Object arg1)
+ {
+ return getPersistenceContext(false).getReference(arg0, arg1);
+ }
+
+ public EntityTransaction getTransaction()
+ {
+ throw new IllegalStateException("Transaction management is not available for container managed EntityManagers");
+ }
+
+ public boolean isOpen()
+ {
+ return true;
+ }
+
+ public void joinTransaction()
+ {
+ //This should be a no-op for a JTA entity manager
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void lock(Object arg0, LockModeType arg1)
+ {
+ getPersistenceContext(true).lock(arg0, arg1);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public <T> T merge(T arg0)
+ {
+ return getPersistenceContext(true).merge(arg0);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void persist(Object arg0)
+ {
+ getPersistenceContext(true).persist(arg0);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void refresh(Object arg0)
+ {
+ getPersistenceContext(true).refresh(arg0);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void remove(Object arg0)
+ {
+ getPersistenceContext(true).remove(arg0);
+ }
+
+ public void setFlushMode(FlushModeType arg0)
+ {
+ getPersistenceContext(false).setFlushMode(arg0);
+ }
+
+ public <T> TypedQuery<T> createNamedQuery(String arg0, Class<T> arg1)
+ {
+ return getPersistenceContext(false).createNamedQuery(arg0, arg1);
+ }
+
+ public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0)
+ {
+ return getPersistenceContext(false).createQuery(arg0);
+ }
+
+ public <T> TypedQuery<T> createQuery(String arg0, Class<T> arg1)
+ {
+ return getPersistenceContext(false).createQuery(arg0, arg1);
+ }
+
+ public void detach(Object arg0)
+ {
+ getPersistenceContext(false).detach(arg0);
+ }
+
+ public <T> T find(Class<T> arg0, Object arg1, Map<String, Object> arg2)
+ {
+ return getPersistenceContext(false).find(arg0, arg1, arg2);
+ }
+
+ /**
+ * @throws TransactionRequiredException if lock mode is not NONE
+ */
+ public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2)
+ {
+ return getPersistenceContext(arg2 != LockModeType.NONE).find(arg0, arg1, arg2);
+ }
+
+ /**
+ * @throws TransactionRequiredException if lock mode is not NONE
+ */
+ public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String, Object> arg3)
+ {
+ return getPersistenceContext(arg2 != LockModeType.NONE).find(arg0, arg1, arg2, arg3);
+ }
+
+ public CriteriaBuilder getCriteriaBuilder()
+ {
+ return getPersistenceContext(false).getCriteriaBuilder();
+ }
+
+ public EntityManagerFactory getEntityManagerFactory()
+ {
+ return emf;
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public LockModeType getLockMode(Object arg0)
+ {
+ return getPersistenceContext(true).getLockMode(arg0);
+ }
+
+ public Metamodel getMetamodel()
+ {
+ return getPersistenceContext(false).getMetamodel();
+ }
+
+ public Map<String, Object> getProperties()
+ {
+ return getPersistenceContext(false).getProperties();
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void lock(Object arg0, LockModeType arg1, Map<String, Object> arg2)
+ {
+ getPersistenceContext(true).lock(arg0, arg1, arg2);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void refresh(Object arg0, Map<String, Object> arg1)
+ {
+ getPersistenceContext(true).refresh(arg0, arg1);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void refresh(Object arg0, LockModeType arg1)
+ {
+ getPersistenceContext(true).refresh(arg0, arg1);
+ }
+
+ /**
+ * @throws TransactionRequiredException
+ */
+ public void refresh(Object arg0, LockModeType arg1, Map<String, Object> arg2)
+ {
+ getPersistenceContext(true).refresh(arg0, arg1, arg2);
+ }
+
+ public void setProperty(String arg0, Object arg1)
+ {
+ getPersistenceContext(false).setProperty(arg0, arg1);
+ }
+
+ public <T> T unwrap(Class<T> arg0)
+ {
+ return getPersistenceContext(false).unwrap(arg0);
+ }
+}
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAEntityManager.java
------------------------------------------------------------------------------
svn:mime-type = text/plain
Modified: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java?rev=955102&r1=955101&r2=955102&view=diff
==============================================================================
--- incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java (original)
+++ incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java Wed Jun 16 00:52:45 2010
@@ -1,226 +1,226 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 WARRANTIESOR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.aries.jpa.container.context.transaction.impl;
-
-import java.util.IdentityHashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.TransactionRequiredException;
-import javax.transaction.Synchronization;
-import javax.transaction.TransactionSynchronizationRegistry;
-
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This class is used to manage the lifecycle of JTA peristence contexts
- */
-public final class JTAPersistenceContextRegistry {
- /** Logger */
- private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.jpa.container.context");
- /** The unique key we use to find our Map */
- private static final TSRKey EMF_MAP_KEY = new TSRKey();
-
- /**
- * A simple class to avoid key collisions in the TransactionSynchronizationRegistry.
- * As recommended by {@link TransactionSynchronizationRegistry#putResource(Object, Object)}
- */
- private final static class TSRKey {
-
- @Override
- public final boolean equals(Object o) {
- return (this == o);
- }
-
- @Override
- public final int hashCode() {
- return 0xDEADBEEF;
- }
- }
-
- /**
- * The transaction synchronization registry, used to determine the currently
- * active transaction, and to register for post-commit cleanup.
- */
- private TransactionSynchronizationRegistry tranRegistry;
-
- /**
- * A flag to indicate whether the {@link TransactionSynchronizationRegistry} is available.
- * The initial value is false, as defined by {@link AtomicBoolean#AtomicBoolean()}.
- */
- private final AtomicBoolean registryAvailable = new AtomicBoolean();
-
- /**
- * Get a PersistenceContext for the current transaction. The persistence context will
- * automatically be closed when the transaction completes.
- *
- * @param persistenceUnit The peristence unit to create the persitence context from
- * @param properties Any properties that should be passed on the call to {@code createEntityManager()}.
- * The properties are NOT used for retrieving an already created persistence context.
- *
- * @return A persistence context associated with the current transaction. Note that this will
- * need to be wrappered to obey the JPA spec by throwing the correct exceptions
- * @throws {@link TransactionRequiredException} if there is no active transaction.
- */
- @SuppressWarnings("unchecked")
- public final EntityManager getCurrentPersistenceContext(EntityManagerFactory persistenceUnit, Map<?,?> properties) throws TransactionRequiredException
- {
- //There will only ever be one thread associated with a transaction at a given time
- //As a result, it is only the outer map that needs to be thread safe.
-
- //Throw the error on to the client
- if(!!!isTransactionActive()) {
- if(jtaIntegrationAvailable())
- throw new TransactionRequiredException("No transaction currently active");
- else {
- throw new TransactionRequiredException("No JTA transaction services implementation is currently available. As a result the" +
- " JPA container cannot integrate with JTA transactions.");
- }
- }
- EntityManager toReturn = null;
-
- //Get hold of the Map. If there is no Map already registered then add one.
- //We don't need to worry about a race condition, as no other thread will
- //share our transaction and be able to access our Map
- Map<EntityManagerFactory, EntityManager> contextsForTransaction = (Map<EntityManagerFactory, EntityManager>) tranRegistry.getResource(EMF_MAP_KEY);
-
- //If we have a map then find an EntityManager, else create a new Map add it to the registry, and register for cleanup
- if(contextsForTransaction != null) {
- toReturn = contextsForTransaction.get(persistenceUnit);
- } else {
- contextsForTransaction = new IdentityHashMap<EntityManagerFactory, EntityManager>();
- try {
- tranRegistry.putResource(EMF_MAP_KEY, contextsForTransaction);
- } catch (IllegalStateException e) {
- _logger.warn("Unable to create a persistence context for the transaction {} because the is not active", new Object[] {tranRegistry.getTransactionKey()});
- throw new TransactionRequiredException("Unable to assiociate resources with transaction " + tranRegistry.getTransactionKey());
- }
- }
-
- //If we have no previously created EntityManager
- if(toReturn == null) {
- toReturn = (properties == null) ? persistenceUnit.createEntityManager() : persistenceUnit.createEntityManager(properties);
- if(_logger.isDebugEnabled())
- _logger.debug("Created a new persistence context {} for transaction {}.", new Object[] {toReturn, tranRegistry.getTransactionKey()});
- try {
- tranRegistry.registerInterposedSynchronization(new EntityManagerClearUp(toReturn));
- } catch (IllegalStateException e) {
- _logger.warn("No persistence context could be created as the JPA container could not register a synchronization with the transaction {}.", new Object[] {tranRegistry.getTransactionKey()});
- toReturn.close();
- throw new TransactionRequiredException("Unable to synchronize with transaction " + tranRegistry.getTransactionKey());
- }
- contextsForTransaction.put(persistenceUnit, toReturn);
- } else {
- if(_logger.isDebugEnabled())
- _logger.debug("Re-using a persistence context for transaction " + tranRegistry.getTransactionKey());
- }
- return toReturn;
- }
-
- /**
- * Determine whether there is an active transaction on the thread
- * @return
- */
- public final boolean isTransactionActive()
- {
- return registryAvailable.get() && tranRegistry.getTransactionKey() != null;
- }
-
- /**
- * Provide a {@link TransactionSynchronizationRegistry} to use
- * @param tranRegistry
- */
- public final void setTranRegistry(TransactionSynchronizationRegistry tranRegistry) {
- this.tranRegistry = tranRegistry;
- }
-
- /**
- * Returns true if we have access to a {@link TransactionSynchronizationRegistry} and
- * can manage persistence contexts
- * @return
- */
- public final boolean jtaIntegrationAvailable()
- {
- return registryAvailable.get();
- }
-
- /**
- * Called by the blueprint container to indicate that a new {@link TransactionSynchronizationRegistry}
- * will be used by the runtime
- * @param ref
- */
- public final void addRegistry(ServiceReference ref) {
- boolean oldValue = registryAvailable.getAndSet(true);
- if(oldValue) {
- _logger.warn("The TransactionSynchronizationRegistry used to manage persistence contexts has been replaced." +
- " The new TransactionSynchronizationRegistry, {}, will now be used to manage persistence contexts." +
- " Managed persistence contexts may not work correctly unless the runtime uses the new JTA Transaction services implementation" +
- " to manage transactions.", new Object[] {ref});
- } else {
- _logger.info("A TransactionSynchronizationRegistry service is now available in the runtime. Managed persistence contexts will now" +
- "integrate with JTA transactions using {}.", new Object[] {ref});
- }
- }
-
- public final void removeRegistry(ServiceReference ref) {
- registryAvailable.set(false);
- _logger.warn("The TransactionSynchronizationRegistry used to manage persistence contexts is no longer available." +
- " Managed persistence contexts will no longer be able to integrate with JTA transactions, and will behave as if" +
- " no there is no transaction context at all times until a new TransactionSynchronizationRegistry is available." +
- " Applications using managed persistence contexts may not work correctly until a new JTA Transaction services" +
- " implementation is available.");
- }
-
- /**
- * This class is used to close EntityManager instances once the transaction has committed,
- * and clear the persistenceContextRegistry of old persistence contexts.
- */
- private final static class EntityManagerClearUp implements Synchronization {
-
- private final EntityManager context;
-
- /**
- * Create a Synchronization to clear up our EntityManagers
- * @param em
- */
- public EntityManagerClearUp(EntityManager em)
- {
- context = em;
- }
-
- public final void beforeCompletion() {
- //This is a no-op;
- }
-
- @SuppressWarnings("unchecked")
- public final void afterCompletion(int arg0) {
- if(_logger.isDebugEnabled())
- _logger.debug("Clearing up EntityManager {} as the transaction has completed.", new Object[] {context});
- try {
- context.close();
- } catch (Exception e) {
- _logger.warn("There was an error when the container closed an EntityManager", context);
- }
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 WARRANTIESOR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.aries.jpa.container.context.transaction.impl;
+
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.TransactionRequiredException;
+import javax.transaction.Synchronization;
+import javax.transaction.TransactionSynchronizationRegistry;
+
+import org.osgi.framework.ServiceReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is used to manage the lifecycle of JTA peristence contexts
+ */
+public final class JTAPersistenceContextRegistry {
+ /** Logger */
+ private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.jpa.container.context");
+ /** The unique key we use to find our Map */
+ private static final TSRKey EMF_MAP_KEY = new TSRKey();
+
+ /**
+ * A simple class to avoid key collisions in the TransactionSynchronizationRegistry.
+ * As recommended by {@link TransactionSynchronizationRegistry#putResource(Object, Object)}
+ */
+ private final static class TSRKey {
+
+ @Override
+ public final boolean equals(Object o) {
+ return (this == o);
+ }
+
+ @Override
+ public final int hashCode() {
+ return 0xDEADBEEF;
+ }
+ }
+
+ /**
+ * The transaction synchronization registry, used to determine the currently
+ * active transaction, and to register for post-commit cleanup.
+ */
+ private TransactionSynchronizationRegistry tranRegistry;
+
+ /**
+ * A flag to indicate whether the {@link TransactionSynchronizationRegistry} is available.
+ * The initial value is false, as defined by {@link AtomicBoolean#AtomicBoolean()}.
+ */
+ private final AtomicBoolean registryAvailable = new AtomicBoolean();
+
+ /**
+ * Get a PersistenceContext for the current transaction. The persistence context will
+ * automatically be closed when the transaction completes.
+ *
+ * @param persistenceUnit The peristence unit to create the persitence context from
+ * @param properties Any properties that should be passed on the call to {@code createEntityManager()}.
+ * The properties are NOT used for retrieving an already created persistence context.
+ *
+ * @return A persistence context associated with the current transaction. Note that this will
+ * need to be wrappered to obey the JPA spec by throwing the correct exceptions
+ * @throws {@link TransactionRequiredException} if there is no active transaction.
+ */
+ @SuppressWarnings("unchecked")
+ public final EntityManager getCurrentPersistenceContext(EntityManagerFactory persistenceUnit, Map<?,?> properties) throws TransactionRequiredException
+ {
+ //There will only ever be one thread associated with a transaction at a given time
+ //As a result, it is only the outer map that needs to be thread safe.
+
+ //Throw the error on to the client
+ if(!!!isTransactionActive()) {
+ if(jtaIntegrationAvailable())
+ throw new TransactionRequiredException("No transaction currently active");
+ else {
+ throw new TransactionRequiredException("No JTA transaction services implementation is currently available. As a result the" +
+ " JPA container cannot integrate with JTA transactions.");
+ }
+ }
+ EntityManager toReturn = null;
+
+ //Get hold of the Map. If there is no Map already registered then add one.
+ //We don't need to worry about a race condition, as no other thread will
+ //share our transaction and be able to access our Map
+ Map<EntityManagerFactory, EntityManager> contextsForTransaction = (Map<EntityManagerFactory, EntityManager>) tranRegistry.getResource(EMF_MAP_KEY);
+
+ //If we have a map then find an EntityManager, else create a new Map add it to the registry, and register for cleanup
+ if(contextsForTransaction != null) {
+ toReturn = contextsForTransaction.get(persistenceUnit);
+ } else {
+ contextsForTransaction = new IdentityHashMap<EntityManagerFactory, EntityManager>();
+ try {
+ tranRegistry.putResource(EMF_MAP_KEY, contextsForTransaction);
+ } catch (IllegalStateException e) {
+ _logger.warn("Unable to create a persistence context for the transaction {} because the is not active", new Object[] {tranRegistry.getTransactionKey()});
+ throw new TransactionRequiredException("Unable to assiociate resources with transaction " + tranRegistry.getTransactionKey());
+ }
+ }
+
+ //If we have no previously created EntityManager
+ if(toReturn == null) {
+ toReturn = (properties == null) ? persistenceUnit.createEntityManager() : persistenceUnit.createEntityManager(properties);
+ if(_logger.isDebugEnabled())
+ _logger.debug("Created a new persistence context {} for transaction {}.", new Object[] {toReturn, tranRegistry.getTransactionKey()});
+ try {
+ tranRegistry.registerInterposedSynchronization(new EntityManagerClearUp(toReturn));
+ } catch (IllegalStateException e) {
+ _logger.warn("No persistence context could be created as the JPA container could not register a synchronization with the transaction {}.", new Object[] {tranRegistry.getTransactionKey()});
+ toReturn.close();
+ throw new TransactionRequiredException("Unable to synchronize with transaction " + tranRegistry.getTransactionKey());
+ }
+ contextsForTransaction.put(persistenceUnit, toReturn);
+ } else {
+ if(_logger.isDebugEnabled())
+ _logger.debug("Re-using a persistence context for transaction " + tranRegistry.getTransactionKey());
+ }
+ return toReturn;
+ }
+
+ /**
+ * Determine whether there is an active transaction on the thread
+ * @return
+ */
+ public final boolean isTransactionActive()
+ {
+ return registryAvailable.get() && tranRegistry.getTransactionKey() != null;
+ }
+
+ /**
+ * Provide a {@link TransactionSynchronizationRegistry} to use
+ * @param tranRegistry
+ */
+ public final void setTranRegistry(TransactionSynchronizationRegistry tranRegistry) {
+ this.tranRegistry = tranRegistry;
+ }
+
+ /**
+ * Returns true if we have access to a {@link TransactionSynchronizationRegistry} and
+ * can manage persistence contexts
+ * @return
+ */
+ public final boolean jtaIntegrationAvailable()
+ {
+ return registryAvailable.get();
+ }
+
+ /**
+ * Called by the blueprint container to indicate that a new {@link TransactionSynchronizationRegistry}
+ * will be used by the runtime
+ * @param ref
+ */
+ public final void addRegistry(ServiceReference ref) {
+ boolean oldValue = registryAvailable.getAndSet(true);
+ if(oldValue) {
+ _logger.warn("The TransactionSynchronizationRegistry used to manage persistence contexts has been replaced." +
+ " The new TransactionSynchronizationRegistry, {}, will now be used to manage persistence contexts." +
+ " Managed persistence contexts may not work correctly unless the runtime uses the new JTA Transaction services implementation" +
+ " to manage transactions.", new Object[] {ref});
+ } else {
+ _logger.info("A TransactionSynchronizationRegistry service is now available in the runtime. Managed persistence contexts will now" +
+ "integrate with JTA transactions using {}.", new Object[] {ref});
+ }
+ }
+
+ public final void removeRegistry(ServiceReference ref) {
+ registryAvailable.set(false);
+ _logger.warn("The TransactionSynchronizationRegistry used to manage persistence contexts is no longer available." +
+ " Managed persistence contexts will no longer be able to integrate with JTA transactions, and will behave as if" +
+ " no there is no transaction context at all times until a new TransactionSynchronizationRegistry is available." +
+ " Applications using managed persistence contexts may not work correctly until a new JTA Transaction services" +
+ " implementation is available.");
+ }
+
+ /**
+ * This class is used to close EntityManager instances once the transaction has committed,
+ * and clear the persistenceContextRegistry of old persistence contexts.
+ */
+ private final static class EntityManagerClearUp implements Synchronization {
+
+ private final EntityManager context;
+
+ /**
+ * Create a Synchronization to clear up our EntityManagers
+ * @param em
+ */
+ public EntityManagerClearUp(EntityManager em)
+ {
+ context = em;
+ }
+
+ public final void beforeCompletion() {
+ //This is a no-op;
+ }
+
+ @SuppressWarnings("unchecked")
+ public final void afterCompletion(int arg0) {
+ if(_logger.isDebugEnabled())
+ _logger.debug("Clearing up EntityManager {} as the transaction has completed.", new Object[] {context});
+ try {
+ context.close();
+ } catch (Exception e) {
+ _logger.warn("There was an error when the container closed an EntityManager", context);
+ }
+ }
+ }
+}
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistry.java
------------------------------------------------------------------------------
svn:mime-type = text/plain
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/resources/OSGI-INF/blueprint/jpa.xml
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/resources/OSGI-INF/blueprint/jpa.xml
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/main/resources/OSGI-INF/blueprint/jpa.xml
------------------------------------------------------------------------------
svn:mime-type = text/xml
Modified: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java?rev=955102&r1=955101&r2=955102&view=diff
==============================================================================
--- incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java (original)
+++ incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java Wed Jun 16 00:52:45 2010
@@ -1,288 +1,288 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-package org.apache.aries.jpa.container.context.impl;
-
-import static java.lang.Boolean.TRUE;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.util.HashMap;
-import java.util.Hashtable;
-
-import javax.persistence.EntityManagerFactory;
-
-import org.apache.aries.jpa.container.PersistenceUnitConstants;
-import org.apache.aries.jpa.container.context.PersistenceContextProvider;
-import org.apache.aries.mocks.BundleContextMock;
-import org.apache.aries.mocks.BundleMock;
-import org.apache.aries.unittest.mocks.Skeleton;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-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.Version;
-
-
-public class PersistenceContextManagerTest {
-
- private BundleContext context;
- private PersistenceContextManager mgr;
-
- private EntityManagerFactory emf1;
- private EntityManagerFactory emf2;
-
- private ServiceRegistration reg1;
- private ServiceRegistration reg2;
-
- private Bundle client1;
- private Bundle client2;
-
- @Before
- public void setUp()
- {
- client1 = Skeleton.newMock(Bundle.class);
- client2 = Skeleton.newMock(Bundle.class);
- emf1 = Skeleton.newMock(EntityManagerFactory.class);
- emf2 = Skeleton.newMock(EntityManagerFactory.class);
- context = Skeleton.newMock(new BundleMock("system.bundle", new Hashtable<Object, Object>()), Bundle.class).getBundleContext();
- mgr = new PersistenceContextManager(context, null);
- mgr.open();
- }
-
- @After
- public void tearDown()
- {
- BundleContextMock.clear();
- }
-
- /**
- * A simple test to show we get a service registered when a unit
- * is registered first.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testUnitThenContext() throws InvalidSyntaxException
- {
- String unitName = "unit";
-
- reg1 = registerUnit(emf1, unitName, TRUE);
-
- assertNoContextRegistered();
-
- mgr.registerContext(unitName, client1, new HashMap<String, Object>());
-
- assertContextRegistered(unitName);
- }
-
- /**
- * A simple test to show we get a service unregistered when a context
- * is removed.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testUnitThenContextThenRemoveContext() throws InvalidSyntaxException
- {
- testUnitThenContext();
- mgr.unregisterContext("unit", client1);
-
- assertNoContextRegistered();
- }
-
- /**
- * A simple test to show we get a service unregistered when a unit
- * is removed.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testUnitThenContextThenRemoveUnit() throws InvalidSyntaxException
- {
- testUnitThenContext();
- reg1.unregister();
-
- assertNoContextRegistered();
- }
-
- /**
- * A simple test to show we get a service registered when a context
- * is registered first.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testContextThenUnit() throws InvalidSyntaxException
- {
- String unitName = "unit";
-
- mgr.registerContext(unitName, client1, new HashMap<String, Object>());
-
- assertNoContextRegistered();
-
- reg1 = registerUnit(emf1, unitName, TRUE);
-
- assertContextRegistered(unitName);
- }
-
- /**
- * A simple test to show we get a service unregistered when a context
- * is removed.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testContextThenUnitThenRemoveContext() throws InvalidSyntaxException
- {
- testContextThenUnit();
- mgr.unregisterContext("unit", client1);
-
- assertNoContextRegistered();
- }
-
- /**
- * A simple test to show we get a service unregistered when a unit
- * is removed.
- *
- * @throws InvalidSyntaxException
- */
- @Test
- public void testContextThenUnitThenRemoveUnit() throws InvalidSyntaxException
- {
- testContextThenUnit();
- reg1.unregister();
-
- assertNoContextRegistered();
- }
-
- /**
- * Test that we don't register a service when the unit and
- * context don't match
- */
- @Test
- public void testAddDifferentContext() throws InvalidSyntaxException
- {
- reg1 = registerUnit(emf1, "unit", TRUE);
-
- assertNoContextRegistered();
-
- mgr.registerContext("context", client1, new HashMap<String, Object>());
-
- assertNoContextRegistered();
- }
-
- /**
- * Test that we don't unregister a service when a different context is
- * removed
- * @throws InvalidSyntaxException
- */
- @Test
- public void testRemoveDifferentContext() throws InvalidSyntaxException
- {
- testAddDifferentContext();
-
- mgr.registerContext("unit", client1, new HashMap<String, Object>());
-
- assertContextRegistered("unit");
-
- mgr.unregisterContext("context", client1);
-
- assertContextRegistered("unit");
- }
-
- /**
- * Test that we don't unregister a service when a different unit is
- * removed
- * @throws InvalidSyntaxException
- */
- @Test
- public void testRemoveDifferentUnit() throws InvalidSyntaxException
- {
- testAddDifferentContext();
- reg2 = registerUnit(emf2, "context", TRUE);
- assertContextRegistered("context");
- reg1.unregister();
- assertContextRegistered("context");
- reg2.unregister();
- assertNoContextRegistered();
- }
-
- /**
- * Test that we cope when multiple clients consume the same context
- * @throws InvalidSyntaxException
- */
- @Test
- public void testMultipleClients() throws InvalidSyntaxException
- {
- testContextThenUnit();
-
- mgr.registerContext("unit", client2, new HashMap<String, Object>());
- assertContextRegistered("unit");
-
- mgr.unregisterContext("unit", client1);
- assertContextRegistered("unit");
-
- mgr.unregisterContext("unit", client2);
- assertNoContextRegistered();
- }
-
-
- private ServiceRegistration registerUnit(EntityManagerFactory emf, String name, Boolean managed) {
-
- Hashtable<String, Object> props = new Hashtable<String, Object>();
-
- if(name != null)
- props.put(PersistenceUnitConstants.OSGI_UNIT_NAME, name);
-
- if(managed)
- props.put(PersistenceUnitConstants.CONTAINER_MANAGED_PERSISTENCE_UNIT, managed);
-
- props.put(PersistenceUnitConstants.OSGI_UNIT_PROVIDER, "some.provider.Name");
- props.put(PersistenceUnitConstants.OSGI_UNIT_VERSION, new Version("1.0.0"));
-
- return context.registerService(
- EntityManagerFactory.class.getName(), emf, props);
- }
-
- private void assertNoContextRegistered() throws InvalidSyntaxException {
- ServiceReference[] refs = context.getServiceReferences(EntityManagerFactory.class.getName(), "("+PersistenceContextProvider.PROXY_FACTORY_EMF_ATTRIBUTE+"=*)");
-
- assertNull(refs);
- }
-
- private void assertContextRegistered(String name) throws InvalidSyntaxException {
- BundleContextMock.assertServiceExists(EntityManagerFactory.class.getName());
-
- ServiceReference[] refs = context.getServiceReferences(EntityManagerFactory.class.getName(), "("+PersistenceContextProvider.PROXY_FACTORY_EMF_ATTRIBUTE+"=*)");
-
- assertEquals("Too many EntityManagerFactories", 1, refs.length);
-
- assertEquals("Wrong unit name", name, refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_NAME));
-
- assertEquals("Wrong provider name", "some.provider.Name", refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_PROVIDER));
-
- assertEquals("Wrong unit version", new Version("1.0.0"), refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_VERSION));
-
- assertEquals("Unit should be managed", Boolean.TRUE, refs[0].getProperty(PersistenceUnitConstants.CONTAINER_MANAGED_PERSISTENCE_UNIT));
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.aries.jpa.container.context.impl;
+
+import static java.lang.Boolean.TRUE;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.util.HashMap;
+import java.util.Hashtable;
+
+import javax.persistence.EntityManagerFactory;
+
+import org.apache.aries.jpa.container.PersistenceUnitConstants;
+import org.apache.aries.jpa.container.context.PersistenceContextProvider;
+import org.apache.aries.mocks.BundleContextMock;
+import org.apache.aries.mocks.BundleMock;
+import org.apache.aries.unittest.mocks.Skeleton;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+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.Version;
+
+
+public class PersistenceContextManagerTest {
+
+ private BundleContext context;
+ private PersistenceContextManager mgr;
+
+ private EntityManagerFactory emf1;
+ private EntityManagerFactory emf2;
+
+ private ServiceRegistration reg1;
+ private ServiceRegistration reg2;
+
+ private Bundle client1;
+ private Bundle client2;
+
+ @Before
+ public void setUp()
+ {
+ client1 = Skeleton.newMock(Bundle.class);
+ client2 = Skeleton.newMock(Bundle.class);
+ emf1 = Skeleton.newMock(EntityManagerFactory.class);
+ emf2 = Skeleton.newMock(EntityManagerFactory.class);
+ context = Skeleton.newMock(new BundleMock("system.bundle", new Hashtable<Object, Object>()), Bundle.class).getBundleContext();
+ mgr = new PersistenceContextManager(context, null);
+ mgr.open();
+ }
+
+ @After
+ public void tearDown()
+ {
+ BundleContextMock.clear();
+ }
+
+ /**
+ * A simple test to show we get a service registered when a unit
+ * is registered first.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testUnitThenContext() throws InvalidSyntaxException
+ {
+ String unitName = "unit";
+
+ reg1 = registerUnit(emf1, unitName, TRUE);
+
+ assertNoContextRegistered();
+
+ mgr.registerContext(unitName, client1, new HashMap<String, Object>());
+
+ assertContextRegistered(unitName);
+ }
+
+ /**
+ * A simple test to show we get a service unregistered when a context
+ * is removed.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testUnitThenContextThenRemoveContext() throws InvalidSyntaxException
+ {
+ testUnitThenContext();
+ mgr.unregisterContext("unit", client1);
+
+ assertNoContextRegistered();
+ }
+
+ /**
+ * A simple test to show we get a service unregistered when a unit
+ * is removed.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testUnitThenContextThenRemoveUnit() throws InvalidSyntaxException
+ {
+ testUnitThenContext();
+ reg1.unregister();
+
+ assertNoContextRegistered();
+ }
+
+ /**
+ * A simple test to show we get a service registered when a context
+ * is registered first.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testContextThenUnit() throws InvalidSyntaxException
+ {
+ String unitName = "unit";
+
+ mgr.registerContext(unitName, client1, new HashMap<String, Object>());
+
+ assertNoContextRegistered();
+
+ reg1 = registerUnit(emf1, unitName, TRUE);
+
+ assertContextRegistered(unitName);
+ }
+
+ /**
+ * A simple test to show we get a service unregistered when a context
+ * is removed.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testContextThenUnitThenRemoveContext() throws InvalidSyntaxException
+ {
+ testContextThenUnit();
+ mgr.unregisterContext("unit", client1);
+
+ assertNoContextRegistered();
+ }
+
+ /**
+ * A simple test to show we get a service unregistered when a unit
+ * is removed.
+ *
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testContextThenUnitThenRemoveUnit() throws InvalidSyntaxException
+ {
+ testContextThenUnit();
+ reg1.unregister();
+
+ assertNoContextRegistered();
+ }
+
+ /**
+ * Test that we don't register a service when the unit and
+ * context don't match
+ */
+ @Test
+ public void testAddDifferentContext() throws InvalidSyntaxException
+ {
+ reg1 = registerUnit(emf1, "unit", TRUE);
+
+ assertNoContextRegistered();
+
+ mgr.registerContext("context", client1, new HashMap<String, Object>());
+
+ assertNoContextRegistered();
+ }
+
+ /**
+ * Test that we don't unregister a service when a different context is
+ * removed
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testRemoveDifferentContext() throws InvalidSyntaxException
+ {
+ testAddDifferentContext();
+
+ mgr.registerContext("unit", client1, new HashMap<String, Object>());
+
+ assertContextRegistered("unit");
+
+ mgr.unregisterContext("context", client1);
+
+ assertContextRegistered("unit");
+ }
+
+ /**
+ * Test that we don't unregister a service when a different unit is
+ * removed
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testRemoveDifferentUnit() throws InvalidSyntaxException
+ {
+ testAddDifferentContext();
+ reg2 = registerUnit(emf2, "context", TRUE);
+ assertContextRegistered("context");
+ reg1.unregister();
+ assertContextRegistered("context");
+ reg2.unregister();
+ assertNoContextRegistered();
+ }
+
+ /**
+ * Test that we cope when multiple clients consume the same context
+ * @throws InvalidSyntaxException
+ */
+ @Test
+ public void testMultipleClients() throws InvalidSyntaxException
+ {
+ testContextThenUnit();
+
+ mgr.registerContext("unit", client2, new HashMap<String, Object>());
+ assertContextRegistered("unit");
+
+ mgr.unregisterContext("unit", client1);
+ assertContextRegistered("unit");
+
+ mgr.unregisterContext("unit", client2);
+ assertNoContextRegistered();
+ }
+
+
+ private ServiceRegistration registerUnit(EntityManagerFactory emf, String name, Boolean managed) {
+
+ Hashtable<String, Object> props = new Hashtable<String, Object>();
+
+ if(name != null)
+ props.put(PersistenceUnitConstants.OSGI_UNIT_NAME, name);
+
+ if(managed)
+ props.put(PersistenceUnitConstants.CONTAINER_MANAGED_PERSISTENCE_UNIT, managed);
+
+ props.put(PersistenceUnitConstants.OSGI_UNIT_PROVIDER, "some.provider.Name");
+ props.put(PersistenceUnitConstants.OSGI_UNIT_VERSION, new Version("1.0.0"));
+
+ return context.registerService(
+ EntityManagerFactory.class.getName(), emf, props);
+ }
+
+ private void assertNoContextRegistered() throws InvalidSyntaxException {
+ ServiceReference[] refs = context.getServiceReferences(EntityManagerFactory.class.getName(), "("+PersistenceContextProvider.PROXY_FACTORY_EMF_ATTRIBUTE+"=*)");
+
+ assertNull(refs);
+ }
+
+ private void assertContextRegistered(String name) throws InvalidSyntaxException {
+ BundleContextMock.assertServiceExists(EntityManagerFactory.class.getName());
+
+ ServiceReference[] refs = context.getServiceReferences(EntityManagerFactory.class.getName(), "("+PersistenceContextProvider.PROXY_FACTORY_EMF_ATTRIBUTE+"=*)");
+
+ assertEquals("Too many EntityManagerFactories", 1, refs.length);
+
+ assertEquals("Wrong unit name", name, refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_NAME));
+
+ assertEquals("Wrong provider name", "some.provider.Name", refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_PROVIDER));
+
+ assertEquals("Wrong unit version", new Version("1.0.0"), refs[0].getProperty(PersistenceUnitConstants.OSGI_UNIT_VERSION));
+
+ assertEquals("Unit should be managed", Boolean.TRUE, refs[0].getProperty(PersistenceUnitConstants.CONTAINER_MANAGED_PERSISTENCE_UNIT));
+ }
+}
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/impl/PersistenceContextManagerTest.java
------------------------------------------------------------------------------
svn:mime-type = text/plain
Modified: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java
URL: http://svn.apache.org/viewvc/incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java?rev=955102&r1=955101&r2=955102&view=diff
==============================================================================
--- incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java (original)
+++ incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java Wed Jun 16 00:52:45 2010
@@ -1,258 +1,258 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-package org.apache.aries.jpa.container.context.transaction.impl;
-
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.TransactionRequiredException;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-import javax.transaction.TransactionSynchronizationRegistry;
-
-import org.apache.aries.unittest.mocks.MethodCall;
-import org.apache.aries.unittest.mocks.Skeleton;
-import org.junit.Before;
-import org.junit.Test;
-
-public class JTAPersistenceContextRegistryTest {
-
- private static class TranSyncRegistryMock
- {
- private String key;
-
- private Map<String, List<Synchronization>> syncs = new HashMap<String, List<Synchronization>>();
-
- private Map<String, Map<Object,Object>> resources = new HashMap<String, Map<Object,Object>>();
-
- public void setTransactionKey(String s)
- {
- key = s;
- }
-
- public Object getTransactionKey() {
- return key;
- }
-
- public void registerInterposedSynchronization(Synchronization arg0) {
- List<Synchronization> list = syncs.get(key);
- if(list == null) {
- list = new ArrayList<Synchronization>();
- syncs.put(key, list);
- }
- list.add(arg0);
- }
-
- public Object getResource(Object o) {
- Object toReturn = null;
- Map<Object, Object> map = resources.get(key);
- if(map != null)
- toReturn = map.get(o);
- return toReturn;
- }
-
- public void putResource(Object resourceKey, Object value) {
- Map<Object, Object> map = resources.get(key);
- if(map == null) {
- map = new HashMap<Object, Object>();
- resources.put(key, map);
- }
- map.put(resourceKey, value);
- }
-
-
- public void afterCompletion(String s)
- {
- for(Synchronization sync : syncs.get(s))
- sync.afterCompletion(Status.STATUS_COMMITTED);
-
- resources.remove(s);
- }
- }
-
- private TranSyncRegistryMock reg;
-
- private EntityManagerFactory emf1;
- private Map<Object,Object> props1;
- private EntityManagerFactory emf2;
- private Map<Object,Object> props2;
-
- private JTAPersistenceContextRegistry contexts;
-
- @Before
- public void setup()
- {
- reg = new TranSyncRegistryMock();
-
- props1 = new HashMap<Object, Object>();
- props1.put("prop1", "value1");
-
- props2 = new HashMap<Object, Object>();
- props2.put("prop2", "value2");
-
- emf1 = Skeleton.newMock(EntityManagerFactory.class);
-
- Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
- "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
- Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
- "createEntityManager", props2), Skeleton.newMock(EntityManager.class));
-
- emf2 = Skeleton.newMock(EntityManagerFactory.class);
-
- Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
- "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
- Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
- "createEntityManager", props2), Skeleton.newMock(EntityManager.class));
-
-
- contexts = new JTAPersistenceContextRegistry();
- contexts.setTranRegistry(Skeleton.newMock(reg, TransactionSynchronizationRegistry.class));
- contexts.addRegistry(null);
- }
-
- @Test
- public void testIsTranActive()
- {
- reg.setTransactionKey(null);
-
- assertFalse(contexts.isTransactionActive());
-
- reg.setTransactionKey("");
-
- assertTrue(contexts.isTransactionActive());
- }
-
- @Test
- public void testMultiGetsOneTran()
- {
- reg.setTransactionKey("");
-
- EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1);
- EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props1);
-
- Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
- Skeleton.getSkeleton(emf1).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
- Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- assertSame("We should get the same delegate!", em1a, em1b);
-
- EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1);
- EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props1);
-
- Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
- Skeleton.getSkeleton(emf2).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
- Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- assertSame("We should get the same delegate!", em2a, em2b);
-
- reg.afterCompletion("");
-
- Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
- Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
- }
-
- @Test
- public void testMultiGetsMultiTrans()
- {
- reg.setTransactionKey("a");
- EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1);
- reg.setTransactionKey("b");
- EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props2);
-
- Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
- Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);
-
- assertNotSame("We should not get the same delegate!", em1a, em1b);
-
- Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- Skeleton.getSkeleton(em1b).assertNotCalled(new MethodCall(EntityManager.class, "close"));
-
- reg.setTransactionKey("a");
- EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1);
- reg.setTransactionKey("b");
- EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props2);
-
- Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
- Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);
-
- assertNotSame("We should get the same delegate!", em2a, em2b);
-
- Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- Skeleton.getSkeleton(em2b).assertNotCalled(new MethodCall(EntityManager.class, "close"));
-
- reg.setTransactionKey("b");
- reg.afterCompletion("b");
-
- Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
- Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
- Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
-
- reg.setTransactionKey("a");
- reg.afterCompletion("a");
-
- Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
- Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
- Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
- Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
- }
-
- @Test
- public void testNoTranSyncRegistry() {
- JTAPersistenceContextRegistry registry = new JTAPersistenceContextRegistry();
- //blueprint will still call our setter
- TransactionSynchronizationRegistry tranSyncReg = Skeleton.newMock(reg, TransactionSynchronizationRegistry.class);
- registry.setTranRegistry(tranSyncReg);
-
- reg.setTransactionKey(null);
-
- assertFalse(registry.jtaIntegrationAvailable());
- assertFalse(registry.isTransactionActive());
-
- Skeleton.getSkeleton(tranSyncReg).assertSkeletonNotCalled();
-
- reg.setTransactionKey("");
-
- assertFalse(registry.jtaIntegrationAvailable());
- assertFalse(registry.isTransactionActive());
-
- Skeleton.getSkeleton(tranSyncReg).assertSkeletonNotCalled();
- }
-
- @Test(expected=TransactionRequiredException.class)
- public void testGetNoTran() {
- reg.setTransactionKey(null);
- contexts.getCurrentPersistenceContext(emf1, props1);
- }
-
- @Test(expected=TransactionRequiredException.class)
- public void testGetNoTranSyncRegistry() {
- reg.setTransactionKey("");
- contexts.removeRegistry(null);
- contexts.getCurrentPersistenceContext(emf1, props1);
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.aries.jpa.container.context.transaction.impl;
+
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.TransactionRequiredException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.TransactionSynchronizationRegistry;
+
+import org.apache.aries.unittest.mocks.MethodCall;
+import org.apache.aries.unittest.mocks.Skeleton;
+import org.junit.Before;
+import org.junit.Test;
+
+public class JTAPersistenceContextRegistryTest {
+
+ private static class TranSyncRegistryMock
+ {
+ private String key;
+
+ private Map<String, List<Synchronization>> syncs = new HashMap<String, List<Synchronization>>();
+
+ private Map<String, Map<Object,Object>> resources = new HashMap<String, Map<Object,Object>>();
+
+ public void setTransactionKey(String s)
+ {
+ key = s;
+ }
+
+ public Object getTransactionKey() {
+ return key;
+ }
+
+ public void registerInterposedSynchronization(Synchronization arg0) {
+ List<Synchronization> list = syncs.get(key);
+ if(list == null) {
+ list = new ArrayList<Synchronization>();
+ syncs.put(key, list);
+ }
+ list.add(arg0);
+ }
+
+ public Object getResource(Object o) {
+ Object toReturn = null;
+ Map<Object, Object> map = resources.get(key);
+ if(map != null)
+ toReturn = map.get(o);
+ return toReturn;
+ }
+
+ public void putResource(Object resourceKey, Object value) {
+ Map<Object, Object> map = resources.get(key);
+ if(map == null) {
+ map = new HashMap<Object, Object>();
+ resources.put(key, map);
+ }
+ map.put(resourceKey, value);
+ }
+
+
+ public void afterCompletion(String s)
+ {
+ for(Synchronization sync : syncs.get(s))
+ sync.afterCompletion(Status.STATUS_COMMITTED);
+
+ resources.remove(s);
+ }
+ }
+
+ private TranSyncRegistryMock reg;
+
+ private EntityManagerFactory emf1;
+ private Map<Object,Object> props1;
+ private EntityManagerFactory emf2;
+ private Map<Object,Object> props2;
+
+ private JTAPersistenceContextRegistry contexts;
+
+ @Before
+ public void setup()
+ {
+ reg = new TranSyncRegistryMock();
+
+ props1 = new HashMap<Object, Object>();
+ props1.put("prop1", "value1");
+
+ props2 = new HashMap<Object, Object>();
+ props2.put("prop2", "value2");
+
+ emf1 = Skeleton.newMock(EntityManagerFactory.class);
+
+ Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
+ "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
+ Skeleton.getSkeleton(emf1).setReturnValue(new MethodCall(EntityManagerFactory.class,
+ "createEntityManager", props2), Skeleton.newMock(EntityManager.class));
+
+ emf2 = Skeleton.newMock(EntityManagerFactory.class);
+
+ Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
+ "createEntityManager", props1), Skeleton.newMock(EntityManager.class));
+ Skeleton.getSkeleton(emf2).setReturnValue(new MethodCall(EntityManagerFactory.class,
+ "createEntityManager", props2), Skeleton.newMock(EntityManager.class));
+
+
+ contexts = new JTAPersistenceContextRegistry();
+ contexts.setTranRegistry(Skeleton.newMock(reg, TransactionSynchronizationRegistry.class));
+ contexts.addRegistry(null);
+ }
+
+ @Test
+ public void testIsTranActive()
+ {
+ reg.setTransactionKey(null);
+
+ assertFalse(contexts.isTransactionActive());
+
+ reg.setTransactionKey("");
+
+ assertTrue(contexts.isTransactionActive());
+ }
+
+ @Test
+ public void testMultiGetsOneTran()
+ {
+ reg.setTransactionKey("");
+
+ EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1);
+ EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props1);
+
+ Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
+ Skeleton.getSkeleton(emf1).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
+ Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ assertSame("We should get the same delegate!", em1a, em1b);
+
+ EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1);
+ EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props1);
+
+ Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
+ Skeleton.getSkeleton(emf2).assertNotCalled(new MethodCall(EntityManagerFactory.class, "createEntityManager"));
+ Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ assertSame("We should get the same delegate!", em2a, em2b);
+
+ reg.afterCompletion("");
+
+ Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
+ Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"),1);
+ }
+
+ @Test
+ public void testMultiGetsMultiTrans()
+ {
+ reg.setTransactionKey("a");
+ EntityManager em1a = contexts.getCurrentPersistenceContext(emf1, props1);
+ reg.setTransactionKey("b");
+ EntityManager em1b = contexts.getCurrentPersistenceContext(emf1, props2);
+
+ Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
+ Skeleton.getSkeleton(emf1).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);
+
+ assertNotSame("We should not get the same delegate!", em1a, em1b);
+
+ Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ Skeleton.getSkeleton(em1b).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+
+ reg.setTransactionKey("a");
+ EntityManager em2a = contexts.getCurrentPersistenceContext(emf2, props1);
+ reg.setTransactionKey("b");
+ EntityManager em2b = contexts.getCurrentPersistenceContext(emf2, props2);
+
+ Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props1), 1);
+ Skeleton.getSkeleton(emf2).assertCalledExactNumberOfTimes(new MethodCall(EntityManagerFactory.class, "createEntityManager", props2), 1);
+
+ assertNotSame("We should get the same delegate!", em2a, em2b);
+
+ Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ Skeleton.getSkeleton(em2b).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+
+ reg.setTransactionKey("b");
+ reg.afterCompletion("b");
+
+ Skeleton.getSkeleton(em1a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+ Skeleton.getSkeleton(em2a).assertNotCalled(new MethodCall(EntityManager.class, "close"));
+ Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+
+ reg.setTransactionKey("a");
+ reg.afterCompletion("a");
+
+ Skeleton.getSkeleton(em1a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+ Skeleton.getSkeleton(em1b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+ Skeleton.getSkeleton(em2a).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+ Skeleton.getSkeleton(em2b).assertCalledExactNumberOfTimes(new MethodCall(EntityManager.class, "close"), 1);
+ }
+
+ @Test
+ public void testNoTranSyncRegistry() {
+ JTAPersistenceContextRegistry registry = new JTAPersistenceContextRegistry();
+ //blueprint will still call our setter
+ TransactionSynchronizationRegistry tranSyncReg = Skeleton.newMock(reg, TransactionSynchronizationRegistry.class);
+ registry.setTranRegistry(tranSyncReg);
+
+ reg.setTransactionKey(null);
+
+ assertFalse(registry.jtaIntegrationAvailable());
+ assertFalse(registry.isTransactionActive());
+
+ Skeleton.getSkeleton(tranSyncReg).assertSkeletonNotCalled();
+
+ reg.setTransactionKey("");
+
+ assertFalse(registry.jtaIntegrationAvailable());
+ assertFalse(registry.isTransactionActive());
+
+ Skeleton.getSkeleton(tranSyncReg).assertSkeletonNotCalled();
+ }
+
+ @Test(expected=TransactionRequiredException.class)
+ public void testGetNoTran() {
+ reg.setTransactionKey(null);
+ contexts.getCurrentPersistenceContext(emf1, props1);
+ }
+
+ @Test(expected=TransactionRequiredException.class)
+ public void testGetNoTranSyncRegistry() {
+ reg.setTransactionKey("");
+ contexts.removeRegistry(null);
+ contexts.getCurrentPersistenceContext(emf1, props1);
+ }
+
+}
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java
------------------------------------------------------------------------------
svn:eol-style = native
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java
------------------------------------------------------------------------------
svn:keywords = Date Revision
Propchange: incubator/aries/trunk/jpa/jpa-container-context/src/test/java/org/apache/aries/jpa/container/context/transaction/impl/JTAPersistenceContextRegistryTest.java
------------------------------------------------------------------------------
svn:mime-type = text/plain