[jboss-cvs] JBossAS SVN: r81462 - 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
Sun Nov 23 03:05:57 EST 2008


Author: jaikiran
Date: 2008-11-23 03:05:56 -0500 (Sun, 23 Nov 2008)
New Revision: 81462

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 must report startup / shutdown

Added support to wait for the MockServer to start/stop. Additionally, multiple MockServers can now be started in their own JVM.

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	2008-11-22 15:30:08 UTC (rev 81461)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/MockServer.java	2008-11-23 08:05:56 UTC (rev 81462)
@@ -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
@@ -31,16 +55,47 @@
    // --------------------------------------------------------------------------------||
 
    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 ---------------------------------------------------------------||
    // --------------------------------------------------------------------------------||
 
    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
@@ -53,10 +108,28 @@
 
    /**
     * 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);
+         
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException("Could not start server at " + uri, e);
+      } 
+      
    }
 
    // --------------------------------------------------------------------------------||
@@ -72,7 +145,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 +160,18 @@
       }
 
       // Create a new Launcher
-      MockServer launcher = new MockServer(testClass);
-      MockServer.setServer(launcher);
-
-      // Initialize the launcher in a new Thread
-      new Startup(launcher).start();
-
+      // the serverBindAddress and the port are always the last two arguments
+      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)
+      {
+         throw new RuntimeException("Exception while waiting for requests ",e);
+      }
+      
    }
 
    // --------------------------------------------------------------------------------||
@@ -105,12 +184,11 @@
     */
    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()));
@@ -146,93 +224,83 @@
       // Install into MC
       this.getBootstrap().installInstance(slsbContainer.getName(), slsbContainer);
       this.getBootstrap().installInstance(sfsbContainer.getName(), sfsbContainer);
-
+      
    }
-
-   // --------------------------------------------------------------------------------||
-   // 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");
       }
-
-      // --------------------------------------------------------------------------------||
-      // Overridden Implementations -----------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      /**
-       * Starts the Remote Launcher
-       */
-      @Override
-      public void run()
-      {
-         // Initialize
-         try
-         {
-            this.getLauncher().initialize();
-         }
-         catch (Throwable e)
-         {
-            throw new RuntimeException("Could not initialize " + this.getLauncher(), e);
-         }
-
-         // Run
-         while (true);
-      }
-
-      // --------------------------------------------------------------------------------||
-      // Accessors / Mutators -----------------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      public MockServer getLauncher()
-      {
-         return launcher;
-      }
-
-      public void setLauncher(MockServer launcher)
-      {
-         this.launcher = launcher;
-      }
+      initialize();
+      this.currentStatus = MockServerStatus.STARTED;
+      log.info("MockServer started");
    }
-
+   
    /**
-    * Shutdown Hook for the MockServer
+    * Stops the server <br>
+    * 
+    * @throws IllegalStateException If the server is not in {@link MockServerStatus.STARTED} 
+    *           state
     */
-   protected static class ShutdownHook extends Thread implements Runnable
+   public void stop()
    {
-
-      // --------------------------------------------------------------------------------||
-      // Overridden Implementations -----------------------------------------------------||
-      // --------------------------------------------------------------------------------||
-
-      /**
-       * Shuts down the Bootstrap
-       */
-      @Override
-      public void run()
+      // Server will be stopped only if current state is STARTED
+      if (!this.currentStatus.equals(MockServerStatus.STARTED))
       {
-         getServer().bootstrap.shutdown();
+         throw new IllegalStateException("Cannot stop MockServer when its in " + getStatus() + " state");
       }
+      this.bootstrap.shutdown();
+      this.currentStatus = MockServerStatus.STOPPED;
+      log.info("MockServer stopped");
+      
+      // 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.
    }
-
+   
+   /**
+    * 
+    * @return Returns the current status of the server
+    */
+   public MockServerStatus getStatus()
+   {
+      return this.currentStatus;
+   }
+   
+   /**
+    * 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();
+   }
+   
+   /**
+    * 
+    * @param serverInvocationHandler The {@link ServerInvocationHandler} to
+    *   handle requests
+    */
+   protected void setInvocationHandler(ServerInvocationHandler serverInvocationHandler)
+   {
+      this.mockServerInvocationHandler = serverInvocationHandler;
+      
+   }
+   
    // --------------------------------------------------------------------------------||
    // Accessors / Mutators -----------------------------------------------------------||
    // --------------------------------------------------------------------------------||
@@ -256,15 +324,6 @@
    {
       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	2008-11-23 08:05:56 UTC (rev 81462)
@@ -0,0 +1,321 @@
+/*
+ * 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.HashMap;
+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.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/shutdown
+    */
+   private static final int TIMEOUT = 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);
+
+      sendStartRequestToServer();
+   }
+
+   /**
+    * 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
+   {
+      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");
+         }
+      }
+   }
+
+   /**
+    * 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 configParams = new HashMap();
+      configParams.put("timeout", String.valueOf(TIMEOUT));
+      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 configParams = new HashMap();
+      configParams.put("timeout", String.valueOf(TIMEOUT));
+      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
+      StringBuffer command = new StringBuffer();
+      command.append(javaHome); // JAVA_HOME
+      command.append(File.separatorChar);
+      command.append(MockServerController.EXECUTABLE_JAVA);
+      command.append(" -cp "); // Classpath
+      command.append("\"");
+
+      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("\"");
+
+      command.append(" -ea "); // Enable Assertions
+      command.append(MockServer.class.getName());
+      command.append(' ');
+      for (int i = 0; i < arguments.length; i++)
+      {
+         command.append(arguments[i]); // Argument
+         command.append(' ');
+      }
+
+      // 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(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: " + cmd);
+      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);
+      }
+
+   }
+
+}

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	2008-11-23 08:05:56 UTC (rev 81462)
@@ -0,0 +1,149 @@
+/*
+ * 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());
+         }
+      }
+
+      logger.debug("Server in " + mockServer.getStatus() + " state");
+      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
+
+   }
+
+}

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	2008-11-22 15:30:08 UTC (rev 81461)
+++ projects/ejb3/trunk/proxy/src/test/java/org/jboss/ejb3/test/proxy/remoteaccess/unit/RemoteAccessTestCase.java	2008-11-23 08:05:56 UTC (rev 81462)
@@ -22,21 +22,15 @@
 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 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 +51,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;
 
    // --------------------------------------------------------------------------------||
@@ -181,11 +167,15 @@
       // Replace the CL
       Thread.currentThread().setContextClassLoader(oldLoader);
 
+      // 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 +186,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