8022221: Intermittent test failures in sun/management/jmxremote/startstop/JMXStartStopTest.sh
authorjbachorik
Tue, 21 Jan 2014 09:15:46 +0100
changeset 22349 2aa385c1c4d8
parent 22348 8e8c84d9535f
child 22350 4143cdafa0d5
8022221: Intermittent test failures in sun/management/jmxremote/startstop/JMXStartStopTest.sh Reviewed-by: sla
jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java
jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java
jdk/test/sun/management/jmxremote/startstop/JMXStartStopDoSomething.java
jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java
jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.sh
--- a/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java	Tue Jan 07 12:17:36 2014 -0800
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/ProcessTools.java	Tue Jan 21 09:15:46 2014 +0100
@@ -32,6 +32,7 @@
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.concurrent.CountDownLatch;
 import java.util.Map;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
@@ -39,6 +40,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.function.Predicate;
+import java.util.function.Consumer;
 
 import sun.management.VMManagement;
 
@@ -70,9 +72,37 @@
     public static Process startProcess(String name,
                                        ProcessBuilder processBuilder)
     throws IOException {
+        return startProcess(name, processBuilder, null);
+    }
+
+    /**
+     * <p>Starts a process from its builder.</p>
+     * <span>The default redirects of STDOUT and STDERR are started</span>
+     * <p>It is possible to monitor the in-streams via the provided {@code consumer}
+     * @param name The process name
+     * @param consumer {@linkplain Consumer} instance to process the in-streams
+     * @param processBuilder The process builder
+     * @return Returns the initialized process
+     * @throws IOException
+     */
+    public static Process startProcess(String name,
+                                       ProcessBuilder processBuilder,
+                                       Consumer<String> consumer)
+    throws IOException {
         Process p = null;
         try {
-            p = startProcess(name, processBuilder, null, -1, TimeUnit.NANOSECONDS);
+            p = startProcess(
+                name,
+                processBuilder,
+                line -> {
+                    if (consumer != null) {
+                        consumer.accept(line);
+                    }
+                    return false;
+                },
+                -1,
+                TimeUnit.NANOSECONDS
+            );
         } catch (InterruptedException | TimeoutException e) {
             // can't ever happen
         }
@@ -111,25 +141,28 @@
 
         stdout.addPump(new LineForwarder(name, System.out));
         stderr.addPump(new LineForwarder(name, System.err));
-        final Phaser phs = new Phaser(1);
+        CountDownLatch latch = new CountDownLatch(1);
         if (linePredicate != null) {
-            stdout.addPump(new StreamPumper.LinePump() {
+            StreamPumper.LinePump pump = new StreamPumper.LinePump() {
                 @Override
                 protected void processLine(String line) {
-                    if (linePredicate.test(line)) {
-                        if (phs.getRegisteredParties() > 0) {
-                            phs.arriveAndDeregister();
-                        }
+                    if (latch.getCount() > 0 && linePredicate.test(line)) {
+                        latch.countDown();
                     }
                 }
-            });
+            };
+            stdout.addPump(pump);
+            stderr.addPump(pump);
         }
         Future<Void> stdoutTask = stdout.process();
         Future<Void> stderrTask = stderr.process();
 
         try {
             if (timeout > -1) {
-                phs.awaitAdvanceInterruptibly(0, timeout, unit);
+                long realTimeout = Math.round(timeout * Utils.TIMEOUT_FACTOR);
+                if (!latch.await(realTimeout, unit)) {
+                    throw new TimeoutException();
+                }
             }
         } catch (TimeoutException | InterruptedException e) {
             System.err.println("Failed to start a process (thread dump follows)");
--- a/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java	Tue Jan 07 12:17:36 2014 -0800
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java	Tue Jan 21 09:15:46 2014 +0100
@@ -59,6 +59,16 @@
      */
     public static final String JAVA_OPTIONS = System.getProperty("test.java.opts", "").trim();
 
+    /**
+    * Returns the value of 'test.timeout.factor' system property
+    * converted to {@code double}.
+    */
+    public static final double TIMEOUT_FACTOR;
+    static {
+        String toFactor = System.getProperty("test.timeout.factor", "1.0");
+       TIMEOUT_FACTOR = Double.parseDouble(toFactor);
+    }
+
     private Utils() {
         // Private constructor to prevent class instantiation
     }
--- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopDoSomething.java	Tue Jan 07 12:17:36 2014 -0800
+++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopDoSomething.java	Tue Jan 21 09:15:46 2014 +0100
@@ -21,37 +21,20 @@
  * questions.
  */
 
-import java.io.File;
+import java.io.IOException;
+import jdk.testlibrary.ProcessTools;
 
 public class JMXStartStopDoSomething {
-
-    private static final String lockFileName = "JMXStartStop.lck";
-
-    public static void doSomething() {
-        try {
-            File lockFile = new File(lockFileName);
-            lockFile.createNewFile();
-
-            while(lockFile.exists()) {
-                long datetime = lockFile.lastModified();
-                long epoch = System.currentTimeMillis()/1000;
-
-                // Don't allow test app to run more than an hour
-                if (epoch - datetime > 3600) {
-                    System.err.println("Lock is too old. Aborting");
-                    return;
-                }
-                Thread.sleep(500);
-            }
-
-        } catch (Throwable e) {
-            System.err.println("Something bad happens:" +e);
-        }
+    public static void doSomething() throws IOException{
+        int r = System.in.read();
+        System.out.println("read: " + r);
     }
 
     public static void main(String args[]) throws Exception {
-        System.err.println("main enter");
+        System.out.println("pid:" + ProcessTools.getProcessId());
+        System.out.println("main enter");
+        System.out.flush();
         doSomething();
-        System.err.println("main exit");
+        System.out.println("main exit");
     }
 }
--- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java	Tue Jan 07 12:17:36 2014 -0800
+++ b/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.java	Tue Jan 21 09:15:46 2014 +0100
@@ -22,45 +22,60 @@
  */
 
 import java.io.File;
-import java.io.FileInputStream;
-import java.io.FilenameFilter;
 import java.io.IOException;
-import java.io.InputStream;
+import java.lang.reflect.Method;
+import java.net.ConnectException;
+import java.rmi.NoSuchObjectException;
 import java.rmi.registry.LocateRegistry;
 import java.rmi.registry.Registry;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Map;
-import java.util.Properties;
+import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
 
 import javax.management.*;
 import javax.management.remote.*;
+import javax.net.ssl.SSLHandshakeException;
 
-import sun.management.AgentConfigurationError;
-import sun.management.jmxremote.ConnectorBootstrap;
-
-public class JMXStartStopTest {
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.JDKToolLauncher;
 
-    static boolean verbose = false;
+/**
+ * @test
+ * @bug 7110104
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.ProcessTools
+ * @build jdk.testlibrary.JDKToolLauncher
+ * @build jdk.testlibrary.Utils
+ * @build JMXStartStopTest JMXStartStopDoSomething
+ * @run main/othervm JMXStartStopTest
+ * @summary Makes sure that enabling/disabling the management agent through
+ *          JCMD achieves the desired results
+ */
+public class JMXStartStopTest {
+    private static final String TEST_JDK = System.getProperty("test.jdk");
+    private static final String TEST_SRC = System.getProperty("test.src");
 
-    static void dbg_print(String msg){
+    private static final boolean verbose = false;
+
+    private static void dbg_print(String msg){
         if (verbose) {
-            System.err.println("DBG: " +msg);
+            System.out.println("DBG: " +msg);
         }
     }
 
-    static void dbg_print(String msg, Throwable ex){
-        if (verbose) {
-            System.err.println("DBG: " + msg + " " + ex.getMessage() );
-            ex.printStackTrace(System.err);
-        }
-    }
-
-    public static int listMBeans(MBeanServerConnection server, ObjectName pattern, QueryExp query)
+    private static int listMBeans(MBeanServerConnection server,
+                                  ObjectName pattern,
+                                  QueryExp query)
     throws Exception {
 
         Set names = server.queryNames(pattern,query);
@@ -72,10 +87,9 @@
             MBeanAttributeInfo[] attrs = info.getAttributes();
             if (attrs == null)
                 continue;
-
-            for (int j=0; j<attrs.length; j++) {
-                if (attrs[j].isReadable()) {
-                    Object o = server.getAttribute(name,attrs[j].getName());
+            for (MBeanAttributeInfo attr : attrs) {
+                if (attr.isReadable()) {
+                    Object o = server.getAttribute(name, attr.getName());
                 }
             }
         }
@@ -83,11 +97,10 @@
     }
 
 
-    public void run_local(String strPid)
+    private static void testConnectLocal(int pid)
     throws Exception {
 
         String jmxUrlStr = null;
-        int pid = Integer.parseInt(strPid);
 
         try {
             jmxUrlStr = sun.management.ConnectorAddressLink.importFrom(pid);
@@ -106,8 +119,8 @@
 
             int count = listMBeans(conn,pattern,null);
             if (count == 0)
-                throw new Exception("Expected at least one matching "+ "MBean for "+pattern);
-
+                throw new Exception("Expected at least one matching "+
+                                    "MBean for "+pattern);
 
         } catch (IOException e) {
             dbg_print("Cannot find process : " + pid);
@@ -115,20 +128,40 @@
         }
     }
 
-    public void run(String args[]) throws Exception {
+    private static void testNoConnect(int port) throws Exception {
+        testNoConnect(port, 0);
+    }
+
+    private static void testNoConnect(int port, int rmiPort) throws Exception {
+        try {
+            testConnect(port, rmiPort);
+            throw new Exception("Didn't expect the management agent running");
+        } catch (Exception e) {
+            Throwable t = e;
+            while (t != null) {
+                if (t instanceof NoSuchObjectException ||
+                    t instanceof ConnectException ||
+                    t instanceof SSLHandshakeException) {
+                    break;
+                }
+                t = t.getCause();
+            }
+            if (t == null) {
+                throw new Exception("Unexpected exception", e);
+            }
+        }
+    }
+
+    private static void testConnect(int port) throws Exception {
+        testConnect(port, 0);
+    }
+
+    private static void testConnect(int port, int rmiPort) throws Exception {
 
         dbg_print("RmiRegistry lookup...");
 
-        int port = 4567;
-        if (args != null && args.length > 0) {
-            port = Integer.parseInt(args[0]);
-        }
         dbg_print("Using port: " + port);
 
-        int rmiPort = 0;
-        if (args != null && args.length > 1) {
-            rmiPort = Integer.parseInt(args[1]);
-        }
         dbg_print("Using rmi port: " + rmiPort);
 
         Registry registry = LocateRegistry.getRegistry(port);
@@ -140,8 +173,13 @@
         }
 
         String jmxUrlStr = (rmiPort != 0) ?
-                           String.format("service:jmx:rmi://localhost:%d/jndi/rmi://localhost:%d/jmxrmi", rmiPort, port) :
-                           String.format("service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",port);
+            String.format(
+                "service:jmx:rmi://localhost:%d/jndi/rmi://localhost:%d/jmxrmi",
+                rmiPort,
+                port) :
+            String.format(
+                "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
+                port);
 
         JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
         Map m = new HashMap();
@@ -153,29 +191,632 @@
 
         int count = listMBeans(conn,pattern,null);
         if (count == 0)
-            throw new Exception("Expected at least one matching "+ "MBean for "+pattern);
+            throw new Exception("Expected at least one matching " +
+                                "MBean for " + pattern);
+    }
+
+    private static class Failure {
+        private final Throwable cause;
+        private final String msg;
+
+        public Failure(Throwable cause, String msg) {
+            this.cause = cause;
+            this.msg = msg;
+        }
+
+        public Failure(String msg) {
+            this(null, msg);
+        }
+
+        public Throwable getCause() {
+            return cause;
+        }
+
+        public String getMsg() {
+            return msg;
+        }
+
+        @Override
+        public int hashCode() {
+            int hash = 7;
+            hash = 97 * hash + Objects.hashCode(this.cause);
+            hash = 97 * hash + Objects.hashCode(this.msg);
+            return hash;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (obj == null) {
+                return false;
+            }
+            if (getClass() != obj.getClass()) {
+                return false;
+            }
+            final Failure other = (Failure) obj;
+            if (!Objects.equals(this.cause, other.cause)) {
+                return false;
+            }
+            if (!Objects.equals(this.msg, other.msg)) {
+                return false;
+            }
+            return true;
+        }
+
+        @Override
+        public String toString() {
+            if (cause != null) {
+                return msg + "\n" + cause;
+            } else {
+                return msg;
+            }
+        }
+    }
+
+    private static List<Failure> failures = new ArrayList<>();
+
+    public static void main(String args[]) throws Exception {
+        for (int i=0;i<3;i++) {
+            System.out.println("=== PASS " + i + " ===");
+            for (Method m : JMXStartStopTest.class.getDeclaredMethods()) {
+                if (m.getName().startsWith("test_")) {
+                    try {
+                        m.invoke(null);
+                        System.out.println("=== PASSED\n");
+                    } catch (Throwable e) {
+                        failures.add(new Failure(e, m.getName() + " failed"));
+                    }
+                }
+            }
+
+            if (!failures.isEmpty()) {
+                for(Failure f : failures) {
+                    System.err.println(f.getMsg());
+                    f.getCause().printStackTrace(System.err);
+                }
+                throw new Error();
+            }
+        }
+    }
+
+    /**
+     * Retrieves the PID of the test application using JCMD
+     * @return The PID of the test application
+     * @throws InterruptedException
+     * @throws IOException
+     */
+    private static String getPID() throws InterruptedException, IOException {
+        final AtomicReference<String> pid = new AtomicReference<>();
+        jcmd(
+            null,
+            line -> {
+                if (line.endsWith("JMXStartStopDoSomething")) {
+                    pid.set(line.split(" ")[0]);
+                }
+            }
+        );
+        return pid.get();
+    }
+
+    private static class Something {
+        private Process p;
+        private final ProcessBuilder pb;
+        private final String name;
+        private final AtomicBoolean started = new AtomicBoolean(false);
+        private volatile int pid = -1;
+
+        public Something(ProcessBuilder pb, String name) {
+            this.pb = pb;
+            this.name = name;
+        }
+
+        public synchronized void start() throws InterruptedException, IOException, TimeoutException {
+            if (started.compareAndSet(false, true)) {
+                try {
+                    p = ProcessTools.startProcess(
+                        "JMXStartStopDoSomething",
+                        pb,
+                        (line) -> {
+                            if (line.toLowerCase().startsWith("pid:")) {
+                                pid = Integer.parseInt(line.split("\\:")[1]);
+                            }
+                            return line.equals("main enter");
+                        },
+                        5,
+                        TimeUnit.SECONDS
+                    );
+                } catch (TimeoutException e) {
+                    p.destroy();
+                    p.waitFor();
+                    throw e;
+                }
+            }
+        }
+
+        public int getPid() {
+            return pid;
+        }
+
+        public synchronized void stop()
+            throws IOException, InterruptedException {
+            if (started.compareAndSet(true, false)) {
+                p.getOutputStream().write(0);
+                p.getOutputStream().flush();
+                int ec = p.waitFor();
+                if (ec != 0) {
+                    StringBuilder msg = new StringBuilder();
+                    msg.append("Test application '").append(name);
+                    msg.append("' failed with exit code: ");
+                    msg.append(ec);
+
+                    failures.add(new Failure(msg.toString()));
+                }
+            }
+        }
+    }
+
+    /**
+     * Runs the test application "JMXStartStopDoSomething"
+     * @param name Test run name
+     * @param args Additional arguments
+     * @return Returns a {@linkplain Something} instance representing the run
+     * @throws IOException
+     * @throws InterruptedException
+     * @throws TimeoutException
+     */
+    private static Something doSomething(String name, String ... args)
+    throws Exception {
+        List<String> pbArgs = new ArrayList<>(Arrays.asList(
+            "-cp",
+            System.getProperty("test.class.path")
+        ));
+        pbArgs.addAll(Arrays.asList(args));
+        pbArgs.add("JMXStartStopDoSomething");
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+            pbArgs.toArray(new String[pbArgs.size()])
+        );
+        Something s = new Something(pb, name);
+        s.start();
+        return s;
+    }
+
+    /**
+     * Run the "jcmd" command
+     *
+     * @param command Command with parameters; space separated string
+     * @throws IOException
+     * @throws InterruptedException
+     */
+    private static void jcmd(String ... command) throws IOException, InterruptedException {
+        if (command.length == 0) {
+            jcmd(null, (Consumer<String>)null);
+        } else {
+            jcmd(null, command);
+        }
+    }
+
+    /**
+     * Run the "jcmd" command
+     *
+     * @param c {@linkplain Consumer} instance; may be null
+     * @param command Command with parameters; space separated string
+     * @throws IOException
+     * @throws InterruptedException
+     */
+    private static void jcmd(Consumer<String> c, String ... command) throws IOException, InterruptedException {
+        jcmd("JMXStartStopDoSomething", c, command);
+    }
+
+    /**
+     * Run the "jcmd" command
+     * @param target The target application name (or PID)
+     * @param c {@linkplain Consumer} instance; may be null
+     * @param command Command with parameters; space separated string
+     * @throws IOException
+     * @throws InterruptedException
+     */
+    private static void jcmd(String target, final Consumer<String> c, String ... command) throws IOException, InterruptedException {
+        dbg_print("[jcmd] " + (command.length > 0 ? command[0] : "list"));
+
+        JDKToolLauncher l = JDKToolLauncher.createUsingTestJDK("jcmd");
+        l.addToolArg(target);
+        for(String cmd : command) {
+            l.addToolArg(cmd);
+        }
+        Process p = ProcessTools.startProcess(
+            "jcmd",
+            new ProcessBuilder(l.getCommand()),
+            c
+        );
+
+        p.waitFor();
+        dbg_print("[jcmd] --------");
+    }
+
+    private static final String CMD_STOP = "ManagementAgent.stop";
+    private static final String CMD_START= "ManagementAgent.start";
+    private static final String CMD_START_LOCAL = "ManagementAgent.start_local";
+    private static final int port1 = 50234;
+    private static final int port2 = 50235;
+
+    private static void test_01() throws Exception {
+        // Run an app with JMX enabled stop it and
+        // restart on other port
+
+        System.out.println("**** Test one ****");
+
+        Something s = doSomething(
+            "test_01",
+            "-Dcom.sun.management.jmxremote.port=" + port1,
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=false");
+
+        try {
+            testConnect(port1);
+
+            jcmd(CMD_STOP);
+            testNoConnect(port1);
+
+            jcmd(CMD_START, "jmxremote.port=" + port2);
+            testConnect(port2);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_02() throws Exception {
+        // Run an app without JMX enabled
+        // start JMX by jcmd
+
+        System.out.println("**** Test two ****");
+
+        Something s = doSomething("test_02");
+        try {
+            jcmd(CMD_START,
+                "jmxremote.port=" + port1,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false");
+
+            testConnect(port1);
+        } finally {
+            s.stop();
+        }
     }
 
+    private static void test_03() throws Exception {
+        // Run an app without JMX enabled
+        // start JMX by jcmd on one port than on other one
 
-    public static void main(String args[]) {
-        JMXStartStopTest manager = new JMXStartStopTest();
+        System.out.println("**** Test three ****");
+
+        Something s = doSomething("test_03");
+        try {
+            jcmd(CMD_START,
+                "jmxremote.port=" + port1,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false");
+
+            // Second agent shouldn't start
+            jcmd(CMD_START,
+                "jmxremote.port=" + port2,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false");
+
+            // First agent should connect
+            testConnect(port1);
+
+            // Second agent should not connect
+            testNoConnect(port2);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_04() throws Exception {
+        // Run an app without JMX enabled
+        // start JMX by jcmd on one port, specify rmi port explicitly
+
+        System.out.println("**** Test four ****");
+
+        Something s = doSomething("test_04");
+
+        try {
+            jcmd(CMD_START,
+                 "jmxremote.port=" + port1,
+                 "jmxremote.rmi.port=" + port2,
+                 "jmxremote.authenticate=false",
+                 "jmxremote.ssl=false");
+
+            testConnect(port1, port2);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_05() throws Exception {
+        // Run an app without JMX enabled, it will enable local server
+        // but should leave remote server disabled
+
+        System.out.println("**** Test five ****");
+
+        Something s = doSomething("test_05");
         try {
-            if (args!=null && args[0].equals("local")) {
-                manager.run_local(args[1]);
-            } else {
-                manager.run(args);
+            jcmd(CMD_START_LOCAL);
+
+            testNoConnect(port1);
+            testConnectLocal(s.getPid());
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_06() throws Exception {
+        // Run an app without JMX enabled
+        // start JMX by jcmd on one port, specify rmi port explicitly
+        // attempt to start it again
+        // 1) with the same port
+        // 2) with other port
+        // 3) attempt to stop it twice
+        // Check for valid messages in the output
+
+        System.out.println("**** Test six ****");
+
+        Something s = doSomething("test_06");
+
+        try {
+            jcmd(CMD_START,
+                 "jmxremote.port=" + port1,
+                 "jmxremote.authenticate=false",
+                 "jmxremote.ssl=false");
+
+            testConnect(port1, port2);
+
+            final boolean[] checks = new boolean[3];
+            jcmd(
+                line -> {
+                    if (line.equals("java.lang.RuntimeException: Invalid agent state")) {
+                        checks[0] = true;
+                    }
+                },
+                CMD_START,
+                 "jmxremote.port=" + port1,
+                 "jmxremote.authenticate=false",
+                 "jmxremote.ssl=false");
+
+            jcmd(
+                line -> {
+                    if (line.equals("java.lang.RuntimeException: Invalid agent state")) {
+                        checks[1] = true;
+                    }
+                },
+                CMD_START,
+                "jmxremote.port=" + port2,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false");
+
+            jcmd(CMD_STOP);
+            jcmd(CMD_STOP);
+
+            jcmd(
+                line -> {
+                    if (line.contains("Port already in use: 22")) {
+                        checks[2] = true;
+                    }
+                },
+                CMD_START,
+                "jmxremote.port=22",
+                "jmxremote.rmi.port=" + port2,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false");
+            if (!checks[0]) {
+                throw new Exception("Starting agent on port " + port1 + " should " +
+                                    "report an invalid agent state");
             }
-        } catch (RuntimeException r) {
-            dbg_print("No connection: ", r);
-            System.out.print("NO_CONN");
-            System.exit(1);
-        } catch (Throwable t) {
-            dbg_print("No connection: ", t);
-            System.out.print("NO_CONN");
-            System.exit(2);
+            if (!checks[1]) {
+                throw new Exception("Starting agent on poprt " + port2 + " should " +
+                                    "report an invalid agent state");
+            }
+            if (!checks[2]) {
+                throw new Exception("Starting agent on port 22 should " +
+                                    "report port in use");
+            }
+        } finally {
+            s.stop();
         }
-        System.out.print("OK_CONN");
-        System.exit(0);
+    }
+
+    private static void test_07() throws Exception {
+        // Run an app without JMX enabled, but with some properties set
+        // in command line.
+        // make sure these properties overriden corectly
+
+        System.out.println("**** Test seven ****");
+
+        Something s = doSomething(
+            "test_07",
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=true");
+
+        try {
+            testNoConnect(port1);
+            jcmd(
+                CMD_START,
+                "jmxremote.port=" + port2,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false"
+            );
+            testConnect(port2);
+        } finally {
+            s.stop();
+        }
     }
 
+    private static void test_08() throws Exception {
+        // Run an app with JMX enabled and with some properties set
+        // in command line.
+        // stop JMX agent and then start it again with different property values
+        // make sure these properties overriden corectly
+
+        System.out.println("**** Test eight ****");
+
+        Something s = doSomething(
+            "test_08",
+            "-Dcom.sun.management.jmxremote.port=" + port1,
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=true");
+
+        try {
+            testNoConnect(port1);
+
+            jcmd(CMD_STOP);
+
+            testNoConnect(port1);
+
+            jcmd(
+                CMD_START,
+                "jmxremote.port=" + port2,
+                "jmxremote.authenticate=false",
+                "jmxremote.ssl=false"
+            );
+
+            testConnect(port2);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_09() throws Exception {
+        // Run an app with JMX enabled and with some properties set
+        // in command line.
+        // stop JMX agent and then start it again with different property values
+        // specifing some property in management config file and some of them
+        // in command line
+        // make sure these properties overriden corectly
+
+        System.out.println("**** Test nine ****");
+
+        Something s = doSomething("test_09",
+            "-Dcom.sun.management.config.file=" +
+                TEST_SRC + File.separator + "management_cl.properties",
+            "-Dcom.sun.management.jmxremote.authenticate=false"
+        );
+
+        try {
+            testNoConnect(port1);
+
+            jcmd(CMD_STOP);
+
+            testNoConnect(port1);
+
+            jcmd(CMD_START,
+                "config.file=" + TEST_SRC + File.separator +
+                    "management_jcmd.properties",
+                "jmxremote.authenticate=false",
+                "jmxremote.port=" + port2
+            );
+
+            testConnect(port2);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_10() throws Exception {
+        // Run an app with JMX enabled and with some properties set
+        // in command line.
+        // stop JMX agent and then start it again with different property values
+        // stop JMX agent again and then start it without property value
+        // make sure these properties overriden corectly
+
+        System.out.println("**** Test ten ****");
+
+        Something s = doSomething(
+            "test_10",
+            "-Dcom.sun.management.jmxremote.port=" + port1,
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=true");
+
+        try {
+            testNoConnect(port1);
+
+            jcmd(CMD_STOP);
+            jcmd(CMD_START,
+                "jmxremote.ssl=false",
+                "jmxremote.port=" + port1
+            );
+            testConnect(port1);
+
+            jcmd(CMD_STOP);
+            jcmd(CMD_START,
+                "jmxremote.port=" + port1
+            );
+
+            testNoConnect(port1);
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_11() throws Exception {
+        // Run an app with JMX enabled
+        // stop remote agent
+        // make sure local agent is not affected
+
+        System.out.println("**** Test eleven ****");
+
+        Something s = doSomething(
+            "test_11",
+            "-Dcom.sun.management.jmxremote.port=" + port1,
+            "-Dcom.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=false");
+        try {
+            testConnect(port1);
+            jcmd(CMD_STOP);
+            testConnectLocal(s.getPid());
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_12() throws Exception {
+        // Run an app with JMX disabled
+        // start local agent only
+
+        System.out.println("**** Test twelve ****");
+
+        Something s = doSomething("test_12");
+
+        try {
+            testNoConnect(port1);
+            jcmd(CMD_START + "_local");
+
+            testConnectLocal(s.getPid());
+
+        } finally {
+            s.stop();
+        }
+    }
+
+    private static void test_13() throws Exception {
+        // Run an app with -javaagent make sure it works as expected -
+        // system properties are ignored
+
+        System.out.println("**** Test fourteen ****");
+
+        String agent = TEST_JDK + "/jre/lib/management-agent.jar";
+        if (!new File(agent).exists()) {
+            agent = TEST_JDK + "/lib/management-agent.jar";
+        }
+
+        Something s = doSomething("test_14",
+            "-javaagent:" + agent + "=com.sun.management.jmxremote.port=" +
+                port1 + ",com.sun.management.jmxremote.authenticate=false",
+            "-Dcom.sun.management.jmxremote.ssl=false"
+        );
+
+        try {
+            testNoConnect(port1);
+        } finally {
+            s.stop();
+        }
+    }
 }
--- a/jdk/test/sun/management/jmxremote/startstop/JMXStartStopTest.sh	Tue Jan 07 12:17:36 2014 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,579 +0,0 @@
-#!/bin/sh
-
-# Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-# 
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-# 
-# This code 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 General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-# 
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-
-# @test
-# @bug 7110104
-# @build JMXStartStopTest JMXStartStopDoSomething
-# @run shell JMXStartStopTest.sh --jtreg --no-compile
-# @summary No word Failed expected in the test output
-
-_server=no
-_jtreg=no
-_compile=yes
-_testsuite="01,02,03,04,05,06,07,08,09,10,11,12,13"
-_port_one=50234
-_port_two=50235
-
-
-_testclasses=".classes"
-_testsrc=`pwd`
-
-_logname=".classes/output.txt"
-_lockFileName="JMXStartStop.lck"
-
-_compile(){
-
-    if [ ! -d ${_testclasses} ]
-    then
-      mkdir -p ${_testclasses} 
-    fi   
-
-    rm -f ${_testclasses}/JMXStartStopTest.class
-
-    # Compile testcase
-    ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d ${_testclasses} \
-	JMXStartStopDoSomething.java JMXStartStopTest.java 
-
-    if [ ! -f ${_testclasses}/JMXStartStopTest.class ]
-    then
-      echo "ERROR: Can't compile"
-      exit -1
-    fi
-}
-
-_app_start(){
-  ${TESTJAVA}/bin/java ${TESTVMOPTS} $* -cp ${_testclasses} JMXStartStopDoSomething  >> ${_logname} 2>&1 &
-
-  x=0
-  while [ ! -f ${_lockFileName} ]
-  do
-     if [ $x -gt 20 ]
-     then
-        echo "ERROR: Test app not started"
-        if [ "${_jtreg}" = "yes" ]
-        then
-           exit -1
-        fi   
-     fi    
-        
-     echo "Waiting JMXStartStopDoSomething to start: $x"
-     x=`expr $x + 1`
-     sleep 1
-  done
-}
-
-_get_pid(){
-    ${COMPILEJAVA}/bin/jps ${TESTTOOLVMOPTS} | sed -n "/JMXStartStopDoSomething/s/ .*//p"
-}
-
-_app_stop(){
-  rm ${_lockFileName}
-
-  # wait until VM is actually shuts down
-  while true 
-  do
-    npid=`_get_pid`
-    if [ "${npid}" = "" ] 
-    then
-      break
-    fi
-    sleep 1
-  done 
-}
-
-_exit_on_jtreg(){
-  # Stop on first failed test under jtreg
-  if [ "${_jtreg}" = "yes" ]
-  then
-      _app_stop
-      exit -1
-  fi
-}
-
-_testme(){
-  ${TESTJAVA}/bin/java ${TESTVMOPTS} -cp ${_testclasses} JMXStartStopTest $*
-}   
-
-  
-_jcmd(){
-  ${TESTJAVA}/bin/jcmd ${TESTTOOLVMOPTS} JMXStartStopDoSomething $* > /dev/null 2>/dev/null
-} 
-
-_echo(){
-    echo "$*"
-    echo "$*" >> ${_logname}
-}
-   
-# ============= TESTS ======================================
-   
-test_01(){
-# Run an app with JMX enabled stop it and 
-# restart on other port
-        
-    _echo "**** Test one ****"      
-
-    _app_start  -Dcom.sun.management.jmxremote.port=$1 \
-                -Dcom.sun.management.jmxremote.authenticate=false \
-                -Dcom.sun.management.jmxremote.ssl=false 
-
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.stop
-
-    res2=`_testme $1`
-
-    _jcmd ManagementAgent.start jmxremote.port=$2
-
-    res3=`_testme $2`
-
-    if [ "${res1}" = "OK_CONN" -a "${res2}" = "NO_CONN" -a "${res3}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(OK):${res1} r2(NO):${res2} r3(OK):${res3}"
-        _exit_on_jtreg
-    fi
-
-    _app_stop
-}  
-   
-test_02(){
-# Run an app without JMX enabled 
-# start JMX by jcmd
-
-    _echo "**** Test two ****"      
-    _app_start  
-
-    _jcmd ManagementAgent.start jmxremote.port=$1 jmxremote.authenticate=false jmxremote.ssl=false 
-
-    res1=`_testme $1`
-
-    if [ "${res1}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(OK):${res1}"
-        _exit_on_jtreg
-    fi
-    _app_stop
-}   
-   
-test_03(){
-# Run an app without JMX enabled 
-# start JMX by jcmd on one port than on other one
-
-    _echo "**** Test three ****"        
-    _app_start  
-
-    _jcmd ManagementAgent.start jmxremote.port=$1 jmxremote.authenticate=false jmxremote.ssl=false 
-
-# Second agent shouldn't start
-    _jcmd ManagementAgent.start jmxremote.port=$2 jmxremote.authenticate=false jmxremote.ssl=false
-
-# First agent should connect
-    res1=`_testme $1`
-
-    if [ "${res1}" = "OK_CONN" ] 
-    then
-        _echo "Passed $1"
-    else
-        _echo "Failed r1(NO):${res1}"
-        _exit_on_jtreg
-    fi
-
-#Second agent shouldn't connect
-    res1=`_testme $2`
-
-    if [ "${res1}" = "NO_CONN" ] 
-    then
-        _echo "Passed $2"
-    else
-        _echo "Failed r1(OK):${res1}"
-        _exit_on_jtreg
-    fi
-
-    _app_stop
-}   
-   
-test_04(){
-# Run an app without JMX enabled 
-# start JMX by jcmd on one port, specify rmi port explicitly
-
-    _echo "**** Test four ****"     
-    _app_start  
-
-    _jcmd ManagementAgent.start jmxremote.port=$1 jmxremote.rmi.port=$2 jmxremote.authenticate=false jmxremote.ssl=false 
-
-# First agent should connect
-    res1=`_testme $1 $2`
-
-    if [ "${res1}" = "OK_CONN" ] 
-    then
-        _echo "Passed $1 $2"
-    else
-        _echo "Failed r1(NO):${res1}"
-        _exit_on_jtreg
-    fi
-
-    _app_stop
-}   
-
-test_05(){
-# Run an app without JMX enabled, it will enable local server
-# but should leave remote server disabled  
-
-    _echo "**** Test five ****"     
-    _app_start  
-
-    _jcmd ManagementAgent.start jmxremote=1 
-
-    # First agent should connect
-    res1=`_testme $1`
-
-    if [ "${res1}" = "NO_CONN" ] 
-    then
-        _echo "Passed $1 $2"
-    else
-        _echo "Failed r1(OK):${res1}"
-        _exit_on_jtreg
-    fi
-
-    _app_stop
-}   
-
-test_06(){
-# Run an app without JMX enabled 
-# start JMX by jcmd on one port, specify rmi port explicitly
-# attempt to start it again
-# 1) with the same port 
-# 2) with other port
-# 3) attempt to stop it twice
-# Check for valid messages in the output    
-
-    _echo "**** Test six ****"      
-    _app_start  
-
-    _jcmd ManagementAgent.start jmxremote.port=$1 jmxremote.authenticate=false jmxremote.ssl=false 
-
-    # First agent should connect
-    res1=`_testme $1 $2`
-
-    if [ "${res1}" = "OK_CONN" ] 
-    then
-        _echo "Passed $1 $2"
-    else
-        _echo "Failed r1(NO):${res1}"
-        _exit_on_jtreg
-    fi
-
-    _jcmd ManagementAgent.start jmxremote.port=$1 jmxremote.authenticate=false jmxremote.ssl=false 
-
-    _jcmd ManagementAgent.start jmxremote.port=$2 jmxremote.authenticate=false jmxremote.ssl=false 
-
-    _jcmd ManagementAgent.stop
-
-    _jcmd ManagementAgent.stop
-
-    _jcmd ManagementAgent.start jmxremote.port=22 jmxremote.rmi.port=$2 jmxremote.authenticate=false jmxremote.ssl=false 
-
-    _app_stop
-}   
-
-test_07(){
-# Run an app without JMX enabled, but with some properties set 
-# in command line.
-# make sure these properties overriden corectly 
-
-    _echo "**** Test seven ****"        
-
-    _app_start   -Dcom.sun.management.jmxremote.authenticate=false \
-                 -Dcom.sun.management.jmxremote.ssl=true 
-
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.start jmxremote.port=$2 jmxremote.authenticate=false jmxremote.ssl=false
-
-    res2=`_testme $2`
-
-    if [ "${res1}" = "NO_CONN" -a "${res2}" = "OK_CONN" ] 
-    then
-        echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1} r2(OK):${res2}"
-        _exit_on_jtreg
-    fi
-
-    _app_stop
-}   
-
-test_08(){
-# Run an app with JMX enabled and with some properties set 
-# in command line.
-# stop JMX agent and then start it again with different property values
-# make sure these properties overriden corectly 
-
-    _echo "**** Test eight ****"        
-
-    _app_start  -Dcom.sun.management.jmxremote.port=$1 \
-                -Dcom.sun.management.jmxremote.authenticate=false \
-                -Dcom.sun.management.jmxremote.ssl=true 
-
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.stop
-
-    res2=`_testme $1`
-
-    _jcmd ManagementAgent.start jmxremote.port=$2 jmxremote.authenticate=false jmxremote.ssl=false
-
-    res3=`_testme $2`
-
-    if [ "${res1}" = "NO_CONN" -a "${res2}" = "NO_CONN" -a "${res3}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1} r2(NO):${res2} r3(OK):${res3}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-test_09(){
-# Run an app with JMX enabled and with some properties set 
-# in command line.
-# stop JMX agent and then start it again with different property values
-# specifing some property in management config file and some of them
-# in command line
-# make sure these properties overriden corectly 
-
-    _echo "**** Test nine ****"     
-
-    _app_start -Dcom.sun.management.config.file=${_testsrc}/management_cl.properties \
-               -Dcom.sun.management.jmxremote.authenticate=false 
-
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.stop
-
-    res2=`_testme $1`
-
-    _jcmd ManagementAgent.start config.file=${_testsrc}/management_jcmd.properties \
-                                jmxremote.authenticate=false jmxremote.port=$2
-
-    res3=`_testme $2`
-
-    if [ "${res1}" = "NO_CONN" -a "${res2}" = "NO_CONN" -a "${res3}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1} r2(NO):${res2} r3(OK):${res3}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-test_10(){
-# Run an app with JMX enabled and with some properties set 
-# in command line.
-# stop JMX agent and then start it again with different property values
-# stop JMX agent again and then start it without property value
-# make sure these properties overriden corectly 
-
-    _echo "**** Test ten ****"      
-
-    _app_start  -Dcom.sun.management.jmxremote.port=$1 \
-                -Dcom.sun.management.jmxremote.authenticate=false \
-                -Dcom.sun.management.jmxremote.ssl=true 
-
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.stop
-    _jcmd ManagementAgent.start jmxremote.ssl=false jmxremote.port=$1
-
-
-    res2=`_testme $1`
-
-    _jcmd ManagementAgent.stop
-    _jcmd ManagementAgent.start jmxremote.port=$1
-
-    res3=`_testme $1`
-
-    if [ "${res1}" = "NO_CONN" -a "${res2}" = "OK_CONN" -a "${res3}" = "NO_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1} r2(OK):${res2} r3(NO):${res3}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-test_11(){
-# Run an app with JMX enabled 
-# stop remote agent 
-# make sure local agent is not affected
-
-    _echo "**** Test eleven ****"       
-
-    _app_start  -Dcom.sun.management.jmxremote.port=$2 \
-                -Dcom.sun.management.jmxremote.authenticate=false \
-                -Dcom.sun.management.jmxremote.ssl=false 
-      
-    res1=`_testme $2`
-
-    _jcmd ManagementAgent.stop
-
-    pid=`${COMPILEJAVA}/bin/jps ${TESTTOOLVMOPTS} | sed -n "/JMXStartStopDoSomething/s/ .*//p"`
-    res2=`_testme local ${pid}`
-
-    if [ "${res1}" = "OK_CONN" -a "${res2}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(OK):${res1} r2(OK):${res2}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-test_12(){
-# Run an app with JMX disabled 
-# start local agent only
-
-    _echo "**** Test twelve ****"       
-
-    _app_start 
-      
-    res1=`_testme $1`
-
-    _jcmd ManagementAgent.start_local
-
-    pid=`_get_pid`
-    if [ "x${pid}" = "x" ]
-    then
-        res2="NO_CONN"
-    else
-        res2=`_testme local ${pid}`
-    fi
-
-    if [ "${res1}" = "NO_CONN" -a "${res2}" = "OK_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1} r2(OK):${res2}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-test_13(){
-# Run an app with -javaagent make sure it works as expected - system properties are ignored
-
-    _echo "**** Test thirteen ****"       
-			   
-    AGENT="${TESTJAVA}/jre/lib/management-agent.jar"
-    if [ ! -f ${AGENT} ]
-    then
-        AGENT="${TESTJAVA}/lib/management-agent.jar"
-    fi
-
-    _app_start -javaagent:${AGENT}=com.sun.management.jmxremote.port=$1,com.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false 
-      
-    res1=`_testme $1`
-
-    if [ "${res1}" = "NO_CONN" ] 
-    then
-        _echo "Passed"
-    else
-        _echo "Failed r1(NO):${res1}"
-        _exit_on_jtreg
-    fi
- 
-    _app_stop
-}   
-
-# ============= MAIN =======================================
-
-if [ "x${TESTJAVA}" = "x" ]
-then
-  echo "TESTJAVA env have to be set"
-  exit
-fi
-
-if [ ! -x "${TESTJAVA}/bin/jcmd" ]
-then
-  echo "${TESTJAVA}/bin/jcmd"
-  echo "Doesn't exist or not an executable"
-  exit
-fi
-
-
-#------------------------------------------------------------------------------
-# reading parameters 
-
-for parm in "$@"  
-do
-   case $parm in
-  --jtreg)        _jtreg=yes    ;;
-  --no-compile)   _compile=no   ;;
-  --testsuite=*)  _testsuite=`_echo $parm | sed "s,^--.*=\(.*\),\1,"`  ;;
-  --port-one=*)   _port_one=`_echo $parm | sed "s,^--.*=\(.*\),\1,"`  ;;
-  --port-two=*)   _port_two=`_echo $parm | sed "s,^--.*=\(.*\),\1,"`  ;;
-  *) 
-     echo "Undefined parameter $parm. Try --help for help" 
-     exit 
-   ;;
- esac 
-done
-
-if [ "${COMPILEJAVA}" = "" ]
-then 
-  COMPILEJAVA=${TESTJAVA}
-fi
-
-if [ ${_compile} = "yes" ]
-then
- _compile
-fi
-
-if [ ${_jtreg} = "yes" ]
-then
- _testclasses=${TESTCLASSES}
- _testsrc=${TESTSRC}
- _logname="JMXStartStopTest_output.txt"
-fi
-
-rm -f ${_logname}
-
-# Local mode tests
-for i in `echo ${_testsuite} | sed -e "s/,/ /g"`
-do
-  test_${i} ${_port_one} ${_port_two}
-done
-
-