[jboss-cvs] JBossAS SVN: r83993 - in projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess: unit and 1 other directory.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Mon Feb 9 04:55:56 EST 2009


Author: jaikiran
Date: 2009-02-09 04:55:55 -0500 (Mon, 09 Feb 2009)
New Revision: 83993

Added:
   projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerController.java
   projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerInvocationHandler.java
Modified:
   projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServer.java
   projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/unit/RemoteAccessTestCase.java
Log:
EJBTHREE-1396 MockServer reports startup/shutdown

Modified: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServer.java
===================================================================
--- projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServer.java	2009-02-09 09:44:45 UTC (rev 83992)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServer.java	2009-02-09 09:55:55 UTC (rev 83993)
@@ -1,3 +1,24 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+  *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
 package org.jboss.ejb3.test.proxy.remoteaccess;
 
 import java.net.URL;
@@ -13,6 +34,9 @@
 import org.jboss.ejb3.test.proxy.common.ejb.sfsb.MyStatefulBean;
 import org.jboss.ejb3.test.proxy.common.ejb.slsb.MyStatelessBean;
 import org.jboss.logging.Logger;
+import org.jboss.remoting.InvokerLocator;
+import org.jboss.remoting.ServerInvocationHandler;
+import org.jboss.remoting.transport.Connector;
 
 /**
  * MockServer
@@ -32,10 +56,29 @@
 
    private static final Logger log = Logger.getLogger(MockServer.class);
 
-   private static MockServer server;
-   
+   /**
+    * Invocation request to the MockServer will be handler by this
+    * invocation handler
+    */
+   private ServerInvocationHandler mockServerInvocationHandler;
+
    private static final String FILENAME_EJB3_INTERCEPTORS_AOP = "ejb3-interceptors-aop.xml";
 
+   /**
+    * Various possible server status
+    */
+   public enum MockServerStatus {
+      STARTED, STOPPED
+   }
+
+   /**
+    * 
+    * Various possible server requests
+    */
+   public enum MockServerRequest {
+      START, STOP
+   }
+
    // --------------------------------------------------------------------------------||
    // Instance Members ---------------------------------------------------------------||
    // --------------------------------------------------------------------------------||
@@ -43,6 +86,16 @@
    private EmbeddedTestMcBootstrap bootstrap;
 
    /**
+    * Accept requests from client using this {@link Connector} 
+    */
+   private Connector remoteConnector;
+
+   /**
+    * The current state of the server 
+    */
+   private MockServerStatus currentStatus = MockServerStatus.STOPPED;
+
+   /**
     * The Test Class using this launcher
     */
    private Class<?> testClass;
@@ -53,10 +106,31 @@
 
    /**
     * Constructor
+    * Configures and creates a socket based {@link Connector} which will
+    * accept (start/stop) requests from client 
     */
-   public MockServer(Class<?> testClass)
+   public MockServer(Class<?> testClass, String serverHost, int port)
    {
       this.setTestClass(testClass);
+      String uri = "socket://" + serverHost + ":" + port;
+      try
+      {
+         InvokerLocator invokerLocator = new InvokerLocator(uri);
+
+         this.remoteConnector = new Connector(invokerLocator);
+         this.remoteConnector.create();
+         this.mockServerInvocationHandler = new MockServerInvocationHandler(this);
+         this.remoteConnector.addInvocationHandler("EJB3Test", this.mockServerInvocationHandler);
+         log.debug("Connector created for accepting MockServer requests");
+
+      }
+      catch (Exception e)
+      {
+         log.error("Could not create Mockserver for testclass = " + testClass + " serverHost= " + serverHost
+               + " port= " + port,e);
+         throw new RuntimeException("Could not start server at " + uri, e);
+      }
+
    }
 
    // --------------------------------------------------------------------------------||
@@ -72,7 +146,7 @@
    {
 
       // Assert test class passed in
-      assert args.length == 1 : "String fully-qualified name of test class is the required first argument";
+      assert args.length > 2 : "Parameters requried (in that order): <Fully qualified test case name> <serverBindAddress> <serverPort> ";
 
       // Get Test Class
       String testClassname = args[0];
@@ -87,12 +161,21 @@
       }
 
       // Create a new Launcher
-      MockServer launcher = new MockServer(testClass);
-      MockServer.setServer(launcher);
+      // the serverBindAddress and the port are always the last two arguments
+      log.debug("Creating a MockServer for testclass = " + testClass + " and serverBindAddr = " + args[args.length - 2]
+            + " and port = " + args[args.length - 1]);
+      MockServer launcher = new MockServer(testClass, args[args.length - 2], Integer.parseInt(args[args.length - 1]));
+      try
+      {
+         // Ready to receive (start/stop) requests
+         launcher.acceptRequests();
+      }
+      catch (Throwable e)
+      {
+         log.error("Exception in MockServer while wating for requests ",e);
+         throw new RuntimeException("Exception while waiting for requests ", e);
+      }
 
-      // Initialize the launcher in a new Thread
-      new Startup(launcher).start();
-
    }
 
    // --------------------------------------------------------------------------------||
@@ -105,36 +188,37 @@
     */
    protected void initialize() throws Throwable
    {
-
       // Create and set a new MC Bootstrap 
       this.setBootstrap(EmbeddedTestMcBootstrap.createEmbeddedMcBootstrap());
 
       // Add a Shutdown Hook
-      Runtime.getRuntime().addShutdownHook(new ShutdownHook());
+      //Runtime.getRuntime().addShutdownHook(new ShutdownHook());
 
       // Bind the Ejb3Registrar
       Ejb3RegistrarLocator.bindRegistrar(new Ejb3McRegistrar(bootstrap.getKernel()));
 
       // Switch up to the hacky CL so that "jndi.properties" is not loaded
       ClassLoader olderLoader = Thread.currentThread().getContextClassLoader();
-      Thread.currentThread().setContextClassLoader(new JndiPropertiesToJnpserverPropertiesHackCl());
-
-      // Deploy *-beans.xml
-      this.getBootstrap().deploy(this.getTestClass());
-      
-      // Load ejb3-interceptors-aop.xml into AspectManager
-      ClassLoader cl = Thread.currentThread().getContextClassLoader();
-      URL url = cl.getResource(FILENAME_EJB3_INTERCEPTORS_AOP);
-      if (url == null)
-      {
-         throw new RuntimeException("Could not load " + AspectManager.class.getSimpleName()
-               + " with definitions from XML as file " + FILENAME_EJB3_INTERCEPTORS_AOP + " could not be found");
+      try {
+         Thread.currentThread().setContextClassLoader(new JndiPropertiesToJnpserverPropertiesHackCl());
+   
+         // Deploy *-beans.xml
+         this.getBootstrap().deploy(this.getTestClass());
+   
+         // Load ejb3-interceptors-aop.xml into AspectManager
+         ClassLoader cl = Thread.currentThread().getContextClassLoader();
+         URL url = cl.getResource(FILENAME_EJB3_INTERCEPTORS_AOP);
+         if (url == null)
+         {
+            throw new RuntimeException("Could not load " + AspectManager.class.getSimpleName()
+                  + " with definitions from XML as file " + FILENAME_EJB3_INTERCEPTORS_AOP + " could not be found");
+         }
+         AspectXmlLoader.deployXML(url);
+      } finally {
+         // Restore old CL
+         Thread.currentThread().setContextClassLoader(olderLoader);
       }
-      AspectXmlLoader.deployXML(url);
 
-      // Restore old CL
-      Thread.currentThread().setContextClassLoader(olderLoader);
-
       // Create a SLSB Container
       StatelessContainer slsbContainer = Utils.createSlsb(MyStatelessBean.class);
       log.info("Created SLSB Container: " + slsbContainer.getName());
@@ -149,88 +233,78 @@
 
    }
 
-   // --------------------------------------------------------------------------------||
-   // Inner Classes ------------------------------------------------------------------||
-   // --------------------------------------------------------------------------------||
-
-   protected static class Startup extends Thread implements Runnable
+   /**
+    * Starts the server <br>
+    * 
+    * @throws IllegalStateException If the server is not in {@link MockServerStatus.STOPPED}
+    *           state 
+    * @throws Throwable
+    */
+   public void start() throws Throwable
    {
-
-      // --------------------------------------------------------------------------------||
-      // Instance Members ---------------------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      private MockServer launcher;
-
-      // --------------------------------------------------------------------------------||
-      // Constructor --------------------------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      /**
-       * Constructor
-       */
-      public Startup(MockServer launcher)
+      // Server will be started only if current state is STOPPED
+      if (!this.currentStatus.equals(MockServerStatus.STOPPED))
       {
-         this.setLauncher(launcher);
+         throw new IllegalStateException("Cannot start MockServer when its in " + getStatus() + " state");
       }
+      initialize();
+      this.currentStatus = MockServerStatus.STARTED;
+      log.info("MockServer started");
+   }
 
-      // --------------------------------------------------------------------------------||
-      // Overridden Implementations -----------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      /**
-       * Starts the Remote Launcher
-       */
-      @Override
-      public void run()
+   /**
+    * Stops the server <br>
+    * 
+    * @throws IllegalStateException If the server is not in {@link MockServerStatus.STARTED} 
+    *           state
+    */
+   public void stop()
+   {
+      // Server will be stopped only if current state is STARTED
+      if (!this.currentStatus.equals(MockServerStatus.STARTED))
       {
-         // Initialize
-         try
-         {
-            this.getLauncher().initialize();
-         }
-         catch (Throwable e)
-         {
-            throw new RuntimeException("Could not initialize " + this.getLauncher(), e);
-         }
-
-         // Run
-         while (true);
+         throw new IllegalStateException("Cannot stop MockServer when its in " + getStatus() + " state");
       }
+      this.bootstrap.shutdown();
+      this.currentStatus = MockServerStatus.STOPPED;
+      log.info("MockServer stopped");
 
-      // --------------------------------------------------------------------------------||
-      // Accessors / Mutators -----------------------------------------------------------||
-      // --------------------------------------------------------------------------------||
+      // Note: Do not stop the Connector which is waiting for clients to 
+      // connect. Letting the Connector remain in waiting state will allow
+      // clients to restart this MockServer by sending the MockServerRequest.START
+      // request again.
+   }
 
-      public MockServer getLauncher()
-      {
-         return launcher;
-      }
+   /**
+    * 
+    * @return Returns the current status of the server
+    */
+   public MockServerStatus getStatus()
+   {
+      return this.currentStatus;
+   }
 
-      public void setLauncher(MockServer launcher)
-      {
-         this.launcher = launcher;
-      }
+   /**
+    * Start accepting requests <br>
+    * This is a blocking call and will wait for clients to connect
+    * 
+    * @see {@link Connector#start()}
+    * @throws Throwable
+    */
+   protected void acceptRequests() throws Throwable
+   {
+      this.remoteConnector.start();
    }
 
    /**
-    * Shutdown Hook for the MockServer
+    * 
+    * @param serverInvocationHandler The {@link ServerInvocationHandler} to
+    *   handle requests
     */
-   protected static class ShutdownHook extends Thread implements Runnable
+   protected void setInvocationHandler(ServerInvocationHandler serverInvocationHandler)
    {
+      this.mockServerInvocationHandler = serverInvocationHandler;
 
-      // --------------------------------------------------------------------------------||
-      // Overridden Implementations -----------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      /**
-       * Shuts down the Bootstrap
-       */
-      @Override
-      public void run()
-      {
-         getServer().bootstrap.shutdown();
-      }
    }
 
    // --------------------------------------------------------------------------------||
@@ -257,14 +331,4 @@
       this.testClass = testClass;
    }
 
-   public static MockServer getServer()
-   {
-      return server;
-   }
-
-   public static void setServer(MockServer server)
-   {
-      MockServer.server = server;
-   }
-
-}
\ No newline at end of file
+}

Added: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerController.java
===================================================================
--- projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerController.java	                        (rev 0)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerController.java	2009-02-09 09:55:55 UTC (rev 83993)
@@ -0,0 +1,441 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+  *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.ejb3.test.proxy.remoteaccess;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.jboss.ejb3.common.thread.RedirectProcessOutputToSystemOutThread;
+import org.jboss.ejb3.test.proxy.remoteaccess.MockServer.MockServerRequest;
+import org.jboss.logging.Logger;
+import org.jboss.remoting.CannotConnectException;
+import org.jboss.remoting.Client;
+import org.jboss.remoting.InvokerLocator;
+
+/**
+ * MockServerController
+ * 
+ * Controls the startup/shutdown of the {@link MockServer} <br/>
+ * 
+ * @author Jaikiran Pai
+ * @version $Revision: $
+ */
+public class MockServerController
+{
+
+   /**
+    * Instance of logger
+    */
+   private static Logger logger = Logger.getLogger(MockServerController.class);
+
+   /**
+    * JAVA_HOME env variable
+    */
+   private static final String ENV_VAR_JAVAHOME = "JAVA_HOME";
+
+   /**
+    * Java executable
+    */
+   private static final String EXECUTABLE_JAVA = "bin" + File.separator + "java";
+
+   /**
+    * The basedir
+    */
+   private static final String LOCATION_BASEDIR = System.getProperty("basedir");
+
+   private static final String LOCATION_TARGET = MockServerController.LOCATION_BASEDIR + File.separator + "target";
+
+   private static final String LOCATION_TEST_CLASSES = MockServerController.LOCATION_TARGET + File.separator
+         + "tests-classes";
+
+   private static final String LOCATION_CLASSES = MockServerController.LOCATION_TARGET + File.separator + "classes";
+
+   private static final String LOCATION_CONF = MockServerController.LOCATION_BASEDIR + File.separator + "conf";
+
+   private static final String FILENAME_DEPENDENCY_CP = MockServerController.LOCATION_TARGET + File.separator
+         + "cp.txt";
+
+   /**
+    * Timeout in milli sec. for server startup. Defaults to 2 minutes.
+    */
+   private int serverStartupTimeout = 120000;
+
+   /**
+    * Timeout in milli sec. for the server to shutdown. Defaults to 2 minutes.
+    */
+   private int serverStopTimeout = 120000;
+
+   /**
+    * The port number on which the {@link MockServer}
+    * is available for requests
+    */
+   private int port;
+
+   /**
+    * The host on which the {@link MockServer}
+    * is available for requests
+    */
+   private String serverHost;
+
+   /**
+    * Remote process in which the {@link MockServer} will run
+    */
+   private Process remoteProcess;
+
+   /**
+    * {@link Client} for sending requests to the {@link MockServer}
+    */
+   private Client mockServerClient;
+
+   /**
+    * Constructor <br>
+    * Creates a {@link Client} to send requests to the remote {@link MockServer}
+    *   
+    * @param host The host on which the {@link MockServer} is available
+    * @param port The port on which the {@link MockServer} is listening
+    */
+   public MockServerController(String host, int port)
+   {
+      this.serverHost = host;
+      this.port = port;
+      String uri = null;
+      try
+      {
+         uri = "socket://" + this.serverHost + ":" + this.port;
+         InvokerLocator invokerLocator = new InvokerLocator(uri);
+         this.mockServerClient = new Client(invokerLocator);
+
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException("Could not create server controller: ", e);
+      }
+
+   }
+
+   /**
+    * Creates a remote process (JVM) to launch the {@link MockServer}
+    * and then sends a {@link MockServerRequest#START} request to start the
+    * server
+    *   
+    * @param arguments The arguments that will be passed to the {@link MockServer} 
+    *       as JVM program arguments
+    *       
+    * @throws Throwable
+    */
+   public void startServer(String[] arguments) throws Throwable
+   {
+      // Along with the arguments that the client passes to the server,
+      // append the the serverHost and port number on which the mockserver is
+      // expected to listen
+      int numberOfArgs = arguments.length;
+      String[] processArgs = new String[numberOfArgs + 2];
+      System.arraycopy(arguments, 0, processArgs, 0, numberOfArgs);
+      // now append the server host and port
+      processArgs[processArgs.length - 2] = this.serverHost;
+      processArgs[processArgs.length - 1] = String.valueOf(this.port);
+
+      createRemoteProcess(processArgs);
+
+      /* 
+       * Wait a max of 5 seconds for the remote process (remember, not the server)
+       * to start
+       */
+      long start = System.currentTimeMillis();
+      int timeoutIntervalSeconds = 5;
+      long timeout = timeoutIntervalSeconds * 1000 + start;
+      boolean started = false;
+      while (!started)
+      {
+         try
+         {
+            // Start the server
+            sendStartRequestToServer();
+            // the server's started now
+            started = true;
+         }
+         // Couldn't start server
+         catch (CannotConnectException cce)
+         {
+            // If we haven't yet timed out
+            long current = System.currentTimeMillis();
+            if (current < timeout)
+            {
+               // Swallow exception and try again
+               logger.trace("Can't connect to server @ " + new Date(current) + ", trying until " + new Date(timeout));
+               Thread.sleep(100);
+               continue;
+            }
+            logger.error("The remote process was not up, even after 5 seconds. Aborting");
+            // Throw the exception, timeout's past
+            throw cce;
+         }
+      }
+
+   }
+
+   /**
+    * Sends a {@link MockServerRequest#STOP} request to the server
+    * and also kills the process in whic the server was running
+    * 
+    * @see MockServerController#stopServer(boolean)
+    * @throws Throwable
+    */
+   public void stopServer() throws Throwable
+   {
+      stopServer(true);
+      logger.debug("Stopped the server and killed the remote process");
+
+   }
+
+   /**
+    * Sends a {@link MockServerRequest#STOP} request to the server 
+    * and if the <code>killProcess</code> is true then it also kills
+    * the process in which the server was running.
+    * 
+    * @param killProcess If true, kills the process in which the {@link MockServer}
+    *           was running. Else, just sends a {@link MockServerRequest#STOP} request
+    *           to the server.
+    * @throws Throwable
+    */
+   public void stopServer(boolean killProcess) throws Throwable
+   {
+      // If there is nothing to stop, then return
+      if (this.remoteProcess == null)
+      {
+         logger.info("No remote process to stop. Returning");
+         return;
+      }
+      try
+      {
+         sendStopRequestToServer();
+         logger.debug("Stopped server");
+         // disconnect the client
+         this.mockServerClient.disconnect();
+
+      }
+      finally
+      {
+         if (killProcess)
+         {
+            // destroy the remote process
+            this.remoteProcess.destroy();
+            logger.debug("Remote process killed");
+         }
+      }
+   }
+
+   /**
+    * Sets the timeout for the server startup.
+    * <br/>
+    * This method has to be called before calling the {@link #startServer(String[])} method,
+    * for the timeout to be considered.
+    * 
+    * @param timeout The timeout value in milli seconds.
+    */
+   public void setServerStartupTimeout(int timeout)
+   {
+      this.serverStartupTimeout = timeout;
+   }
+
+   /**
+    * Returns the timeout set for the server startup.
+    * 
+    * @return
+    */
+   public int getServerStartupTimeout()
+   {
+      return this.serverStartupTimeout;
+   }
+
+   /**
+    * Returns the timeout set for server to stop
+    * 
+    * @return
+    */
+   public int getServerStopTimeout()
+   {
+      return this.serverStopTimeout;
+   }
+
+   /**
+    * Sets the timeout for the server to stop.
+    * <br/>
+    * This method has to be called before calling the {@link #stopServer()} method,
+    * for the timeout to be considered.
+    * 
+    * @param timeout The timeout value in milli seconds.
+    */
+   public void setServerStopTimeout(int timeout)
+   {
+      this.serverStopTimeout = timeout;
+   }
+
+   /**
+    * Sends a {@link MockServerRequest#STOP} to the server
+    * 
+    * @throws Throwable
+    */
+   protected void sendStopRequestToServer() throws Throwable
+   {
+      this.mockServerClient.connect();
+      // set a timeout - The client will wait for this amount of time 
+      // for the mockserver to shutdown
+      Map<String, String> configParams = new HashMap<String, String>();
+      configParams.put("timeout", String.valueOf(this.serverStopTimeout));
+      Object serverStatus = this.mockServerClient.invoke(MockServerRequest.STOP, configParams);
+      logger.debug("Stop request returned Status = " + serverStatus);
+
+   }
+
+   /**
+    * Sends a {@link MockServerRequest#START} to the server
+    * @throws Throwable
+    */
+   protected void sendStartRequestToServer() throws Throwable
+   {
+      this.mockServerClient.connect();
+      // set a timeout - The client will wait for this amount of time 
+      // for the mockserver to shutdown
+      Map<String, String> configParams = new HashMap<String, String>();
+      configParams.put("timeout", String.valueOf(this.serverStartupTimeout));
+      Object serverStatus = this.mockServerClient.invoke(MockServerRequest.START, configParams);
+      logger.info("Server started. Status = " + serverStatus);
+
+   }
+
+   /**
+    * Creates a new JVM process in which the {@link MockServer} will be active
+    * 
+    * 
+    * @param arguments The arguments to the passed to the {@link MockServer}
+    * 
+    * @throws Throwable
+    */
+   private void createRemoteProcess(String arguments[]) throws Throwable
+   {
+      // Get the current System Properties and Environment Variables
+      String javaHome = System.getenv(MockServerController.ENV_VAR_JAVAHOME);
+      String conf = MockServerController.LOCATION_CONF;
+      String testClasses = MockServerController.LOCATION_TEST_CLASSES;
+      String classes = MockServerController.LOCATION_CLASSES;
+
+      // Get the contents of the dependency classpath file
+      String dependencyClasspathFilename = MockServerController.FILENAME_DEPENDENCY_CP;
+      File dependencyClasspath = new File(dependencyClasspathFilename);
+      assert dependencyClasspath.exists() : "File " + dependencyClasspathFilename
+            + " is required to denote the dependency CP";
+      BufferedReader reader = new BufferedReader(new FileReader(dependencyClasspath));
+      StringBuffer contents = new StringBuffer();
+      String line = null;
+      while ((line = reader.readLine()) != null)
+      {
+         contents.append(line);
+         contents.append(System.getProperty("line.separator"));
+      }
+      String depCp = contents.toString().trim();
+
+      // Build the command
+      List<String> command = new ArrayList<String>();
+
+      // Executable (Java)
+      StringBuffer executable = new StringBuffer();
+      executable.append(javaHome); // JAVA_HOME
+      executable.append(File.separatorChar);
+      executable.append(MockServerController.EXECUTABLE_JAVA);
+
+      command.add(executable.toString());
+
+      // Classpath
+      command.add("-classpath");
+
+      StringBuffer classPath = new StringBuffer();
+      classPath.append(classes);
+      classPath.append(File.pathSeparator);
+      classPath.append(testClasses);
+      classPath.append(File.pathSeparatorChar);
+      classPath.append(conf);
+      classPath.append(File.pathSeparatorChar);
+      classPath.append(depCp); // Dependency CP
+
+      command.add(classPath.toString());
+      // Other params to the JVM
+      command.add("-ea");
+      // The class to run
+      command.add(MockServer.class.getName());
+      // The arguments to the main class
+      for (int i = 0; i < arguments.length; i++)
+      {
+         command.add(arguments[i]);
+      }
+
+      // Create a Remote Launcher
+      ProcessBuilder builder = new ProcessBuilder();
+      builder.command(command);
+      builder.redirectErrorStream(true);
+      File pwd = new File(MockServerController.LOCATION_BASEDIR);
+      assert pwd.exists() : "Present working directory for execution of remote process, " + pwd.getAbsolutePath()
+            + ", could not be found.";
+      logger.debug("Remote Process working directory: " + pwd.getAbsolutePath());
+      builder.directory(pwd);
+      logger.info("Launching in separate process: " + getPrintableCommand(command));
+      try
+      {
+         this.remoteProcess = builder.start();
+         logger.info("Remote process = " + this.remoteProcess);
+         // Redirect output from the separate process
+         new RedirectProcessOutputToSystemOutThread(this.remoteProcess).start();
+
+      }
+      catch (Throwable t)
+      {
+         throw new RuntimeException("Could not execute remote process", t);
+      }
+
+   }
+
+   /**
+    * Utility method to generate a printable string from a List.
+    * The elements of the list will be separated by a space (unlike the
+    * default comma separated List.toString()).
+    * 
+    * @param command The command
+    * @return Returns a printable form of the <code>command</code>
+    */
+   private String getPrintableCommand(List<String> command)
+   {
+      StringBuffer printableCmd = new StringBuffer();
+      for (String cmd : command)
+      {
+         printableCmd.append(cmd);
+         printableCmd.append(" ");
+      }
+      return printableCmd.toString();
+   }
+
+}


Property changes on: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerController.java
___________________________________________________________________
Name: svn:executable
   + *

Added: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerInvocationHandler.java
===================================================================
--- projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerInvocationHandler.java	                        (rev 0)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerInvocationHandler.java	2009-02-09 09:55:55 UTC (rev 83993)
@@ -0,0 +1,150 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+  *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.ejb3.test.proxy.remoteaccess;
+
+import javax.management.MBeanServer;
+
+import org.jboss.ejb3.test.proxy.remoteaccess.MockServer.MockServerRequest;
+import org.jboss.logging.Logger;
+import org.jboss.remoting.InvocationRequest;
+import org.jboss.remoting.ServerInvocationHandler;
+import org.jboss.remoting.ServerInvoker;
+import org.jboss.remoting.callback.InvokerCallbackHandler;
+
+/**
+ * MockServerInvocationHandler
+ *
+ * @author Jaikiran Pai
+ * @version $Revision: $
+ */
+public class MockServerInvocationHandler implements ServerInvocationHandler
+{
+
+   /**
+    * Instance of logger
+    */
+   private static Logger logger = Logger.getLogger(MockServerInvocationHandler.class);
+
+   /**
+    * Instance of {@link MockServer} to which the requests will be
+    * forwarded
+    */
+   private MockServer mockServer;
+
+   /**
+    * Constructor
+    * 
+    * @param mockServer  
+    */
+   public MockServerInvocationHandler(MockServer mockServer)
+   {
+      this.mockServer = mockServer;
+   }
+
+   /**
+    * @see org.jboss.remoting.ServerInvocationHandler#addListener(org.jboss.remoting.callback.InvokerCallbackHandler)
+    */
+   public void addListener(InvokerCallbackHandler callbackHandler)
+   {
+      // no asynchronous support required as of now. Implement later if required
+
+   }
+
+   /**
+    * On receiving a {@link MockServerRequest} the invocation handler will
+    * carry out appropriate operation on the {@link MockServer} <br>
+    * 
+    * Supported requests are <br/>
+    * <li>
+    *   <ul>
+    *   {@link MockServerRequest.START} - On receiving this request, the invocation 
+    *   handler will start the {@link MockServer}
+    *   </ul>
+    *   <ul>
+    *   {@link MockServerRequest.STOP} - On receiving this request, the invocation 
+    *   handler will stop the {@link MockServer}
+    *   </ul>
+    * </li>
+    * @throws {@link IllegalArgumentException} If the <code>invocationRequest</code>
+    *           is not supported
+    * @see org.jboss.remoting.ServerInvocationHandler#invoke(org.jboss.remoting.InvocationRequest)
+    */
+   public Object invoke(InvocationRequest invocationRequest) throws Throwable
+   {
+
+      if (!(invocationRequest.getParameter() instanceof MockServerRequest))
+      {
+         throw new IllegalArgumentException("Unrecognized request type " + invocationRequest.getParameter());
+      }
+      MockServerRequest request = (MockServerRequest) invocationRequest.getParameter();
+      logger.info("Received request: " + request);
+
+      // The same invocation handler can be called by multiple threads.
+      synchronized (this.mockServer)
+      {
+         if (request.equals(MockServerRequest.START))
+         {
+            this.mockServer.start();
+         }
+         else if (request.equals(MockServerRequest.STOP))
+         {
+            this.mockServer.stop();
+            
+         }
+         else
+         {
+            throw new IllegalArgumentException("Unrecognized request " + invocationRequest.getParameter());
+         }
+         return mockServer.getStatus();
+      }
+
+      
+   }
+
+   /**
+    * @see org.jboss.remoting.ServerInvocationHandler#removeListener(org.jboss.remoting.callback.InvokerCallbackHandler)
+    */
+   public void removeListener(InvokerCallbackHandler callbackHandler)
+   {
+      // do nothing - Implement later if needed
+
+   }
+
+   /**
+    * @see org.jboss.remoting.ServerInvocationHandler#setInvoker(org.jboss.remoting.ServerInvoker)
+    */
+   public void setInvoker(ServerInvoker invoker)
+   {
+      // do nothing - Implement later if needed
+
+   }
+
+   /**
+    * @see org.jboss.remoting.ServerInvocationHandler#setMBeanServer(javax.management.MBeanServer)
+    */
+   public void setMBeanServer(MBeanServer server)
+   {
+      // do nothing - Implement later if needed
+
+   }
+
+}


Property changes on: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServerInvocationHandler.java
___________________________________________________________________
Name: svn:executable
   + *

Modified: projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/unit/RemoteAccessTestCase.java
===================================================================
--- projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/unit/RemoteAccessTestCase.java	2009-02-09 09:44:45 UTC (rev 83992)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/unit/RemoteAccessTestCase.java	2009-02-09 09:55:55 UTC (rev 83993)
@@ -22,21 +22,18 @@
 package org.jboss.ejb3.test.proxy.remoteaccess.unit;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
+import java.io.InputStream;
+import java.util.Properties;
 
 import javax.naming.Context;
 import javax.naming.InitialContext;
 
-import org.jboss.ejb3.common.thread.RedirectProcessOutputToSystemOutThread;
 import org.jboss.ejb3.test.proxy.common.ejb.sfsb.MyStatefulRemoteBusiness;
 import org.jboss.ejb3.test.proxy.common.ejb.slsb.MyStatelessRemote;
 import org.jboss.ejb3.test.proxy.remoteaccess.JndiPropertiesToJndiRemotePropertiesHackCl;
-import org.jboss.ejb3.test.proxy.remoteaccess.MockServer;
+import org.jboss.ejb3.test.proxy.remoteaccess.MockServerController;
 import org.jboss.logging.Logger;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
@@ -57,32 +54,24 @@
 
    private static final Logger log = Logger.getLogger(RemoteAccessTestCase.class);
 
-   private static final String ENV_VAR_JAVAHOME = "JAVA_HOME";
-
-   private static final String EXECUTABLE_JAVA = "bin" + File.separator + "java";
-
-   private static final String LOCATION_BASEDIR = System.getProperty("basedir");
-
-   private static final String LOCATION_TARGET = RemoteAccessTestCase.LOCATION_BASEDIR + File.separator + "target";
-
-   private static final String LOCATION_TEST_CLASSES = RemoteAccessTestCase.LOCATION_TARGET + File.separator
-         + "tests-classes";
-
-   private static final String LOCATION_CLASSES = RemoteAccessTestCase.LOCATION_TARGET + File.separator + "classes";
-
-   private static final String LOCATION_CONF = RemoteAccessTestCase.LOCATION_BASEDIR + File.separator + "conf";
-
-   private static final String FILENAME_DEPENDENCY_CP = RemoteAccessTestCase.LOCATION_TARGET + File.separator
-         + "cp.txt";
-
    private static final String JNDI_NAME_SLSB_LOCAL = "MyStatelessBean/local";
 
    private static final String JNDI_NAME_SLSB_REMOTE = "MyStatelessBean/remote";
 
    private static final String JNDI_NAME_SFSB_REMOTE = "MyStatefulBean/remote";
 
-   private static Process remoteProcess;
+   private static MockServerController mockServerController;
 
+   /**
+    * The server host on which the MockServer will be available for requests
+    */
+   private static final String serverHost = "localhost";
+
+   /**
+    * The server port on which the MockServer will be available for requests
+    */
+   private static final int serverPort = 12345;
+
    private static Context context;
 
    // --------------------------------------------------------------------------------||
@@ -172,20 +161,29 @@
    @BeforeClass
    public static void beforeClass() throws Throwable
    {
-      // Switch up to the hacky CL so that "jndi.properties" is not loaded, and uses instead "jndi-remote.properties"
-      ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
-      Thread.currentThread().setContextClassLoader(new JndiPropertiesToJndiRemotePropertiesHackCl());
+      
+      // get the input stream for jndi-remote.properties file, which will be available
+      // in classpath
+      InputStream inputStream = RemoteAccessTestCase.class.getClassLoader().getResourceAsStream(
+            "jndi-remote.properties");
 
-      RemoteAccessTestCase.setContext(new InitialContext());
+      // load the jndi-remote.properties 
+      Properties jndiRemoteProperties = new Properties();
+      jndiRemoteProperties.load(inputStream);
 
-      // Replace the CL
-      Thread.currentThread().setContextClassLoader(oldLoader);
+      // Use the non-default constructor of InitialContext and pass the 
+      // properties
+      RemoteAccessTestCase.setContext(new InitialContext(jndiRemoteProperties));  
+      
+      // create a controller for mockserver
+      mockServerController = new MockServerController(serverHost, serverPort);
 
       // Start Server
-      RemoteAccessTestCase.invokeRemoteMockServerProcess(RemoteAccessTestCase.class.getName());
+      long start = System.currentTimeMillis();
+      mockServerController.startServer(new String[]{RemoteAccessTestCase.class.getName()});
+      long end = System.currentTimeMillis();
+      log.info("MockServer started in " + (end - start) + " milli sec.");
 
-      // Wait for Server to start
-      Thread.sleep(5000);
    }
 
    /**
@@ -196,104 +194,14 @@
    @AfterClass
    public static void afterClass() throws Throwable
    {
-      /*
-       * This is far from a graceful shutdown, but hey, this is only a test
-       */
-      Process p = RemoteAccessTestCase.getRemoteProcess();
-      p.destroy();
+      mockServerController.stopServer();
 
    }
 
    // --------------------------------------------------------------------------------||
-   // Helper Methods -----------------------------------------------------------------||
-   // --------------------------------------------------------------------------------||
-
-   /**
-    * Invokes on the MockServer, spinning up as a new Process
-    * 
-    * @param argument
-    * @throws Throwable
-    */
-   protected static void invokeRemoteMockServerProcess(String argument) throws Throwable
-   {
-      // Get the current System Properties and Environment Variables
-      String javaHome = System.getenv(RemoteAccessTestCase.ENV_VAR_JAVAHOME);
-      String conf = RemoteAccessTestCase.LOCATION_CONF;
-      String testClasses = RemoteAccessTestCase.LOCATION_TEST_CLASSES;
-      String classes = RemoteAccessTestCase.LOCATION_CLASSES;
-
-      // Get the contents of the dependency classpath file
-      String dependencyClasspathFilename = RemoteAccessTestCase.FILENAME_DEPENDENCY_CP;
-      File dependencyClasspath = new File(dependencyClasspathFilename);
-      assert dependencyClasspath.exists() : "File " + dependencyClasspathFilename
-            + " is required to denote the dependency CP";
-      BufferedReader reader = new BufferedReader(new FileReader(dependencyClasspath));
-      StringBuffer contents = new StringBuffer();
-      String line = null;
-      while ((line = reader.readLine()) != null)
-      {
-         contents.append(line);
-         contents.append(System.getProperty("line.separator"));
-      }
-      String depCp = contents.toString().trim();
-
-      // Build the command
-      StringBuffer command = new StringBuffer();
-      command.append(javaHome); // JAVA_HOME
-      command.append(File.separatorChar);
-      command.append(RemoteAccessTestCase.EXECUTABLE_JAVA);
-      command.append(" -cp "); // Classpath
-
-      command.append(classes);
-      command.append(File.pathSeparatorChar);
-      command.append(testClasses);
-      command.append(File.pathSeparatorChar);
-      command.append(conf);
-      command.append(File.pathSeparatorChar);
-      command.append(depCp); // Dependency CP
-      command.append(" -ea "); // Enable Assertions
-      command.append(MockServer.class.getName());
-      command.append(' ');
-      command.append(argument); // Argument
-
-      // Create a Remote Launcher
-      String cmd = command.toString();
-      String[] cmds = cmd.split(" ");
-      ProcessBuilder builder = new ProcessBuilder();
-      builder.command(cmds);
-      builder.redirectErrorStream(true);
-      File pwd = new File(RemoteAccessTestCase.LOCATION_BASEDIR);
-      assert pwd.exists() : "Present working directory for execution of remote process, " + pwd.getAbsolutePath()
-            + ", could not be found.";
-      log.debug("Remote Process working directory: " + pwd.getAbsolutePath());
-      builder.directory(pwd);
-      log.info("Launching in separate process: " + cmd);
-      try
-      {
-         RemoteAccessTestCase.setRemoteProcess(builder.start());
-         // Redirect output from the separate process
-         new RedirectProcessOutputToSystemOutThread(RemoteAccessTestCase.getRemoteProcess()).start();
-      }
-      catch (Throwable t)
-      {
-         throw new RuntimeException("Could not execute remote process", t);
-      }
-   }
-
-   // --------------------------------------------------------------------------------||
    // Accessors / Mutators -----------------------------------------------------------||
    // --------------------------------------------------------------------------------||
 
-   public static Process getRemoteProcess()
-   {
-      return remoteProcess;
-   }
-
-   protected static void setRemoteProcess(Process remoteProcess)
-   {
-      RemoteAccessTestCase.remoteProcess = remoteProcess;
-   }
-
    public static Context getContext()
    {
       return context;




More information about the jboss-cvs-commits mailing list