You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by an...@apache.org on 2012/12/18 10:02:38 UTC

svn commit: r1423354 - in /openejb/trunk/openejb/container: openejb-core/src/main/java/org/apache/openejb/assembler/classic/ openejb-core/src/main/java/org/apache/openejb/core/managed/ openejb-core/src/main/java/org/apache/openejb/core/stateful/ openej...

Author: andygumbrecht
Date: Tue Dec 18 09:02:34 2012
New Revision: 1423354

URL: http://svn.apache.org/viewvc?rev=1423354&view=rev
Log:
Ensure failed File.delete() calls File.deleteOnExit()
Finals.

Modified:
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/managed/SimplePassivater.java
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/stateful/SimplePassivater.java
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/util/JarExtractor.java
    openejb/trunk/openejb/container/openejb-javaagent/src/main/java/org/apache/openejb/javaagent/Agent.java
    openejb/trunk/openejb/container/openejb-loader/src/main/java/org/apache/openejb/loader/TomcatClassPath.java

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java Tue Dec 18 09:02:34 2012
@@ -294,7 +294,8 @@ public class Assembler extends Assembler
     }
 
     public static void installNaming() {
-        if (SystemInstance.get().hasProperty("openejb.geronimo")) return;
+        if (SystemInstance.get().hasProperty("openejb.geronimo"))
+            return;
 
         /* Add IntraVM JNDI service /////////////////////*/
         installNaming(OPENEJB_URL_PKG_PREFIX);
@@ -535,17 +536,21 @@ public class Assembler extends Assembler
 
     public AppContext createApplication(final AppInfo appInfo, ClassLoader classLoader, final boolean start) throws OpenEJBException, IOException, NamingException {
         // The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places
-        if (appInfo.appId == null) throw new IllegalArgumentException("AppInfo.appId cannot be null");
-        if (appInfo.path == null) appInfo.path = appInfo.appId;
+        if (appInfo.appId == null) {
+            throw new IllegalArgumentException("AppInfo.appId cannot be null");
+        }
+        if (appInfo.path == null) {
+            appInfo.path = appInfo.appId;
+        }
 
         logger.info("createApplication.start", appInfo.path);
 
-//        try {
-//            Thread.sleep(5000);
-//        } catch (InterruptedException e) {
-//            e.printStackTrace();
-//            Thread.interrupted();
-//        }
+        //        try {
+        //            Thread.sleep(5000);
+        //        } catch (InterruptedException e) {
+        //            e.printStackTrace();
+        //            Thread.interrupted();
+        //        }
 
         // To start out, ensure we don't already have any beans deployed with duplicate IDs.  This
         // is a conflict we can't handle.
@@ -818,7 +823,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()) {
@@ -839,7 +844,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) {
@@ -865,7 +870,7 @@ public class Assembler extends Assembler
                 jndiEncBuilder.setUseCrossClassLoaderRef(false);
                 final Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
 
-//                Debug.printContext(context);
+                //                Debug.printContext(context);
 
                 containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context);
 
@@ -937,7 +942,6 @@ public class Assembler extends Assembler
                 }
             }
 
-
             logger.info("createApplication.success", appInfo.path);
 
             deployedApplications.put(appInfo.path, appInfo);
@@ -1001,7 +1005,8 @@ public class Assembler extends Assembler
 
     private void ensureWebBeansContext(final AppContext appContext) {
         WebBeansContext webBeansContext = appContext.get(WebBeansContext.class);
-        if (webBeansContext == null) webBeansContext = appContext.getWebBeansContext();
+        if (webBeansContext == null)
+            webBeansContext = appContext.getWebBeansContext();
         if (webBeansContext == null) {
 
             final Map<Class<?>, Object> services = new HashMap<Class<?>, Object>();
@@ -1338,9 +1343,10 @@ public class Assembler extends Assembler
             }
         }
 
-        if (appContext != null) for (final WebContext webContext : appContext.getWebContexts()) {
-            containerSystem.removeWebContext(webContext);
-        }
+        if (appContext != null)
+            for (final WebContext webContext : appContext.getWebContexts()) {
+                containerSystem.removeWebContext(webContext);
+            }
 
         // Clear out naming for all components first
         for (final BeanContext deployment : deployments) {
@@ -1352,13 +1358,14 @@ public class Assembler extends Assembler
             }
 
             final JndiBuilder.Bindings bindings = deployment.get(JndiBuilder.Bindings.class);
-            if (bindings != null) for (final String name : bindings.getBindings()) {
-                try {
-                    globalContext.unbind(name);
-                } catch (Throwable t) {
-                    undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
+            if (bindings != null)
+                for (final String name : bindings.getBindings()) {
+                    try {
+                        globalContext.unbind(name);
+                    } catch (Throwable t) {
+                        undeployException.getCauses().add(new Exception("bean: " + deploymentID + ": " + t.getMessage(), t));
+                    }
                 }
-            }
         }
 
         for (final String sId : moduleIds) {
@@ -1485,10 +1492,12 @@ public class Assembler extends Assembler
     public ClassLoader createAppClassLoader(final AppInfo appInfo) throws OpenEJBException, IOException {
         final Set<URL> jars = new HashSet<URL>();
         for (final EjbJarInfo info : appInfo.ejbJars) {
-            if (info.path != null) jars.add(toUrl(info.path));
+            if (info.path != null)
+                jars.add(toUrl(info.path));
         }
         for (final ClientInfo info : appInfo.clients) {
-            if (info.path != null) jars.add(toUrl(info.path));
+            if (info.path != null)
+                jars.add(toUrl(info.path));
         }
         for (final ConnectorInfo info : appInfo.connectors) {
             for (final String jarPath : info.libs) {
@@ -1596,7 +1605,7 @@ public class Assembler extends Assembler
 
         logger.getChildLogger("service").debug("createService.success", serviceInfo.service, serviceInfo.id, serviceInfo.className);
 
-        if (service instanceof Container && LocalMBeanServer.isJMXActive()) {
+        if (Container.class.isInstance(service) && LocalMBeanServer.isJMXActive()) {
             final ObjectName objectName = ObjectNameBuilder.uniqueName("containers", serviceInfo.id, service);
             try {
                 LocalMBeanServer.get().registerMBean(new DynamicMBeanWrapper(new JMXContainer(serviceInfo, (Container) service)), objectName);
@@ -1723,7 +1732,7 @@ 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()
+                        && !(key.equalsIgnoreCase("url") && props.containsKey("JdbcUrl"))) { // with @DataSource we can get both, see org.apache.openejb.config.ConvertDataSourceDefinitions.rawDefinition()
                         props.put(key, entry.getValue());
                     }
                 }
@@ -1772,7 +1781,6 @@ public class Assembler extends Assembler
                 workManager = new SimpleWorkManager(threadPool);
             }
 
-
             // BootstrapContext: wraps the WorkMananger and XATerminator
             final BootstrapContext bootstrapContext;
             if (transactionManager instanceof GeronimoTransactionManager) {
@@ -1808,8 +1816,10 @@ public class Assembler extends Assembler
             // standard properties
             connectionManagerRecipe.setProperty("transactionManager", transactionManager);
             ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
-            if (classLoader == null) classLoader = getClass().getClassLoader();
-            if (classLoader == null) classLoader = ClassLoader.getSystemClassLoader();
+            if (classLoader == null)
+                classLoader = getClass().getClassLoader();
+            if (classLoader == null)
+                classLoader = ClassLoader.getSystemClassLoader();
             connectionManagerRecipe.setProperty("classLoader", classLoader);
 
             logger.getChildLogger("service").info("createResource.createConnectionManager", serviceInfo.id, service.getClass().getName());
@@ -1824,7 +1834,8 @@ public class Assembler extends Assembler
             final Map<String, Object> unsetB = connectionManagerRecipe.getUnsetProperties();
             final Map<String, Object> unset = new HashMap<String, Object>();
             for (final Map.Entry<String, Object> entry : unsetA.entrySet()) {
-                if (unsetB.containsKey(entry.getKey())) unset.put(entry.getKey(), entry.getValue());
+                if (unsetB.containsKey(entry.getKey()))
+                    unset.put(entry.getKey(), entry.getValue());
             }
             logUnusedProperties(unset, serviceInfo);
 
@@ -1862,7 +1873,7 @@ public class Assembler extends Assembler
         }
 
         bindResource(serviceInfo.id, service);
-        for (String alias : serviceInfo.aliases) {
+        for (final String alias : serviceInfo.aliases) {
             bindResource(alias, service);
         }
 
@@ -2050,7 +2061,6 @@ public class Assembler extends Assembler
             throw new OpenEJBException("Cannot bind java:comp/TransactionSynchronizationRegistry", e);
         }
 
-
         // JtaEntityManagerRegistry
         // todo this should be built
         final JtaEntityManagerRegistry jtaEntityManagerRegistry = new JtaEntityManagerRegistry(synchronizationRegistry);
@@ -2068,18 +2078,27 @@ public class Assembler extends Assembler
     private static void logUnusedProperties(final Map<String, Object> unsetProperties, final ServiceInfo info) {
         for (final String property : unsetProperties.keySet()) {
             //TODO: DMB: Make more robust later
-            if (property.equalsIgnoreCase("JndiName")) return;
-            if (property.equalsIgnoreCase("Origin")) return;
-            if (property.equalsIgnoreCase("DatabaseName")) return;
-            if (property.equalsIgnoreCase("connectionAttributes")) return;
-
-            if (property.equalsIgnoreCase("properties")) return;
-            if (property.equalsIgnoreCase("ApplicationWide")) return;
-            if (property.equalsIgnoreCase("transactionManager")) return;
-            if (info.types.contains("javax.mail.Session")) return;
+            if (property.equalsIgnoreCase("JndiName"))
+                return;
+            if (property.equalsIgnoreCase("Origin"))
+                return;
+            if (property.equalsIgnoreCase("DatabaseName"))
+                return;
+            if (property.equalsIgnoreCase("connectionAttributes"))
+                return;
+
+            if (property.equalsIgnoreCase("properties"))
+                return;
+            if (property.equalsIgnoreCase("ApplicationWide"))
+                return;
+            if (property.equalsIgnoreCase("transactionManager"))
+                return;
+            if (info.types.contains("javax.mail.Session"))
+                return;
             //---
 
-            if (info.types.isEmpty() && "class".equalsIgnoreCase(property)) continue; // inline service (no sp)
+            if (info.types.isEmpty() && "class".equalsIgnoreCase(property))
+                continue; // inline service (no sp)
 
             logger.getChildLogger("service").warning("unusedProperty", property, info.id);
         }
@@ -2099,7 +2118,7 @@ public class Assembler extends Assembler
         if (info instanceof ResourceInfo) {
             final List<String> aliasesList = ((ResourceInfo) info).aliases;
             if (!aliasesList.isEmpty()) {
-                String aliases = Join.join(", ", aliasesList);
+                final String aliases = Join.join(", ", aliasesList);
                 serviceLogger.info("createServiceWithAliases", info.service, info.id, aliases);
             } else {
                 serviceLogger.info("createService", info.service, info.id);
@@ -2133,6 +2152,7 @@ public class Assembler extends Assembler
     }
 
     private static class PersistenceClassLoaderHandlerImpl implements PersistenceClassLoaderHandler {
+
         private static boolean logged = false;
 
         private final Map<String, List<ClassFileTransformer>> transformers = new TreeMap<String, List<ClassFileTransformer>>();
@@ -2182,6 +2202,7 @@ public class Assembler extends Assembler
     // Which is freely licensed as follows.
     // "Use, modify, and redistribute this code in any way without acknowledgement"
     private static class ResourceAdapterThreadFactory implements ThreadFactory {
+
         private final ThreadGroup group;
         private final String namePrefix;
         private final AtomicInteger threadNumber = new AtomicInteger(1);
@@ -2200,24 +2221,31 @@ public class Assembler extends Assembler
         @Override
         public Thread newThread(final Runnable runnable) {
             final Thread thread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0);
-            if (!thread.isDaemon()) thread.setDaemon(true);
-            if (thread.getPriority() != Thread.NORM_PRIORITY) thread.setPriority(Thread.NORM_PRIORITY);
+            if (!thread.isDaemon())
+                thread.setDaemon(true);
+            if (thread.getPriority() != Thread.NORM_PRIORITY)
+                thread.setPriority(Thread.NORM_PRIORITY);
             return thread;
         }
     }
 
     public static class DeploymentListenerObserver {
+
         private final DeploymentListener delegate;
 
         public DeploymentListenerObserver(final DeploymentListener deploymentListener) {
             delegate = deploymentListener;
         }
 
-        public void afterApplicationCreated(@Observes final AssemblerAfterApplicationCreated event) {
+        public void afterApplicationCreated(
+                @Observes
+                final AssemblerAfterApplicationCreated event) {
             delegate.afterApplicationCreated(event.getApp());
         }
 
-        public void beforeApplicationDestroyed(@Observes final AssemblerBeforeApplicationDestroyed event) {
+        public void beforeApplicationDestroyed(
+                @Observes
+                final AssemblerBeforeApplicationDestroyed event) {
             delegate.beforeApplicationDestroyed(event.getApp());
         }
 

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/managed/SimplePassivater.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/managed/SimplePassivater.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/managed/SimplePassivater.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/managed/SimplePassivater.java Tue Dec 18 09:02:34 2012
@@ -16,12 +16,6 @@
  */
 package org.apache.openejb.core.managed;
 
-import java.io.File;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.Map;
-import java.util.Properties;
-
 import org.apache.openejb.SystemException;
 import org.apache.openejb.core.EnvProps;
 import org.apache.openejb.loader.IO;
@@ -29,8 +23,14 @@ import org.apache.openejb.loader.SystemI
 import org.apache.openejb.util.LogCategory;
 import org.apache.openejb.util.Logger;
 
+import java.io.File;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Map;
+import java.util.Properties;
 
 public class SimplePassivater implements PassivationStrategy {
+
     private static final Logger logger = Logger.getInstance(LogCategory.OPENEJB, "org.apache.openejb.util.resources");
     private File sessionDirectory;
 
@@ -38,12 +38,13 @@ public class SimplePassivater implements
         init(null);
     }
 
+    @Override
     public void init(Properties props) throws SystemException {
         if (props == null) {
             props = new Properties();
         }
 
-        String dir = props.getProperty(EnvProps.IM_PASSIVATOR_PATH_PREFIX);
+        final String dir = props.getProperty(EnvProps.IM_PASSIVATOR_PATH_PREFIX);
 
         try {
             if (dir != null) {
@@ -57,14 +58,14 @@ public class SimplePassivater implements
         }
     }
 
-    public void passivate(Object primaryKey, Object state) throws SystemException {
+    public void passivate(final Object primaryKey, final Object state) throws SystemException {
         try {
-            String filename = primaryKey.toString().replace(':', '=');
+            final String filename = primaryKey.toString().replace(':', '=');
 
-            File sessionFile = new File(sessionDirectory, filename);
+            final File sessionFile = new File(sessionDirectory, filename);
 
             logger.info("Passivating to file " + sessionFile);
-            ObjectOutputStream oos = new ObjectOutputStream(IO.write(sessionFile));
+            final ObjectOutputStream oos = new ObjectOutputStream(IO.write(sessionFile));
 
             oos.writeObject(state);// passivate just the bean instance
             oos.close();
@@ -78,25 +79,29 @@ public class SimplePassivater implements
         }
     }
 
-    public void passivate(Map hash) throws SystemException {
-        for (Object id : hash.keySet()) {
+    @Override
+    public void passivate(final Map hash) throws SystemException {
+        for (final Object id : hash.keySet()) {
             passivate(id, hash.get(id));
         }
     }
 
-    public Object activate(Object primaryKey) throws SystemException {
+    @Override
+    public Object activate(final Object primaryKey) throws SystemException {
         try {
-            String filename = primaryKey.toString().replace(':', '=');
+            final String filename = primaryKey.toString().replace(':', '=');
 
-            File sessionFile = new File(sessionDirectory, filename);
+            final File sessionFile = new File(sessionDirectory, filename);
 
             if (sessionFile.exists()) {
                 logger.info("Activating from file " + sessionFile);
 
-                ObjectInputStream ois = new ObjectInputStream(IO.read(sessionFile));
-                Object state = ois.readObject();
+                final ObjectInputStream ois = new ObjectInputStream(IO.read(sessionFile));
+                final Object state = ois.readObject();
                 ois.close();
-                sessionFile.delete();
+                if (!sessionFile.delete()) {
+                    sessionFile.deleteOnExit();
+                }
                 return state;
             } else {
                 logger.info("Activation failed: file not found " + sessionFile);

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/stateful/SimplePassivater.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/stateful/SimplePassivater.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/stateful/SimplePassivater.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/core/stateful/SimplePassivater.java Tue Dec 18 09:02:34 2012
@@ -16,12 +16,6 @@
  */
 package org.apache.openejb.core.stateful;
 
-import java.io.File;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.Map;
-import java.util.Properties;
-
 import org.apache.openejb.SystemException;
 import org.apache.openejb.core.EnvProps;
 import org.apache.openejb.core.ivm.EjbObjectInputStream;
@@ -30,8 +24,14 @@ import org.apache.openejb.loader.SystemI
 import org.apache.openejb.util.LogCategory;
 import org.apache.openejb.util.Logger;
 
+import java.io.File;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Map;
+import java.util.Properties;
 
 public class SimplePassivater implements PassivationStrategy {
+
     private static final Logger logger = Logger.getInstance(LogCategory.OPENEJB, "org.apache.openejb.util.resources");
     private File sessionDirectory;
 
@@ -39,12 +39,13 @@ public class SimplePassivater implements
         init(null);
     }
 
+    @Override
     public void init(Properties props) throws SystemException {
         if (props == null) {
             props = new Properties();
         }
 
-        String dir = props.getProperty(EnvProps.IM_PASSIVATOR_PATH_PREFIX);
+        final String dir = props.getProperty(EnvProps.IM_PASSIVATOR_PATH_PREFIX);
 
         try {
             if (dir != null) {
@@ -58,11 +59,11 @@ public class SimplePassivater implements
         }
     }
 
-    public void passivate(Object primaryKey, Object state) throws SystemException {
+    public void passivate(final Object primaryKey, final Object state) throws SystemException {
         try {
-            String filename = primaryKey.toString().replace(':', '=');
+            final String filename = primaryKey.toString().replace(':', '=');
 
-            File sessionFile = new File(sessionDirectory, filename);
+            final File sessionFile = new File(sessionDirectory, filename);
 
             logger.info("Passivating to file " + sessionFile);
 
@@ -83,17 +84,19 @@ public class SimplePassivater implements
         }
     }
 
-    public void passivate(Map hash) throws SystemException {
-        for (Object id : hash.keySet()) {
+    @Override
+    public void passivate(final Map hash) throws SystemException {
+        for (final Object id : hash.keySet()) {
             passivate(id, hash.get(id));
         }
     }
 
-    public Object activate(Object primaryKey) throws SystemException {
+    @Override
+    public Object activate(final Object primaryKey) throws SystemException {
         try {
-            String filename = primaryKey.toString().replace(':', '=');
+            final String filename = primaryKey.toString().replace(':', '=');
 
-            File sessionFile = new File(sessionDirectory, filename);
+            final File sessionFile = new File(sessionDirectory, filename);
 
             if (sessionFile.exists()) {
                 logger.info("Activating from file " + sessionFile);
@@ -103,7 +106,9 @@ public class SimplePassivater implements
                     return ois.readObject();
                 } finally {
                     IO.close(ois);
-                    sessionFile.delete();
+                    if (!sessionFile.delete()) {
+                        sessionFile.deleteOnExit();
+                    }
                 }
             } else {
                 logger.info("Activation failed: file not found " + sessionFile);

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/util/JarExtractor.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/util/JarExtractor.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/util/JarExtractor.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/util/JarExtractor.java Tue Dec 18 09:02:34 2012
@@ -35,6 +35,7 @@ import java.util.Properties;
  * @version $Rev$ $Date$
  */
 public class JarExtractor {
+
     public static final Logger logger = Logger.getInstance(LogCategory.OPENEJB_STARTUP_CONFIG, "org.apache.openejb.util.resources");
 
     /**
@@ -113,7 +114,6 @@ public class JarExtractor {
         return destinationDir.getAbsoluteFile();
     }
 
-
     /**
      * Copy the specified file or directory to the destination.
      *
@@ -166,7 +166,6 @@ public class JarExtractor {
 
     }
 
-
     /**
      * Delete the specified directory, including all of its contents and
      * subdirectories recursively.
@@ -177,7 +176,6 @@ public class JarExtractor {
         return deleteDir(dir);
     }
 
-
     /**
      * Delete the specified directory, including all of its contents and
      * subdirectories recursively.
@@ -185,7 +183,8 @@ public class JarExtractor {
      * @param dir File object representing the directory to be deleted
      */
     public static boolean deleteDir(final File dir) {
-        if (dir == null) return true;
+        if (dir == null)
+            return true;
 
         if (dir.isDirectory()) {
             final File[] files = dir.listFiles();
@@ -199,7 +198,6 @@ public class JarExtractor {
         return dir.delete();
     }
 
-
     /**
      * Extract the specified input stream into the specified directory, creating
      * a file named from the specified relative path.
@@ -216,8 +214,7 @@ public class JarExtractor {
         final File file = new File(docBase, name);
         BufferedOutputStream output = null;
         try {
-            output =
-                    new BufferedOutputStream(new FileOutputStream(file));
+            output = new BufferedOutputStream(new FileOutputStream(file));
             final byte[] buffer = new byte[2048];
             while (true) {
                 final int n = input.read(buffer);
@@ -238,5 +235,4 @@ public class JarExtractor {
         return file;
     }
 
-
 }

Modified: openejb/trunk/openejb/container/openejb-javaagent/src/main/java/org/apache/openejb/javaagent/Agent.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-javaagent/src/main/java/org/apache/openejb/javaagent/Agent.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-javaagent/src/main/java/org/apache/openejb/javaagent/Agent.java (original)
+++ openejb/trunk/openejb/container/openejb-javaagent/src/main/java/org/apache/openejb/javaagent/Agent.java Tue Dec 18 09:02:34 2012
@@ -17,38 +17,41 @@
  */
 package org.apache.openejb.javaagent;
 
+import java.io.Closeable;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.PrintWriter;
 import java.io.OutputStreamWriter;
-import java.io.Closeable;
-import java.lang.instrument.Instrumentation;
+import java.io.PrintWriter;
 import java.lang.instrument.ClassFileTransformer;
 import java.lang.instrument.IllegalClassFormatException;
+import java.lang.instrument.Instrumentation;
 import java.lang.management.ManagementFactory;
 import java.lang.management.RuntimeMXBean;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.lang.reflect.ReflectPermission;
-import java.lang.reflect.InvocationTargetException;
 import java.net.JarURLConnection;
 import java.net.URL;
 import java.net.URLConnection;
 import java.security.Permission;
 import java.security.ProtectionDomain;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
 public class Agent {
+
     private static final Permission ACCESS_PERMISSION = new ReflectPermission("suppressAccessChecks");
     private static String agentArgs;
     private static Instrumentation instrumentation;
     private static boolean initialized = false;
 
-    public static void premain(String agentArgs, Instrumentation instrumentation) {
-        if (Agent.instrumentation != null) return;
+    public static void premain(final String agentArgs, final Instrumentation instrumentation) {
+        if (Agent.instrumentation != null)
+            return;
 
         Agent.agentArgs = agentArgs;
         Agent.instrumentation = instrumentation;
@@ -57,8 +60,9 @@ public class Agent {
         instrumentation.addTransformer(new BootstrapTransformer());
     }
 
-    public static void agentmain(String agentArgs, Instrumentation instrumentation) {
-        if (Agent.instrumentation != null) return;
+    public static void agentmain(final String agentArgs, final Instrumentation instrumentation) {
+        if (Agent.instrumentation != null)
+            return;
 
         Agent.agentArgs = agentArgs;
         Agent.instrumentation = instrumentation;
@@ -66,8 +70,9 @@ public class Agent {
     }
 
     public static synchronized String getAgentArgs() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
+        final SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(ACCESS_PERMISSION);
         checkInitialization();
         return agentArgs;
     }
@@ -75,11 +80,13 @@ public class Agent {
     /**
      * Gets the instrumentation instance.
      * You must have java.lang.ReflectPermission(suppressAccessChecks) to call this method
+     *
      * @return the instrumentation instance
      */
     public static synchronized Instrumentation getInstrumentation() {
-        SecurityManager sm = System.getSecurityManager();
-        if (sm != null) sm.checkPermission(ACCESS_PERMISSION);
+        final SecurityManager sm = System.getSecurityManager();
+        if (sm != null)
+            sm.checkPermission(ACCESS_PERMISSION);
         checkInitialization();
         return instrumentation;
     }
@@ -98,42 +105,44 @@ public class Agent {
     }
 
     private static void checkSystemClassPath() throws NoSuchFieldException, IllegalAccessException {
-        if (instrumentation != null) return;
+        if (instrumentation != null)
+            return;
 
-        Class<?> systemAgentClass = null;
+        final Class<?> systemAgentClass;
         try {
-            ClassLoader systemCl = ClassLoader.getSystemClassLoader();
+            final ClassLoader systemCl = ClassLoader.getSystemClassLoader();
             systemAgentClass = systemCl.loadClass(Agent.class.getName());
         } catch (ClassNotFoundException e) {
             // java-agent jar was not on the system class path
             return;
         }
 
-        Field instrumentationField = systemAgentClass.getDeclaredField("instrumentation");
+        final Field instrumentationField = systemAgentClass.getDeclaredField("instrumentation");
         instrumentationField.setAccessible(true);
         instrumentation = (Instrumentation) instrumentationField.get(null);
 
-        Field agentArgsField = systemAgentClass.getDeclaredField("agentArgs");
+        final Field agentArgsField = systemAgentClass.getDeclaredField("agentArgs");
         agentArgsField.setAccessible(true);
         agentArgs = (String) agentArgsField.get(null);
     }
 
-    private static void dynamicLoadAgent() throws Exception{
-        if (instrumentation != null) return;
+    private static void dynamicLoadAgent() throws Exception {
+        if (instrumentation != null)
+            return;
 
         try {
-            Class<?> vmClass = Class.forName("com.sun.tools.attach.VirtualMachine");
-            Method attachMethod = vmClass.getMethod("attach", String.class);
-            Method loadAgentMethod = vmClass.getMethod("loadAgent", String.class);
+            final Class<?> vmClass = Class.forName("com.sun.tools.attach.VirtualMachine");
+            final Method attachMethod = vmClass.getMethod("attach", String.class);
+            final Method loadAgentMethod = vmClass.getMethod("loadAgent", String.class);
 
             // find the agentJar
-            String agentPath = getAgentJar();
+            final String agentPath = getAgentJar();
 
             // get the pid of the current process (for attach command)
-            String pid = getPid();
+            final String pid = getPid();
 
             // attach to the vm
-            Object vm = attachMethod.invoke(null, new String[] { pid });
+            final Object vm = attachMethod.invoke(null, new String[]{pid});
 
             // load our agent
             loadAgentMethod.invoke(vm, agentPath);
@@ -154,9 +163,9 @@ public class Agent {
         // there appears to be no other way to obtain the
         // current process' id, which we need for the attach
         // process
-        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
+        final RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
         String pid = bean.getName();
-        if (pid.indexOf("@") != -1) {
+        if (pid.contains("@")) {
             pid = pid.substring(0, pid.indexOf("@"));
         }
         return pid;
@@ -167,18 +176,18 @@ public class Agent {
      * file for the sole purpose of specifying an Agent-Class to load into the JVM.
      */
     private static String getAgentJar() throws IOException {
-        URL resource = Agent.class.getClassLoader().getResource(Agent.class.getName().replace('.', '/') + ".class");
+        final URL resource = Agent.class.getClassLoader().getResource(Agent.class.getName().replace('.', '/') + ".class");
         if (resource == null) {
             throw new IllegalStateException("Could not find Agent class file in class path");
         }
 
-        URLConnection urlConnection = resource.openConnection();
+        final URLConnection urlConnection = resource.openConnection();
         if (urlConnection instanceof JarURLConnection) {
-            JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
+            final JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
             return jarURLConnection.getJarFile().getName();
         }
 
-        InputStream in = urlConnection.getInputStream();
+        final InputStream in = urlConnection.getInputStream();
         ZipOutputStream out = null;
         File file = null;
         try {
@@ -190,7 +199,7 @@ public class Agent {
             // write manifest
             out.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
             try {
-                PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
+                final PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
                 writer.println("Agent-Class: " + Agent.class.getName());
                 writer.println("Can-Redefine-Classes: true");
                 writer.println("Can-Retransform-Classes: true");
@@ -202,7 +211,7 @@ public class Agent {
             // write agent class
             out.putNextEntry(new ZipEntry(Agent.class.getName().replace('.', '/') + ".class"));
             try {
-                byte[] buffer = new byte[4096];
+                final byte[] buffer = new byte[4096];
                 for (int count = in.read(buffer); count >= 0; count = in.read(buffer)) {
                     out.write(buffer, 0, count);
                 }
@@ -213,7 +222,9 @@ public class Agent {
             return file.getAbsolutePath();
         } catch (IOException e) {
             if (file != null) {
-                file.delete();
+                if (!file.delete()) {
+                    file.deleteOnExit();
+                }
             }
             throw e;
         } finally {
@@ -222,7 +233,7 @@ public class Agent {
         }
     }
 
-    private static void close(Closeable closeable) {
+    private static void close(final Closeable closeable) {
         if (closeable != null) {
             try {
                 closeable.close();
@@ -232,9 +243,11 @@ public class Agent {
     }
 
     private static class BootstrapTransformer implements ClassFileTransformer {
+
         private boolean done;
 
-        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
+        @Override
+        public byte[] transform(final ClassLoader loader, final String className, final Class<?> classBeingRedefined, final ProtectionDomain protectionDomain, final byte[] classfileBuffer) throws IllegalClassFormatException {
 
             try {
                 bootstrap(loader);
@@ -245,11 +258,12 @@ public class Agent {
             return classfileBuffer;
         }
 
-        private void bootstrap(ClassLoader loader) {
-            if (loader == null || done) return;
+        private void bootstrap(final ClassLoader loader) {
+            if (loader == null || done)
+                return;
 
-            String bootstrapClassName = "org.apache.openejb.persistence.PersistenceBootstrap";
-            String bootstrapClassFile = "org/apache/openejb/persistence/PersistenceBootstrap.class";
+            final String bootstrapClassName = "org.apache.openejb.persistence.PersistenceBootstrap";
+            final String bootstrapClassFile = "org/apache/openejb/persistence/PersistenceBootstrap.class";
 
             if (loader.getResource(bootstrapClassFile) == null) {
                 return;
@@ -261,10 +275,11 @@ public class Agent {
             done = true;
 
             try {
-                Class<?> bootstrapClass = loader.loadClass(bootstrapClassName);
-                Method bootstrap = bootstrapClass.getMethod("bootstrap", ClassLoader.class);
+                final Class<?> bootstrapClass = loader.loadClass(bootstrapClassName);
+                final Method bootstrap = bootstrapClass.getMethod("bootstrap", ClassLoader.class);
                 bootstrap.invoke(null, loader);
             } catch (Throwable e) {
+                Logger.getLogger(Agent.class.getName()).log(Level.WARNING, "Failed to invoke bootstrap: " + e.getMessage());
             }
         }
     }

Modified: openejb/trunk/openejb/container/openejb-loader/src/main/java/org/apache/openejb/loader/TomcatClassPath.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-loader/src/main/java/org/apache/openejb/loader/TomcatClassPath.java?rev=1423354&r1=1423353&r2=1423354&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-loader/src/main/java/org/apache/openejb/loader/TomcatClassPath.java (original)
+++ openejb/trunk/openejb/container/openejb-loader/src/main/java/org/apache/openejb/loader/TomcatClassPath.java Tue Dec 18 09:02:34 2012
@@ -51,7 +51,7 @@ public class TomcatClassPath extends Bas
         this(getCommonLoader(getContextClassLoader()));
     }
 
-    public TomcatClassPath(ClassLoader classLoader) {
+    public TomcatClassPath(final ClassLoader classLoader) {
         this.commonLoader = classLoader;
         try {
             addRepositoryMethod = getAddRepositoryMethod();
@@ -64,7 +64,7 @@ public class TomcatClassPath extends Bas
             }
         }
 
-        ClassLoader serverLoader = getServerLoader(getContextClassLoader());
+        final ClassLoader serverLoader = getServerLoader(getContextClassLoader());
         if (serverLoader != null && serverLoader != commonLoader) {
             this.serverLoader = serverLoader;
         } else
@@ -93,7 +93,7 @@ public class TomcatClassPath extends Bas
         return loader;
     }
 
-    private static ClassLoader getServerLoader(ClassLoader loader) {
+    private static ClassLoader getServerLoader(final ClassLoader loader) {
         try {
             return loader.loadClass("org.apache.catalina.Container").getClassLoader();
         } catch (ClassNotFoundException e) {
@@ -113,10 +113,10 @@ public class TomcatClassPath extends Bas
     }
 
     @Override
-    public void addJarsToPath(File dir) throws Exception {
-        String[] jarNames = dir.list(new java.io.FilenameFilter() {
+    public void addJarsToPath(final File dir) throws Exception {
+        final String[] jarNames = dir.list(new java.io.FilenameFilter() {
             @Override
-            public boolean accept(File dir, String name) {
+            public boolean accept(final File dir, final String name) {
                 return (name.endsWith(".jar") || name.endsWith(".zip"));
             }
         });
@@ -125,19 +125,19 @@ public class TomcatClassPath extends Bas
             return;
         }
 
-        for (String jarName : jarNames) {
+        for (final String jarName : jarNames) {
             this.addJarToPath(new File(dir, jarName).toURI().toURL());
         }
         rebuild();
     }
 
     @Override
-    public void addJarToPath(URL jar) throws Exception {
+    public void addJarToPath(final URL jar) throws Exception {
         this._addJarToPath(jar);
         rebuild();
     }
 
-    public void _addJarToPath(URL jar) throws Exception {
+    public void _addJarToPath(final URL jar) throws Exception {
         ClassLoader classLoader = commonLoader;
 
         if (serverLoader != null && useServerClassLoader(jar)) {
@@ -145,16 +145,16 @@ public class TomcatClassPath extends Bas
         }
 
         if (addRepositoryMethod != null) {
-            String path = jar.toExternalForm();
+            final String path = jar.toExternalForm();
             addRepositoryMethod.invoke(classLoader, path);
         } else {
             addURLMethod.invoke(classLoader, jar);
         }
     }
 
-    private boolean useServerClassLoader(URL jar) {
+    private boolean useServerClassLoader(final URL jar) {
         try {
-            URL url = findResource("META-INF/org.apache.openejb.tomcat/ServerClassLoader", jar);
+            final URL url = findResource("META-INF/org.apache.openejb.tomcat/ServerClassLoader", jar);
             return url != null;
         } catch (Exception e) {
             return false;
@@ -168,8 +168,8 @@ public class TomcatClassPath extends Bas
             @Override
             public Method run() {
                 try {
-                    Object cp = getURLClassPath((URLClassLoader) getClassLoader());
-                    Class<?> clazz = cp.getClass();
+                    final Object cp = getURLClassPath((URLClassLoader) getClassLoader());
+                    final Class<?> clazz = cp.getClass();
                     return clazz.getDeclaredMethod("getURLs", URL.class);
                 } catch (Exception e) {
                     throw new LoaderRuntimeException(e);
@@ -182,15 +182,15 @@ public class TomcatClassPath extends Bas
 
     protected void rebuild() {
         try {
-            Object cp = getURLClassPath((URLClassLoader) getClassLoader());
-            Method getURLsMethod = getGetURLsMethod();
+            final Object cp = getURLClassPath((URLClassLoader) getClassLoader());
+            final Method getURLsMethod = getGetURLsMethod();
             //noinspection NullArgumentToVariableArgMethod
-            URL[] urls = (URL[]) getURLsMethod.invoke(cp, (Object) null);
+            final URL[] urls = (URL[]) getURLsMethod.invoke(cp, (Object) null);
 
             if (urls.length < 1)
                 return;
 
-            StringBuilder path = new StringBuilder(urls.length * 32);
+            final StringBuilder path = new StringBuilder(urls.length * 32);
 
             File s;
             try {
@@ -227,7 +227,7 @@ public class TomcatClassPath extends Bas
             public Method run() {
                 Method method = null;
                 try {
-                    Class clazz = URLClassLoader.class;
+                    final Class clazz = URLClassLoader.class;
                     method = clazz.getDeclaredMethod("addURL", URL.class);
                     method.setAccessible(true);
                 } catch (Exception e2) {
@@ -242,9 +242,9 @@ public class TomcatClassPath extends Bas
         return AccessController.doPrivileged(new PrivilegedAction<Method>() {
             @Override
             public Method run() {
-                Method method;
+                final Method method;
                 try {
-                    Class clazz = getClassLoader().getClass();
+                    final Class clazz = getClassLoader().getClass();
                     method = clazz.getDeclaredMethod("addRepository", String.class);
                     method.setAccessible(true);
                     return method;
@@ -255,13 +255,13 @@ public class TomcatClassPath extends Bas
         });
     }
 
-    private static boolean isDirectory(URL url) {
-        String file = url.getFile();
+    private static boolean isDirectory(final URL url) {
+        final String file = url.getFile();
         return (file.length() > 0 && file.charAt(file.length() - 1) == '/');
     }
 
     @SuppressWarnings("ConstantConditions")
-    private static URL findResource(String resourceName, URL... search) {
+    private static URL findResource(final String resourceName, final URL... search) {
 
         for (int i = 0; i < search.length; i++) {
             URL currentUrl = search[i];
@@ -278,18 +278,18 @@ public class TomcatClassPath extends Bas
                 Logger.getLogger(TomcatClassPath.class.getName()).log(Level.FINE, "findResource", e);
             }
 
-            JarFile jarFile;
+            final JarFile jarFile;
             try {
-                String protocol = currentUrl.getProtocol();
+                final String protocol = currentUrl.getProtocol();
                 if (protocol.equals("jar")) {
                     /*
                     * If the connection for currentUrl or resURL is
                     * used, getJarFile() will throw an exception if the
                     * entry doesn't exist.
                     */
-                    URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
+                    final URL jarURL = ((JarURLConnection) currentUrl.openConnection()).getJarFileURL();
                     try {
-                        JarURLConnection juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
+                        final JarURLConnection juc = (JarURLConnection) new URL("jar", "", jarURL.toExternalForm() + "!/").openConnection();
                         jarFile = juc.getJarFile();
                     } catch (IOException e) {
                         // Don't look for this jar file again
@@ -297,11 +297,11 @@ public class TomcatClassPath extends Bas
                         throw e;
                     }
 
-                    String entryName;
+                    final String entryName;
                     if (currentUrl.getFile().endsWith("!/")) {
                         entryName = resourceName;
                     } else {
-                        String file = currentUrl.getFile();
+                        final String file = currentUrl.getFile();
                         int sepIdx = file.lastIndexOf("!/");
                         if (sepIdx == -1) {
                             // Invalid URL, don't look here again
@@ -309,7 +309,7 @@ public class TomcatClassPath extends Bas
                             continue;
                         }
                         sepIdx += 2;
-                        StringBuilder sb = new StringBuilder(file.length() - sepIdx + resourceName.length());
+                        final StringBuilder sb = new StringBuilder(file.length() - sepIdx + resourceName.length());
                         sb.append(file.substring(sepIdx));
                         sb.append(resourceName);
                         entryName = sb.toString();
@@ -321,13 +321,13 @@ public class TomcatClassPath extends Bas
                         return targetURL(currentUrl, resourceName);
                     }
                 } else if (protocol.equals("file")) {
-                    String baseFile = currentUrl.getFile();
-                    String host = currentUrl.getHost();
+                    final String baseFile = currentUrl.getFile();
+                    final String host = currentUrl.getHost();
                     int hostLength = 0;
                     if (host != null) {
                         hostLength = host.length();
                     }
-                    StringBuilder buf = new StringBuilder(2 + hostLength + baseFile.length() + resourceName.length());
+                    final StringBuilder buf = new StringBuilder(2 + hostLength + baseFile.length() + resourceName.length());
 
                     if (hostLength > 0) {
                         buf.append("//").append(host);
@@ -340,8 +340,8 @@ public class TomcatClassPath extends Bas
                         fixedResName = fixedResName.substring(1);
                     }
                     buf.append(fixedResName);
-                    String filename = buf.toString();
-                    File file = new File(filename);
+                    final String filename = buf.toString();
+                    final File file = new File(filename);
                     File file2;
                     try {
                         file2 = new File(decode(filename, "UTF-8"));
@@ -353,8 +353,8 @@ public class TomcatClassPath extends Bas
                         return targetURL(currentUrl, fixedResName);
                     }
                 } else {
-                    URL resourceURL = targetURL(currentUrl, resourceName);
-                    URLConnection urlConnection = resourceURL.openConnection();
+                    final URL resourceURL = targetURL(currentUrl, resourceName);
+                    final URLConnection urlConnection = resourceURL.openConnection();
 
                     try {
                         urlConnection.getInputStream().close();
@@ -367,7 +367,7 @@ public class TomcatClassPath extends Bas
                         return resourceURL;
                     }
 
-                    int code = ((HttpURLConnection) urlConnection).getResponseCode();
+                    final int code = ((HttpURLConnection) urlConnection).getResponseCode();
                     if (code >= 200 && code < 300) {
                         return resourceURL;
                     }
@@ -381,11 +381,11 @@ public class TomcatClassPath extends Bas
         return null;
     }
 
-    private static URL targetURL(URL base, String name) throws MalformedURLException {
-        StringBuilder sb = new StringBuilder(base.getFile().length() + name.length());
+    private static URL targetURL(final URL base, final String name) throws MalformedURLException {
+        final StringBuilder sb = new StringBuilder(base.getFile().length() + name.length());
         sb.append(base.getFile());
         sb.append(name);
-        String file = sb.toString();
+        final String file = sb.toString();
         return new URL(base.getProtocol(), base.getHost(), base.getPort(), file, null);
     }