corrected merge to latest snapshot version
[taxeditor.git] / eu.etaxonomy.taxeditor.test / src / test / java / eu / etaxonomy / taxeditor / httpinvoker / CDMServer.java
index cdb5abea841289d6dbcd085549e8592ab28aebc4..a6f5fd509f5924780e7c45946f1f091d3f0ed8fa 100644 (file)
@@ -12,11 +12,18 @@ package eu.etaxonomy.taxeditor.httpinvoker;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
-import java.net.Socket;
 
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanException;
+import javax.management.MBeanServerConnection;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
 import javax.sql.DataSource;
 
-import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 import org.springframework.core.io.ClassPathResource;
 import org.springframework.core.io.Resource;
@@ -48,25 +55,14 @@ public class CDMServer {
 
     private final String name = "default";
     private final String host = "127.0.0.1";
-    private final int port = 9090;
-    private final int stopPort = 9191;
-    private final String stopKey = "jetty-cdm-server";
+    private int httpPort = 9090;
+    private int stopPort = 9191;
+    private String stopKey = "jetty-cdm-server";
     private final String contextPath = "";
 
-    private boolean keepServerRunning = false;
-
     public static final Resource DEFAULT_CDM_WEBAPP_RESOURCE =
             new ClassPathResource("/etc/jetty/cdmlib-remote-webapp.war");
 
-    public static final Resource DEFAULT_JETTY_CONFIG_RESOURCE =
-            new ClassPathResource("/etc/jetty/jetty.xml");
-
-    public static final Resource DEFAULT_JETTY_TEMP_RESOURCE =
-            new ClassPathResource("/etc/jetty/temp");
-
-    public static final Resource DEFAULT_JETTY_TEMP_WAR_LIB_RESOURCE =
-            new ClassPathResource("/etc/jetty/temp/webapp/WEB-INF/lib");
-
     public static final Resource DEFAULT_DATASOURCE_FILE =
             new ClassPathResource("datasources.xml");
 
@@ -76,14 +72,10 @@ public class CDMServer {
     public static final Resource DEFAULT_JETTY_RESOURCE =
             new ClassPathResource("/etc/jetty/start-9.2.3.v20140905.jar");
 
-
-
     private static CDMServer cdmServer = null;
     private static CDMServerException cdmse = null;
 
-    private void CDMServer() {
-        logger.setLevel(Level.INFO);
-    }
+    private void CDMServer() {}
 
     public static CDMServer getInstance() {
         if(cdmServer == null) {
@@ -101,21 +93,26 @@ public class CDMServer {
     }
 
     public int getPort() {
-        return port;
+        return httpPort;
     }
 
     public String getContextPath() {
         return contextPath;
     }
 
-    public boolean getKeepServerRunning() {
-        return keepServerRunning;
+    public void setHttpPort(int port) {
+        this.httpPort = port;
+    }
+
+    public void setStopPort(int stopPort) {
+        this.stopPort = stopPort;
     }
 
-    public void setKeepServerRunning(boolean keepServerRunning) {
-        this.keepServerRunning = keepServerRunning;
+    public void setStopKey(String stopKey) {
+        this.stopKey = stopKey;
     }
 
+
     public static boolean isRunningInEclipse() {
         return (System.getProperty("sun.java.command") != null &&
                 System.getProperty("sun.java.command").startsWith("org.eclipse.jdt.internal.junit.runner.RemoteTestRunner"));
@@ -129,10 +126,9 @@ public class CDMServer {
         return sb.toString();
     }
 
-    private String getStartServerArgs() {
+    private String getStartServerArgs() throws IOException {
         StringBuilder sb = new StringBuilder();
-        sb.append(" --port ");
-        sb.append(port);
+        sb.append(" --port " + httpPort);
         return sb.toString();
     }
 
@@ -154,6 +150,7 @@ public class CDMServer {
         return sb.toString();
     }
 
+
     public void start() throws CDMServerException {
 
         /**
@@ -163,22 +160,15 @@ public class CDMServer {
          * has started but incorrectly, in which case we try to force stop it (if we can)
          * and start a new server.
          */
-        if(isRunning(1)) {
-            logger.info("[CDM-Server] Server already running @ " + host + ":" + port );
+        if(isStarted(1)) {
+            logger.info("[CDM-Server] Server already running @ " + host + ":" + httpPort );
             return;
-        } else if (isAvailable(1)){
-            logger.info("[CDM-Server] Server available, but not started correctly @ " + host + ":" + port );
-            logger.info("[CDM-Server] .... trying to force stop server @ " + host + ":" + port );
-            try {
-                stop(true);
-            } catch (Exception e) {
-                throw new CDMServerException("CDM Server could not be stopped : " + e.getMessage());
-            }
         }
 
         Thread t = new Thread() {
             @Override
             public void run() {
+
                 StringBuffer output = new StringBuffer();
                 try{
                     Process p;
@@ -193,19 +183,25 @@ public class CDMServer {
                     logger.info("[CDM-Server] Starting server with Command : " + command);
                     p = Runtime.getRuntime().exec(command);
 
-                    BufferedReader reader =
+                    BufferedReader inpReader =
                             new BufferedReader(new InputStreamReader(p.getInputStream()));
 
+                    BufferedReader errReader =
+                            new BufferedReader(new InputStreamReader(p.getErrorStream()));
+
                     String line = "";
-                    while ((line = reader.readLine())!= null) {
-                        logger.info("[CDM-Server] Start : " + line);
+                    while ((line = inpReader.readLine())!= null) {
+                        logger.info("[CDM-Server Start] : " + line);
+                    }
+
+                    while ((line = errReader.readLine())!= null) {
+                        logger.info("[CDM-Server Start] : " + line);
                     }
 
                 } catch (Exception e) {
                     e.printStackTrace();
                     cdmse = new CDMServerException(e);
                 }
-
             }
         };
 
@@ -213,8 +209,8 @@ public class CDMServer {
         cdmse = null;
         t.start();
 
-        if(isRunning(60)) {
-            logger.info("[CDM-Server] Started Server @ " + host + ":" + port );
+        if(isStarted(50)) {
+            logger.info("[CDM-Server] Server running @ " + host + ":" + httpPort );
         } else {
             logger.info("[CDM-Server] Server not started within given interval");
             // making sure to kill server if it is not started correctly
@@ -228,50 +224,11 @@ public class CDMServer {
 
     }
 
-    public boolean isAvailable(int checkingIntervals) throws CDMServerException {
-        int intervalsCount = 0;
-        do {
-            try {
-                Socket s = new Socket(host, port);
-                logger.info("[CDM-Server] Available @ " + host + ":" + port );
-                return true;
-            } catch (IOException ioe) {
 
-            }
-            try {
-                Thread.sleep(1000);
-            } catch (InterruptedException ie) {
-                throw new CDMServerException("Error checking CDM Server status", ie);
-            }
-            intervalsCount++;
-        } while (intervalsCount < checkingIntervals);
-
-        return false;
-    }
-
-    public boolean isStopped(int checkingIntervals) throws CDMServerException {
-        int intervalsCount = 0;
-        do {
-            try {
-                Socket s = new Socket(host, port);
-            } catch (IOException ioe) {
-                return true;
-            }
-            try {
-                Thread.sleep(1000);
-            } catch (InterruptedException ie) {
-                throw new CDMServerException("Error checking CDM Server status", ie);
-            }
-            intervalsCount++;
-        } while (intervalsCount < checkingIntervals);
-
-        return false;
-    }
-
-    public boolean isRunning(int checkingIntervals) throws CDMServerException  {
+    public boolean isStarted(int checkingIntervals) throws CDMServerException  {
         CdmRemoteSourceBase crsb = new CdmRemoteSourceBase("local-cdm-server",
                 host,
-                port,
+                httpPort,
                 contextPath,
                 null);
         int intervalsCount = 0;
@@ -282,7 +239,7 @@ public class CDMServer {
                 }
                 boolean check = crsb.checkConnection();
                 if(check) {
-                    logger.info("[CDM-Server] Running @ " + host + ":" + port );
+                    logger.info("[CDM-Server] Running @ " + host + ":" + httpPort );
                     return true;
                 }
             } catch (Exception e) {
@@ -301,19 +258,16 @@ public class CDMServer {
     public void stop() throws Exception {
         stop(false);
     }
+
     public void stop(boolean force) throws Exception {
 
         if(!force) {
-            if(!getInstance().isAvailable(1)) {
-                logger.info("[CDM-Server] Server already stopped @ " + host + ":" + port );
-                return;
-            }
-
-            if(getInstance().getKeepServerRunning()) {
-                logger.info("[CDM-Server] Server @ " + host + ":" + port + " is set to keep running");
+            if(!getInstance().isStarted(1)) {
+                logger.info("[CDM-Server] Server already stopped @ " + host + ":" + httpPort );
                 return;
             }
         }
+
         Thread t = new Thread() {
             @Override
             public void run() {
@@ -324,15 +278,25 @@ public class CDMServer {
                             + getStopServerArgs() + " --stop ";
                     logger.info("[CDM-Server] Stop Command : " + command);
                     p = Runtime.getRuntime().exec(command);
-                    p.waitFor();
-                    BufferedReader reader =
+
+                    BufferedReader inpReader =
                             new BufferedReader(new InputStreamReader(p.getInputStream()));
+
+                    BufferedReader errReader =
+                            new BufferedReader(new InputStreamReader(p.getErrorStream()));
+
                     String line = "";
-                    while ((line = reader.readLine())!= null) {
-                        logger.info("CDM-Server Stop : " + line + "\n");
+                    while ((line = inpReader.readLine())!= null) {
+                        logger.info("[CDM-Server Stop] : " + line);
+                    }
+
+                    while ((line = errReader.readLine())!= null) {
+                        logger.info("[CDM-Server Stop] : " + line);
                     }
+                    logger.info("CDM-Server Stopped : ");
                 } catch (Exception e) {
-                    e.printStackTrace();
+                    logger.info("[CDM-Server] Could not stop @ " + host + ":" + httpPort + ". Please kill it manually");
+
                 }
 
             }
@@ -341,10 +305,32 @@ public class CDMServer {
         t.setDaemon(true);
         t.start();
 
-        if(isStopped(5)) {
-            logger.info("[CDM-Server] Stopped Server @ " + host + ":" + port );
-        } else {
-            logger.info("[CDM-Server] Could not stop @ " + host + ":" + port + ". Please kill it manually");
+    }
+
+    public static void stopServerViaJMX(int jmxPort) throws CDMServerException  {
+        String JMX_URL = "service:jmx:rmi:///jndi/rmi://localhost:" + jmxPort + "/jmxrmi";
+        logger.warn("Shutting down Jetty instance ... ");
+
+        try {
+            JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(JMX_URL), null);
+            connector.connect(null);
+            MBeanServerConnection connection = connector.getMBeanServerConnection();
+            ObjectName objectName = new ObjectName("org.eclipse.jetty.server:type=server,id=0");
+            connection.invoke(objectName, "stop", null, null);
+            logger.warn("Shutdown command sent");
+        } catch (InstanceNotFoundException e) {
+            throw new CDMServerException(e);
+        } catch (MBeanException e) {
+            throw new CDMServerException(e);
+        } catch (ReflectionException e) {
+            throw new CDMServerException(e);
+        } catch (IOException e) {
+            throw new CDMServerException(e);
+        } catch (MalformedObjectNameException e) {
+            throw new CDMServerException(e);
         }
+
+
+
     }
 }