tomee-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From andygumbre...@apache.org
Subject svn commit: r1508847 - in /tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb: ./ assembler/classic/ client/ core/ osgi/client/
Date Wed, 31 Jul 2013 13:20:49 GMT
Author: andygumbrecht
Date: Wed Jul 31 13:20:49 2013
New Revision: 1508847

URL: http://svn.apache.org/r1508847
Log:
Make LocalInitialContextFactory thread safe - Creating a new LocalInitialContext could/would
result in a NullPointerException on getRoot() after a destroy due to race condition.
Finals.

Modified:
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/ClientInjections.java
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/OpenEJB.java
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/client/LocalInitialContextFactory.java
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/core/LocalInitialContextFactory.java
    tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/osgi/client/LocalInitialContextFactory.java

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/ClientInjections.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/ClientInjections.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/ClientInjections.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/ClientInjections.java
Wed Jul 31 13:20:49 2013
@@ -25,19 +25,21 @@ import javax.naming.NamingException;
 import java.util.List;
 
 public final class ClientInjections {
+
     private ClientInjections() {
         // no-op
     }
 
+    @SuppressWarnings("unchecked")
     public static InjectionProcessor<?> clientInjector(final Object object) throws
OpenEJBException {
         if (object == null) {
             throw new NullPointerException("Object supplied to 'inject' operation is null");
         }
 
-        Context clients;
+        final Context clients;
         try {
             clients = (Context) SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext()
-                    .lookup("openejb/client/");
+                                              .lookup("openejb/client/");
         } catch (NamingException e) {
             throw new OpenEJBException(object.getClass().getName(), e);
         }
@@ -48,7 +50,7 @@ public final class ClientInjections {
         Class<?> current = object.getClass();
         while (current != null && !current.equals(Object.class)) {
             try {
-                String moduleId = (String) clients.lookup(current.getName());
+                final String moduleId = (String) clients.lookup(current.getName());
                 ctx = (Context) clients.lookup(moduleId);
                 injections = (List<Injection>) ctx.lookup("info/injections");
                 break;
@@ -59,10 +61,10 @@ public final class ClientInjections {
 
         if (injections == null) {
             throw new OpenEJBException("Unable to find injection meta-data for "
-                    + object.getClass().getName()
-                    + ".  Ensure that class was annotated with @"
-                    + LocalClient.class.getName()+" and was successfully discovered and deployed.
"
-                    + " See http://openejb.apache.org/3.0/local-client-injection.html");
+                                       + object.getClass().getName()
+                                       + ".  Ensure that class was annotated with @"
+                                       + LocalClient.class.getName() + " and was successfully
discovered and deployed. "
+                                       + " See http://openejb.apache.org/3.0/local-client-injection.html");
         }
 
         return new InjectionProcessor(object, injections, ctx);

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/OpenEJB.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/OpenEJB.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/OpenEJB.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/OpenEJB.java
Wed Jul 31 13:20:49 2013
@@ -16,11 +16,6 @@
  */
 package org.apache.openejb;
 
-import java.util.Date;
-import java.util.Properties;
-
-import javax.transaction.TransactionManager;
-
 import org.apache.openejb.assembler.classic.DeploymentExceptionManager;
 import org.apache.openejb.cdi.CdiBuilder;
 import org.apache.openejb.loader.SystemInstance;
@@ -35,6 +30,10 @@ import org.apache.openejb.util.OpenEjbVe
 import org.apache.openejb.util.OptionsLog;
 import org.apache.openejb.util.SafeToolkit;
 
+import javax.transaction.TransactionManager;
+import java.util.Date;
+import java.util.Properties;
+
 /**
  * @version $Rev$ $Date$
  */
@@ -49,30 +48,31 @@ public final class OpenEJB {
         return SystemInstance.get().getComponent(ApplicationServer.class);
     }
 
-    public static TransactionManager getTransactionManager(){
+    public static TransactionManager getTransactionManager() {
         return SystemInstance.get().getComponent(TransactionManager.class);
     }
 
     public static class Instance {
-        private static Messages messages = new Messages("org.apache.openejb.util.resources");
+
+        private static final Messages messages = new Messages("org.apache.openejb.util.resources");
         private final Throwable initialized;
 
         /**
          * 1 usage
          * org.apache.openejb.core.ivm.naming.InitContextFactory
          */
-        public Instance(Properties props) throws OpenEJBException {
+        public Instance(final Properties props) throws OpenEJBException {
             this(props, new org.apache.openejb.core.ServerFederation());
         }
 
         /**
          * 2 usages
          */
-        public Instance(Properties initProps, ApplicationServer appServer) throws OpenEJBException
{
+        public Instance(final Properties initProps, final ApplicationServer appServer) throws
OpenEJBException {
             if (appServer == null) {
                 throw new IllegalArgumentException("appServer must not be null");
             }
-            initialized = new InitializationException("Initialized at "+new Date()).fillInStackTrace();
+            initialized = new InitializationException("Initialized at " + new Date()).fillInStackTrace();
 
             try {
                 SystemInstance.init(initProps);
@@ -84,7 +84,7 @@ public final class OpenEJB {
             } catch (Exception e) {
                 throw new OpenEJBException(e);
             }
-            SystemInstance system = SystemInstance.get();
+            final SystemInstance system = SystemInstance.get();
 
             final Logger logger = Logger.getInstance(LogCategory.OPENEJB_STARTUP, "org.apache.openejb.util.resources");
 
@@ -92,15 +92,16 @@ public final class OpenEJB {
 
             system.setComponent(ApplicationServer.class, appServer);
 
-            OpenEjbVersion versionInfo = OpenEjbVersion.get();
+            final OpenEjbVersion versionInfo = OpenEjbVersion.get();
             if (!system.getOptions().get("openejb.nobanner", true)) {
+                //noinspection UseOfSystemOutOrSystemErr
                 versionInfo.print(System.out);
             }
 
-            Logger logger2 = Logger.getInstance(LogCategory.OPENEJB, "org.apache.openejb.util.resources");
-            final String[] bannerValues = new String[] {
-                    null, versionInfo.getUrl(), new Date().toString(), versionInfo.getCopyright(),
-                    versionInfo.getVersion(), versionInfo.getDate(), versionInfo.getTime(),
null
+            final Logger logger2 = Logger.getInstance(LogCategory.OPENEJB, "org.apache.openejb.util.resources");
+            final String[] bannerValues = new String[]{
+                                                          null, versionInfo.getUrl(), new
Date().toString(), versionInfo.getCopyright(),
+                                                          versionInfo.getVersion(), versionInfo.getDate(),
versionInfo.getTime(), null
             };
             for (int i = 0; i < bannerValues.length; i++) {
                 if (bannerValues[i] == null) {
@@ -116,18 +117,18 @@ public final class OpenEJB {
             //OWB support.  The classloader has to be able to load all OWB components including
the ones supplied by OpenEjb.
             CdiBuilder.initializeOWB(getClass().getClassLoader());
 
-            String className = system.getOptions().get("openejb.assembler", "org.apache.openejb.assembler.classic.Assembler");
+            final String className = system.getOptions().get("openejb.assembler", "org.apache.openejb.assembler.classic.Assembler");
 
             logger.debug("startup.instantiatingAssemblerClass", className);
-            
-            Assembler assembler;
+
+            final Assembler assembler;
             try {
                 assembler = (Assembler) SafeToolkit.getToolkit("OpenEJB").newInstance(className);
             } catch (OpenEJBException oe) {
                 logger.fatal("startup.assemblerCannotBeInstantiated", oe);
                 throw oe;
             } catch (Throwable t) {
-                String msg = messages.message("startup.openejbEncounteredUnexpectedError");
+                final String msg = messages.message("startup.openejbEncounteredUnexpectedError");
                 logger.fatal(msg, t);
                 throw new OpenEJBException(msg, t);
             }
@@ -138,7 +139,7 @@ public final class OpenEJB {
                 logger.fatal("startup.assemblerFailedToInitialize", oe);
                 throw oe;
             } catch (Throwable t) {
-                String msg = messages.message("startup.assemblerEncounteredUnexpectedError");
+                final String msg = messages.message("startup.assemblerEncounteredUnexpectedError");
                 logger.fatal(msg, t);
                 throw new OpenEJBException(msg, t);
             }
@@ -149,14 +150,14 @@ public final class OpenEJB {
                 logger.fatal("startup.assemblerFailedToBuild", oe);
                 throw oe;
             } catch (Throwable t) {
-                String msg = messages.message("startup.assemblerEncounterUnexpectedBuildError");
+                final String msg = messages.message("startup.assemblerEncounterUnexpectedBuildError");
                 logger.fatal(msg, t);
                 throw new OpenEJBException(msg, t);
             }
 
-            ContainerSystem containerSystem = assembler.getContainerSystem();
+            final ContainerSystem containerSystem = assembler.getContainerSystem();
             if (containerSystem == null) {
-                String msg = messages.message("startup.assemblerReturnedNullContainer");
+                final String msg = messages.message("startup.assemblerReturnedNullContainer");
                 logger.fatal(msg);
                 throw new OpenEJBException(msg);
             }
@@ -167,7 +168,7 @@ public final class OpenEJB {
                 logger.debug("startup.debugContainers", containerSystem.containers().length);
 
                 if (containerSystem.containers().length > 0) {
-                    Container[] c = containerSystem.containers();
+                    final Container[] c = containerSystem.containers();
                     logger.debug("startup.debugContainersType");
                     for (int i = 0; i < c.length; i++) {
                         String entry = "   ";
@@ -196,7 +197,7 @@ public final class OpenEJB {
                 logger.debug("startup.debugDeployments", containerSystem.deployments().length);
                 if (containerSystem.deployments().length > 0) {
                     logger.debug("startup.debugDeploymentsType");
-                    BeanContext[] d = containerSystem.deployments();
+                    final BeanContext[] d = containerSystem.deployments();
                     for (int i = 0; i < d.length; i++) {
                         String entry = "   ";
                         switch (d[i].getComponentType()) {
@@ -228,9 +229,9 @@ public final class OpenEJB {
                 }
             }
 
-            SecurityService securityService = assembler.getSecurityService();
+            final SecurityService securityService = assembler.getSecurityService();
             if (securityService == null) {
-                String msg = messages.message("startup.assemblerReturnedNullSecurityService");
+                final String msg = messages.message("startup.assemblerReturnedNullSecurityService");
                 logger.fatal(msg);
                 throw new OpenEJBException(msg);
             } else {
@@ -238,9 +239,9 @@ public final class OpenEJB {
             }
             system.setComponent(SecurityService.class, securityService);
 
-            TransactionManager transactionManager = assembler.getTransactionManager();
+            final TransactionManager transactionManager = assembler.getTransactionManager();
             if (transactionManager == null) {
-                String msg = messages.message("startup.assemblerReturnedNullTransactionManager");
+                final String msg = messages.message("startup.assemblerReturnedNullTransactionManager");
                 logger.fatal(msg);
                 throw new OpenEJBException(msg);
             } else {
@@ -258,9 +259,12 @@ public final class OpenEJB {
     }
 
     public static void destroy() {
-        Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
-        if (assembler != null) assembler.destroy();
-        SystemInstance.reset();
+        final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
+        if (assembler != null) {
+            assembler.destroy();
+        } else {
+            SystemInstance.reset();
+        }
         instance = null;
     }
 
@@ -268,23 +272,23 @@ public final class OpenEJB {
      * 1 usage
      * org.apache.openejb.core.ivm.naming.InitContextFactory
      */
-    public static void init(Properties props) throws OpenEJBException {
+    public static void init(final Properties props) throws OpenEJBException {
         init(props, null);
     }
 
-    private static Messages messages = new Messages("org.apache.openejb.util.resources");
+    private static final Messages messages = new Messages("org.apache.openejb.util.resources");
 
     /**
      * 2 usages
      */
-    public static void init(Properties initProps, ApplicationServer appServer) throws OpenEJBException
{
+    public static void init(final Properties initProps, final ApplicationServer appServer)
throws OpenEJBException {
         if (isInitialized()) {
-            if (instance != null){
-                String msg = messages.message("startup.alreadyInitialized");
+            if (instance != null) {
+                final String msg = messages.message("startup.alreadyInitialized");
                 logger().error(msg, instance.initialized);
                 throw new OpenEJBException(msg, instance.initialized);
             } else {
-                String msg = messages.message("startup.alreadyInitialized");
+                final String msg = messages.message("startup.alreadyInitialized");
                 logger().error(msg);
                 throw new OpenEJBException(msg);
             }
@@ -305,8 +309,8 @@ public final class OpenEJB {
     }
 
     public static class InitializationException extends Exception {
-        public InitializationException(String message)
-        {
+
+        public InitializationException(final String message) {
             super(message);
         }
     }

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
Wed Jul 31 13:20:49 2013
@@ -789,8 +789,8 @@ public class Assembler extends Assembler
             final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo,
appContext, injections, new ArrayList<BeanContext>(), null);
 
             if ("true".equalsIgnoreCase(SystemInstance.get()
-                    .getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
-                            appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
"false")))) {
+                                                      .getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
+                                                                   appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS,
"false")))) {
                 propagateApplicationExceptions(appInfo, classLoader, allDeployments);
             }
 
@@ -1029,11 +1029,11 @@ public class Assembler extends Assembler
                             final MethodContext methodContext = entry.getValue();
                             for (final ScheduleData scheduleData : methodContext.getSchedules())
{
                                 timerStore.createCalendarTimer(timerService,
-                                        (String) beanContext.getDeploymentID(),
-                                        null,
-                                        entry.getKey(),
-                                        scheduleData.getExpression(),
-                                        scheduleData.getConfig());
+                                                               (String) beanContext.getDeploymentID(),
+                                                               null,
+                                                               entry.getKey(),
+                                                               scheduleData.getExpression(),
+                                                               scheduleData.getConfig());
                             }
                         }
                         beanContext.setEjbTimerService(timerService);
@@ -1105,7 +1105,7 @@ public class Assembler extends Assembler
                     if (container.getBeanContext(deployment.getDeploymentID()) == null) {
                         container.deploy(deployment);
                         if (!((String) deployment.getDeploymentID()).endsWith(".Comp")
-                                && !deployment.isHidden()) {
+                            && !deployment.isHidden()) {
                             logger.info("createApplication.createdEjb", deployment.getDeploymentID(),
deployment.getEjbName(), container.getContainerID());
                         }
                         if (logger.isDebugEnabled()) {
@@ -1126,7 +1126,7 @@ public class Assembler extends Assembler
                     final Container container = deployment.getContainer();
                     container.start(deployment);
                     if (!((String) deployment.getDeploymentID()).endsWith(".Comp")
-                            && !deployment.isHidden()) {
+                        && !deployment.isHidden()) {
                         logger.info("createApplication.startedEjb", deployment.getDeploymentID(),
deployment.getEjbName(), container.getContainerID());
                     }
                 } catch (Throwable t) {
@@ -1180,10 +1180,10 @@ public class Assembler extends Assembler
             final MBeanServer server = LocalMBeanServer.get();
             try {
                 final ObjectName leaf = new ObjectNameBuilder("openejb.user.mbeans")
-                        .set("application", id)
-                        .set("group", clazz.getPackage().getName())
-                        .set("name", clazz.getSimpleName())
-                        .build();
+                                            .set("application", id)
+                                            .set("group", clazz.getPackage().getName())
+                                            .set("name", clazz.getSimpleName())
+                                            .build();
 
                 server.registerMBean(new DynamicMBeanWrapper(wc, instance), leaf);
                 appMbeans.put(mbeanClass, leaf.getCanonicalName());
@@ -1422,7 +1422,7 @@ public class Assembler extends Assembler
         } else if (ExecutorService.class.isInstance(object)) {
             ExecutorService.class.cast(object).shutdown();
         } else if (DataSource.class.isInstance(object)) {
-
+            //Do nothing?
         } else if (logger.isDebugEnabled()) {
             logger.debug("Not processing resource on destroy: " + className);
         }
@@ -1675,7 +1675,7 @@ public class Assembler extends Assembler
                 }
             } catch (NamingException e) {
                 undeployException.getCauses().add(new Exception("Unable to prune openejb/Deployments
and openejb/local namespaces, this could cause future deployments to fail.",
-                        e));
+                                                                e));
             }
 
             deployments.clear();
@@ -1771,7 +1771,7 @@ public class Assembler extends Assembler
         }
     }
 
-    private void destroyLookedUpResource(Context globalContext, String id, String name) throws
NamingException {
+    private void destroyLookedUpResource(final Context globalContext, final String id, final
String name) throws NamingException {
         final Object object = globalContext.lookup(name);
         final String clazz;
         if (object == null) { // should it be possible?
@@ -1904,7 +1904,7 @@ public class Assembler extends Assembler
             initialContext = new InitialContext(contextInfo.properties);
         } catch (NamingException ne) {
             throw new OpenEJBException(String.format("JndiProvider(id=\"%s\") could not be
created.  Failed to create the InitialContext using the supplied properties",
-                    contextInfo.id), ne);
+                                                     contextInfo.id), ne);
         }
 
         try {
@@ -2081,8 +2081,10 @@ public class Assembler extends Assembler
                 for (final Map.Entry<Object, Object> entry : p.entrySet()) {
                     final String key = entry.getKey().toString();
                     if (!props.containsKey(key)
-                            // never override from Definition, just use it to complete the
properties set
-                            && !(key.equalsIgnoreCase("url") && props.containsKey("JdbcUrl")))
{ // with @DataSource we can get both, see org.apache.openejb.config.ConvertDataSourceDefinitions.rawDefinition()
+                        // never override from Definition, just use it to complete the properties
set
+                        &&
+                        !(key.equalsIgnoreCase("url") &&
+                          props.containsKey("JdbcUrl"))) { // with @DataSource we can get
both, see org.apache.openejb.config.ConvertDataSourceDefinitions.rawDefinition()
                         props.put(key, entry.getValue());
                     }
                 }
@@ -2136,8 +2138,8 @@ public class Assembler extends Assembler
             final BootstrapContext bootstrapContext;
             if (transactionManager instanceof GeronimoTransactionManager) {
                 bootstrapContext = new GeronimoBootstrapContext((GeronimoWorkManager) workManager,
-                        (GeronimoTransactionManager) transactionManager,
-                        (GeronimoTransactionManager) transactionManager);
+                                                                (GeronimoTransactionManager)
transactionManager,
+                                                                (GeronimoTransactionManager)
transactionManager);
             } else if (transactionManager instanceof XATerminator) {
                 bootstrapContext = new SimpleBootstrapContext(workManager, (XATerminator)
transactionManager);
             } else {
@@ -2200,7 +2202,7 @@ public class Assembler extends Assembler
             // init cm if needed
             final Object eagerInit = unset.remove("eagerInit");
             if (eagerInit != null && eagerInit instanceof String && "true".equalsIgnoreCase((String)
eagerInit)
-                    && connectionManager instanceof AbstractConnectionManager) {
+                && connectionManager instanceof AbstractConnectionManager) {
                 try {
                     ((AbstractConnectionManager) connectionManager).doStart();
                     try {
@@ -2255,7 +2257,7 @@ public class Assembler extends Assembler
             bindResource(alias, service);
         }
         if (serviceInfo.originAppName != null && !serviceInfo.originAppName.isEmpty()
&& !"/".equals(serviceInfo.originAppName)
-                && !serviceInfo.id.startsWith("global")) {
+            && !serviceInfo.id.startsWith("global")) {
             final String baseJndiName = serviceInfo.id.substring(serviceInfo.originAppName.length()
+ 1);
             serviceInfo.aliases.add(baseJndiName);
             final ContextualJndiReference ref = new ContextualJndiReference(baseJndiName);
@@ -2667,14 +2669,14 @@ public class Assembler extends Assembler
         }
 
         public void afterApplicationCreated(
-                @Observes
-                final AssemblerAfterApplicationCreated event) {
+                                               @Observes
+                                               final AssemblerAfterApplicationCreated event)
{
             delegate.afterApplicationCreated(event.getApp());
         }
 
         public void beforeApplicationDestroyed(
-                @Observes
-                final AssemblerBeforeApplicationDestroyed event) {
+                                                  @Observes
+                                                  final AssemblerBeforeApplicationDestroyed
event) {
             delegate.beforeApplicationDestroyed(event.getApp());
         }
 

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/client/LocalInitialContextFactory.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/client/LocalInitialContextFactory.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/client/LocalInitialContextFactory.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/client/LocalInitialContextFactory.java
Wed Jul 31 13:20:49 2013
@@ -20,5 +20,6 @@ package org.apache.openejb.client;
 /**
  * @deprecated use org.apache.openejb.core.LocalInitialContextFactory
  */
+@Deprecated
 public class LocalInitialContextFactory extends org.apache.openejb.core.LocalInitialContextFactory
{
 }

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/core/LocalInitialContextFactory.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/core/LocalInitialContextFactory.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/core/LocalInitialContextFactory.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/core/LocalInitialContextFactory.java
Wed Jul 31 13:20:49 2013
@@ -22,46 +22,73 @@ import org.apache.openejb.util.OptionsLo
 
 import javax.naming.Context;
 import javax.naming.NamingException;
-import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
 import java.util.Hashtable;
 import java.util.Properties;
+import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * @version $Rev$ $Date$
  */
+@SuppressWarnings("UseOfObsoleteCollectionType")
 public class LocalInitialContextFactory implements javax.naming.spi.InitialContextFactory
{
 
-    private static OpenEJBInstance openejb;
+    private static final ReentrantLock lock = new ReentrantLock();
+    private static OpenEJBInstance openejb = null;
 
     private boolean bootedOpenEJB;
 
-    public Context getInitialContext(Hashtable env) throws javax.naming.NamingException {
+    @Override
+    public Context getInitialContext(final Hashtable env) throws javax.naming.NamingException
{
         init(env);
         return getLocalInitialContext(env);
     }
 
-    protected void init(Hashtable env) throws javax.naming.NamingException {
-        if (openejb != null) {
-            return;
-        }
+    protected void init(final Hashtable env) throws javax.naming.NamingException {
+
+        final ReentrantLock l = lock;
+        l.lock();
+
         try {
-            Properties properties = new Properties();
-            properties.putAll(env);
-            init(properties);
-        } catch (Exception e) {
-            throw (NamingException) new NamingException("Attempted to load OpenEJB. " + e.getMessage()).initCause(e);
+            if (openejb != null && openejb.isInitialized()) {
+                return;
+            }
+            try {
+                final Properties properties = new Properties();
+                properties.putAll(env);
+                init(properties);
+            } catch (Exception e) {
+                throw (NamingException) new NamingException("Attempted to load OpenEJB. "
+ e.getMessage()).initCause(e);
+            }
+        } finally {
+            l.unlock();
         }
     }
 
     boolean bootedOpenEJB() {
-        return bootedOpenEJB;
+        final ReentrantLock l = lock;
+        l.lock();
+
+        try {
+            return bootedOpenEJB;
+        } finally {
+            l.unlock();
+        }
+
     }
 
-    public void init(Properties properties) throws Exception {
-        if (openejb != null) return;
+    private void init(final Properties properties) throws Exception {
+        if (openejb != null && openejb.isInitialized()) {
+            return;
+        }
+
         openejb = new OpenEJBInstance();
-        if (openejb.isInitialized()) return;
+
+        if (openejb.isInitialized()) {
+            return;
+        }
+
         bootedOpenEJB = true;
         SystemInstance.init(properties);
         OptionsLog.install();
@@ -69,32 +96,40 @@ public class LocalInitialContextFactory 
         openejb.init(properties);
     }
 
-    public void close(){
-        openejb = null;
+    public void close() {
+        final ReentrantLock l = lock;
+        l.lock();
+
+        try {
+            openejb = null;
+        } finally {
+            l.unlock();
+        }
     }
 
-    private Context getLocalInitialContext(Hashtable env) throws javax.naming.NamingException
{
-        Context context;
+    private Context getLocalInitialContext(final Hashtable env) throws javax.naming.NamingException
{
+        final Context context;
         try {
-            ClassLoader cl = SystemInstance.get().getClassLoader();
+            final ClassLoader cl = SystemInstance.get().getClassLoader();
 
-            Class localInitialContext = Class.forName("org.apache.openejb.core.LocalInitialContext",
true, cl);
+            final Class localInitialContext = Class.forName("org.apache.openejb.core.LocalInitialContext",
true, cl);
 
-            Constructor constructor = localInitialContext.getConstructor(Hashtable.class,
LocalInitialContextFactory.class);
+            //noinspection unchecked
+            final Constructor constructor = localInitialContext.getConstructor(Hashtable.class,
LocalInitialContextFactory.class);
             context = (Context) constructor.newInstance(env, this);
         } catch (Throwable e) {
             if (e instanceof InvocationTargetException) {
-                InvocationTargetException ite = (InvocationTargetException) e;
-                if (ite.getTargetException() != null){
+                final InvocationTargetException ite = (InvocationTargetException) e;
+                if (ite.getTargetException() != null) {
                     e = ite.getTargetException();
                 }
             }
 
-            if (e instanceof NamingException){
+            if (e instanceof NamingException) {
                 throw (NamingException) e;
             }
             throw (NamingException) new javax.naming.NamingException("Cannot instantiate
a LocalInitialContext. Exception: "
-                    + e.getClass().getName() + " " + e.getMessage()).initCause(e);
+                                                                     + e.getClass().getName()
+ " " + e.getMessage()).initCause(e);
         }
 
         return context;

Modified: tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/osgi/client/LocalInitialContextFactory.java
URL: http://svn.apache.org/viewvc/tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/osgi/client/LocalInitialContextFactory.java?rev=1508847&r1=1508846&r2=1508847&view=diff
==============================================================================
--- tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/osgi/client/LocalInitialContextFactory.java
(original)
+++ tomee/tomee/trunk/container/openejb-core/src/main/java/org/apache/openejb/osgi/client/LocalInitialContextFactory.java
Wed Jul 31 13:20:49 2013
@@ -16,18 +16,18 @@
  */
 package org.apache.openejb.osgi.client;
 
-import java.util.Hashtable;
+import org.apache.openejb.core.LocalInitialContext;
 
 import javax.naming.Context;
-
-import org.apache.openejb.core.LocalInitialContext;
+import java.util.Hashtable;
 
 /**
  * @version $Rev$ $Date$
  */
 public class LocalInitialContextFactory extends org.apache.openejb.core.LocalInitialContextFactory
{
 
-    public Context getInitialContext(Hashtable env) throws javax.naming.NamingException {
+    @Override
+    public Context getInitialContext(final Hashtable env) throws javax.naming.NamingException
{
         init(env);
         return new LocalInitialContext(env, this);
     }



Mime
View raw message