7195249: Some jtreg tests use hard coded ports
authorsla
Fri, 28 Feb 2014 12:57:35 +0400
changeset 23031 995cf5c2eb55
parent 23030 51178fbafe9c
child 23032 97414b5605ab
7195249: Some jtreg tests use hard coded ports Summary: Use Utils.getFreePort() and launch the tests by java code Reviewed-by: jbachorik, sla
jdk/test/ProblemList.txt
jdk/test/sun/management/jmxremote/RunTest.sh
jdk/test/sun/management/jmxremote/bootstrap/AbstractFilePermissionTest.java
jdk/test/sun/management/jmxremote/bootstrap/Dummy.java
jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java
jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java
jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.sh
jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java
jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh
jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java
jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.sh
jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTestApp.java
jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh
jdk/test/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java
jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java
jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.sh
jdk/test/sun/management/jmxremote/bootstrap/TestLogger.java
jdk/test/sun/management/jmxremote/bootstrap/rmiregistry.properties
jdk/test/sun/management/jmxremote/bootstrap/rmiregistryssl.properties
--- a/jdk/test/ProblemList.txt	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/ProblemList.txt	Fri Feb 28 12:57:35 2014 +0400
@@ -127,9 +127,6 @@
 
 # jdk_management
 
-# 8028150
-sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh	windows-all
-
 ############################################################################
 
 # jdk_jmx
--- a/jdk/test/sun/management/jmxremote/RunTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/RunTest.sh	Fri Feb 28 12:57:35 2014 +0400
@@ -25,9 +25,9 @@
 # No need to compile (now done by JTReg tags in calling file)
 #
 echo ${TESTJAVA}/bin/java ${TESTVMOPTS} -Dtest.src=${TESTCLASSES} \
-     -classpath ${TESTCLASSES} $* || exit 20 
+     -classpath ${TESTCLASSPATH} $* || exit 20
 
 ${TESTJAVA}/bin/java ${TESTVMOPTS} -Dtest.src=${TESTCLASSES} \
-     -classpath ${TESTCLASSES} $* || exit 20 
+     -classpath ${TESTCLASSPATH} $* || exit 20
 
 exit 0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/management/jmxremote/bootstrap/AbstractFilePermissionTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2013, 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.
+ */
+
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.Platform;
+import jdk.testlibrary.ProcessTools;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Change file permission for out-of-the-box management an do test used by
+ * PasswordFilePermissionTest and SSLConfigFilePermissionTest tests
+ *
+ * @author Taras Ledkov
+ */
+public abstract class AbstractFilePermissionTest {
+    private final String TEST_CLASS_PATH = System.getProperty("test.class.path");
+    protected final String TEST_CLASSES = System.getProperty("test.classes");
+    protected final FileSystem FS = FileSystems.getDefault();
+    private int MAX_GET_FREE_PORT_TRIES = 10;
+
+    protected final Path libDir = FS.getPath(TEST_CLASSES, "lib");
+    protected final Path mgmt = libDir.resolve("management.properties");
+    private final String mp = "-Dcom.sun.management.config.file=" + mgmt.toFile().getAbsolutePath();
+    private final String className = "Dummy";
+    private int failures = 0;
+
+    protected final Path file2PermissionTest;
+
+    protected AbstractFilePermissionTest(String fileName2PermissionTest) {
+        this.file2PermissionTest = libDir.resolve(fileName2PermissionTest);
+
+        try {
+            MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
+        } catch (NumberFormatException ex) {
+            ex.printStackTrace();
+        }
+    }
+
+
+    public static void createFile(Path path, String... content) throws IOException {
+        if (Files.exists(path) && Files.isRegularFile(path)) {
+            try {
+                Files.delete(path);
+            } catch (Exception ex) {
+                System.out.println("WARNING: " + path.toFile().getAbsolutePath() + " already exists - unable to remove old copy");
+                ex.printStackTrace();
+            }
+        }
+
+        try (BufferedWriter bw = Files.newBufferedWriter(path, Charset.defaultCharset())) {
+            for (String str : content) {
+                bw.write(str, 0, str.length());
+                bw.newLine();
+            }
+        }
+    }
+
+    public boolean skipTest() {
+        if ((TEST_CLASSES == null) || ("".equals(TEST_CLASSES))) {
+            System.out.println("Test is designed to be run from jtreg only");
+            return true;
+        }
+
+        if (!Platform.isLinux() && !Platform.isSolaris()) {
+            System.out.println("Test not designed to run on this operating system, skipping...");
+            return true;
+        }
+        return false;
+    }
+
+    protected abstract void testSetup() throws IOException;
+
+    public void runTest(String[] args) throws Exception {
+
+        if (skipTest()) {
+            return;
+        }
+
+        Files.deleteIfExists(mgmt);
+        Files.deleteIfExists(file2PermissionTest);
+        libDir.toFile().mkdir();
+
+        testSetup();
+
+        try {
+            test1();
+            test2();
+
+            if (failures == 0) {
+                System.out.println("All test(s) passed");
+            } else {
+                throw new Error(String.format("%d test(s) failed", failures));
+            }
+        } finally {
+            resetPasswordFilePermission();
+        }
+    }
+
+    /**
+     * Test 1 - SSL config file is secure - VM should start
+     */
+    private void test1() throws Exception {
+        final Set<PosixFilePermission> perms_0700 = new HashSet<>();
+        perms_0700.add(PosixFilePermission.OWNER_WRITE);
+        perms_0700.add(PosixFilePermission.OWNER_READ);
+        perms_0700.add(PosixFilePermission.OWNER_EXECUTE);
+        Files.setPosixFilePermissions(file2PermissionTest, perms_0700);
+
+        if (doTest() != 0) {
+            ++failures;
+        }
+    }
+
+    /**
+     * Test 1 - SSL config file is secure - VM should start
+     */
+    private void test2() throws Exception {
+        final Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file2PermissionTest);
+        perms.add(PosixFilePermission.OTHERS_READ);
+        perms.add(PosixFilePermission.OTHERS_EXECUTE);
+        Files.setPosixFilePermissions(file2PermissionTest, perms);
+
+        if (doTest() == 0) {
+            ++failures;
+        }
+    }
+
+    private int doTest() throws Exception {
+
+        for (int i = 0; i < MAX_GET_FREE_PORT_TRIES; ++i) {
+            final String pp = "-Dcom.sun.management.jmxremote.port=" + jdk.testlibrary.Utils.getFreePort();
+
+            List<String> command = new ArrayList<>();
+            command.addAll(jdk.testlibrary.Utils.getVmOptions());
+            command.add(mp);
+            command.add(pp);
+            command.add("-cp");
+            command.add(TEST_CLASSES);
+            command.add(className);
+
+
+            ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(
+                    command.toArray(new String[command.size()]));
+
+            System.out.println("test cmdline: " + Arrays.toString(processBuilder.command().toArray()).replace(",", ""));
+            Process p = processBuilder.start();
+            OutputAnalyzer output = new OutputAnalyzer(p);
+
+            System.out.println("test output:");
+            System.out.println(output.getOutput());
+
+            if ((p.exitValue() == 0)  ||
+                !output.getOutput().contains("Exception thrown by the agent : " +
+                        "java.rmi.server.ExportException: Port already in use")) {
+                return p.exitValue();
+            }
+        }
+
+        return -1;
+    }
+
+    private void resetPasswordFilePermission() throws Exception {
+        final Set<PosixFilePermission> perms_0777 = new HashSet<>();
+        Arrays.asList(PosixFilePermission.values()).stream().forEach(p -> {
+            perms_0777.add(p);
+        });
+        Files.setPosixFilePermissions(file2PermissionTest, perms_0777);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/management/jmxremote/bootstrap/Dummy.java	Fri Feb 28 12:57:35 2014 +0400
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2013, 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.
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.util.List;
+
+/**
+ * A dummy test "application" used by unit tests -
+ *   SSLConfigFilePermissionTest.java
+ *
+ *   @author Taras Ledkov
+ */
+class Dummy {
+    public static void main(String[] args) {
+        System.out.println("Inside main method...");
+    }
+}
--- a/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/LocalManagementTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -22,6 +22,7 @@
  */
 
 import java.io.File;
+import java.io.IOException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.nio.file.FileSystem;
@@ -32,7 +33,6 @@
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
-import jdk.testlibrary.ProcessTools;
 
 /**
  * @test
@@ -43,15 +43,25 @@
  *          TestManager will attempt a connection to the address obtained from
  *          both agent properties and jvmstat buffer.
  * @build jdk.testlibrary.ProcessTools
+ * @build jdk.testlibrary.Utils
  * @build TestManager TestApplication
  * @run main/othervm/timeout=300 -XX:+UsePerfData LocalManagementTest
  */
 
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.Utils;
+
 public class LocalManagementTest {
-    private static final  String TEST_CLASSPATH = System.getProperty("test.class.path");
-    private static final  String TEST_JDK = System.getProperty("test.jdk");
+    private static final String TEST_CLASSPATH = System.getProperty("test.class.path");
+    private static final String TEST_JDK = System.getProperty("test.jdk");
+    private static int MAX_GET_FREE_PORT_TRIES = 10;
 
     public static void main(String[] args) throws Exception {
+        try {
+            MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
+        } catch (NumberFormatException ex) {
+        }
+
         int failures = 0;
         for(Method m : LocalManagementTest.class.getDeclaredMethods()) {
             if (Modifier.isStatic(m.getModifiers()) &&
@@ -103,29 +113,49 @@
     private static boolean test4() throws Exception {
         Path agentPath = findAgent();
         if (agentPath != null) {
-            ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(
-                "-javaagent:" + agentPath.toString() +
-                "=com.sun.management.jmxremote.port=7775," +
-                "com.sun.management.jmxremote.authenticate=false," +
-                "com.sun.management.jmxremote.ssl=false",
-                "-cp",
-                TEST_CLASSPATH,
-                "TestApplication",
-                "-exit"
-            );
+
+            for (int i = 0; i < MAX_GET_FREE_PORT_TRIES; ++i) {
+                ProcessBuilder builder = ProcessTools.createJavaProcessBuilder(
+                        "-javaagent:" + agentPath.toString() +
+                                "=com.sun.management.jmxremote.port=" + Utils.getFreePort() + "," +
+                                "com.sun.management.jmxremote.authenticate=false," +
+                                "com.sun.management.jmxremote.ssl=false",
+                        "-cp",
+                        TEST_CLASSPATH,
+                        "TestApplication",
+                        "-exit"
+                );
 
-            Process prc = null;
-            try {
-                prc = ProcessTools.startProcess(
-                    "TestApplication",
-                    builder
-                );
-                int exitCode = prc.waitFor();
-                return exitCode == 0;
-            } finally {
-                if (prc != null) {
-                    prc.destroy();
+                Process prc = null;
+                final AtomicReference<Boolean> isBindExceptionThrown = new AtomicReference<>();
+                isBindExceptionThrown.set(new Boolean(false));
+                try {
+                    prc = ProcessTools.startProcess(
+                            "TestApplication",
+                            builder,
+                            (String line) -> {
+                                if (line.contains("Exception thrown by the agent : " +
+                                        "java.rmi.server.ExportException: Port already in use")) {
+                                    isBindExceptionThrown.set(new Boolean(true));
+                                }
+                            });
+
                     prc.waitFor();
+
+                    if (prc.exitValue() == 0) {
+                        return true;
+                    }
+
+                    if (isBindExceptionThrown.get().booleanValue()) {
+                        System.out.println("'Port already in use' error detected. Try again");
+                    } else {
+                        return false;
+                    }
+                } finally {
+                    if (prc != null) {
+                        prc.destroy();
+                        prc.waitFor();
+                    }
                 }
             }
         }
@@ -239,4 +269,4 @@
             }
         }
     }
-}
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2013, 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.
+ */
+
+import java.io.IOException;
+
+/**
+ * @test
+ * @library /lib/testlibrary
+ * @bug 6557093
+ * @summary Check SSL config file permission for out-of-the-box management
+ * @build jdk.testlibrary.Utils
+ * @build jdk.testlibrary.ProcessTools
+ * @build jdk.testlibrary.OutputAnalyzer
+ * @build AbstractFilePermissionTest
+ * @build Dummy
+ * @run main/timeout=300 PasswordFilePermissionTest
+ *
+ * @author Taras Ledkov
+ */
+public class PasswordFilePermissionTest extends AbstractFilePermissionTest {
+
+    private PasswordFilePermissionTest() {
+        super("jmxremote.passwordconfig");
+    }
+
+    public void testSetup() throws IOException {
+        createFile(mgmt,
+                "# management.properties",
+                "com.sun.management.jmxremote.ssl=false",
+                "com.sun.management.jmxremote.password.file=" + file2PermissionTest.toFile().getAbsolutePath());
+
+        createFile(file2PermissionTest,
+                "# jmxremote.password\n");
+    }
+
+    public static void main(String[] args) throws Exception {
+        PasswordFilePermissionTest test = new PasswordFilePermissionTest();
+
+        test.runTest(args);
+    }
+
+}
+
+
--- a/jdk/test/sun/management/jmxremote/bootstrap/PasswordFilePermissionTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,134 +0,0 @@
-#!/bin/sh
-
-#
-# Copyright (c) 2004, 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 5008047
-# @summary Check password file permission for out-of-the-box management
-#
-# @run shell PasswordFilePermissionTest.sh
-
-createJavaFile()
-{
-    cat << EOF > $1/$2.java
-    class $2 {
-        public static void main(String[] args) {
-            System.out.println("Inside main method...");
-        }
-    }
-EOF
-}
-
-createConfigFile() {
-    cat << EOF > $1
-# management.properties
-com.sun.management.jmxremote.ssl=false
-com.sun.management.jmxremote.password.file=$2
-EOF
-}
-
-createPasswordFile() {
-    if [ -f "$1" ] ; then
-	rm -f $1 || echo WARNING: $1 already exists - unable to remove old copy
-    fi
-    cat << EOF > $1
-# jmxremote.password
-EOF
-}
-
-
-# Check we are run from jtreg
-if [ -z "${TESTCLASSES}" ]; then
-    echo "Test is designed to be run from jtreg only"
-    exit 0
-fi
-
-
-# Test not suitable for Windows as chmod may not be able to
-# security the password file.
-
-os=`uname -s`
-if [ "$os" != "Linux" -a "$os" != "SunOS" ]; then
-    echo "Test not designed to run on this operating system, skipping..."
-    exit 0
-fi
-
-
-# Create configuration file and dummy password file
-
-LIBDIR=${TESTCLASSES}/lib
-CONFIG=${LIBDIR}/management.properties
-PASSWD=${LIBDIR}/jmxremote.password
-rm -f ${CONFIG}
-rm -f ${PASSWD}
-mkdir ${LIBDIR} 2>&1
-createJavaFile ${TESTCLASSES} Null
-createConfigFile ${CONFIG} ${PASSWD}
-createPasswordFile ${PASSWD}
-
-# Compile test 
-
-${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d ${TESTCLASSES} ${TESTCLASSES}/Null.java
-
-
-JAVA=${TESTJAVA}/bin/java
-CLASSPATH=${TESTCLASSES}
-export CLASSPATH
-
-failures=0
-
-mp=-Dcom.sun.management.config.file=${CONFIG}
-pp=-Dcom.sun.management.jmxremote.port=4888
-
-go() {
-    echo ''
-    sh -xc "$JAVA ${TESTVMOPTS} $1 $2 $3 $4 $5 $6 $7 $8" 2>&1
-    if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
-}
-
-# Test 1 - password file is secure - VM should start
-chmod 700 ${PASSWD}
-sh -xc "$JAVA ${TESTVMOPTS} $mp $pp Null" 2>&1
-if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
-
-# Test 2 - password file is not secure - VM should fail to start
-chmod o+rx ${PASSWD}
-sh -xc "$JAVA ${TESTVMOPTS} $mp $pp Null" 2>&1
-if [ $? = 0 ]; then failures=`expr $failures + 1`; fi
-
-# Reset the file permissions on the generated password file
-chmod 777 ${PASSWD}
-
-#
-# Results
-#
-echo ''
-if [ $failures -gt 0 ];
-  then echo "$failures test(s) failed";
-  else echo "All test(s) passed"; fi
-exit $failures
-
-
-
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -27,7 +27,6 @@
 import java.io.FilenameFilter;
 import java.io.IOException;
 import java.net.BindException;
-import java.net.ServerSocket;
 import java.rmi.server.ExportException;
 
 import java.util.Properties;
@@ -43,8 +42,6 @@
 
 import sun.management.AgentConfigurationError;
 
-import util.TestLogger;
-
 /**
  * <p>This class implements unit test for RMI Bootstrap.
  * When called with no arguments main() looks in the directory indicated
@@ -71,18 +68,11 @@
  **/
 public class RmiBootstrapTest {
     // the number of consecutive ports to test for availability
-    private static final int PORT_TEST_LEN = 800;
+    private static int MAX_GET_FREE_PORT_TRIES = 10;
     static TestLogger log =
         new TestLogger("RmiBootstrapTest");
 
     /**
-     * When launching several registries, we increment the port number
-     * to avoid falling into "port number already in use" problems.
-     **/
-    static int testPort = 0;
-    static int basePort = 0;
-
-    /**
      * Default values for RMI configuration properties.
      **/
     public static interface DefaultValues {
@@ -627,92 +617,100 @@
      * eventually cleans up by calling ConnectorBootstrap.terminate().
      * @return null if the test succeeds, an error message otherwise.
      **/
-    private String testConfiguration(File file,int port) throws BindException {
-
-        final String path;
-        try {
-            path=(file==null)?null:file.getCanonicalPath();
-        } catch(IOException x) {
-            final String err = "Failed to test configuration " + file +
-                ": " + x;
-            log.trace("testConfiguration",err);
-            log.debug("testConfiguration",x);
-            return err;
-        }
-        final String config = (path==null)?"Default config file":path;
-
-        System.out.println("***");
-        System.out.println("*** Testing configuration (port=" + port + "): "
-                           + path);
-        System.out.println("***");
+    private String testConfiguration(File file) throws IOException, InterruptedException {
 
-        System.setProperty("com.sun.management.jmxremote.port",
-                            Integer.toString(port));
-        if (path != null)
-            System.setProperty("com.sun.management.config.file", path);
-        else
-            System.getProperties().remove("com.sun.management.config.file");
-
-        log.trace("testConfiguration","com.sun.management.jmxremote.port="+port);
-        if (path != null && log.isDebugOn())
-            log.trace("testConfiguration",
-                      "com.sun.management.config.file="+path);
-
-        checkSslConfiguration();
-
-        final JMXConnectorServer cs;
-        try {
-            cs = ConnectorBootstrap.initialize();
-        } catch (AgentConfigurationError x) {
-            if (x.getCause() instanceof ExportException) {
-                if (x.getCause().getCause() instanceof BindException) {
-                    throw (BindException)x.getCause().getCause();
+        for (int i = 0; i < MAX_GET_FREE_PORT_TRIES; i++) {
+            try {
+                int port = jdk.testlibrary.Utils.getFreePort();
+                final String path;
+                try {
+                    path=(file==null)?null:file.getCanonicalPath();
+                } catch(IOException x) {
+                    final String err = "Failed to test configuration " + file +
+                        ": " + x;
+                    log.trace("testConfiguration",err);
+                    log.debug("testConfiguration",x);
+                    return err;
                 }
-            }
-            final String err = "Failed to initialize connector:" +
-                "\n\tcom.sun.management.jmxremote.port=" + port +
-                ((path!=null)?"\n\tcom.sun.management.config.file="+path:
-                 "\n\t"+config) +
-                "\n\tError is: " + x;
-            log.trace("testConfiguration",err);
-            log.debug("testConfiguration",x);
-            return err;
-        } catch (Exception x) {
-            log.debug("testConfiguration",x);
-            return x.toString();
-        }
+                final String config = (path==null)?"Default config file":path;
+
+                System.out.println("***");
+                System.out.println("*** Testing configuration (port=" + port + "): "
+                                   + path);
+                System.out.println("***");
 
-        try {
-            JMXServiceURL url =
-                new JMXServiceURL("rmi",null,0,"/jndi/rmi://localhost:"+
-                                  port+"/jmxrmi");
+                System.setProperty("com.sun.management.jmxremote.port",
+                                    Integer.toString(port));
+                if (path != null)
+                    System.setProperty("com.sun.management.config.file", path);
+                else
+                    System.getProperties().remove("com.sun.management.config.file");
+
+                log.trace("testConfiguration","com.sun.management.jmxremote.port="+port);
+                if (path != null && log.isDebugOn())
+                    log.trace("testConfiguration",
+                              "com.sun.management.config.file="+path);
+
+                checkSslConfiguration();
 
-            try {
-                testCommunication(url);
-            } catch (Exception x) {
-                final String err = "Failed to connect to agent {url="+url+
-                    "}: " + x;
-                log.trace("testConfiguration",err);
-                log.debug("testConfiguration",x);
-                return err;
-            }
-        } catch (Exception x) {
-            final String err = "Failed to test configuration "+config+
-                ": "+x;
-            log.trace("testConfiguration",err);
-            log.debug("testConfiguration",x);
-            return err;
-        } finally {
-            try {
-                cs.stop();
-            } catch (Exception x) {
-                final String err = "Failed to terminate: "+x;
-                log.trace("testConfiguration",err);
-                log.debug("testConfiguration",x);
+                final JMXConnectorServer cs;
+                try {
+                    cs = ConnectorBootstrap.initialize();
+                } catch (AgentConfigurationError x) {
+                    if (x.getCause() instanceof ExportException) {
+                        if (x.getCause().getCause() instanceof BindException) {
+                            throw (BindException)x.getCause().getCause();
+                        }
+                    }
+                    final String err = "Failed to initialize connector:" +
+                        "\n\tcom.sun.management.jmxremote.port=" + port +
+                        ((path!=null)?"\n\tcom.sun.management.config.file="+path:
+                         "\n\t"+config) +
+                        "\n\tError is: " + x;
+                    log.trace("testConfiguration",err);
+                    log.debug("testConfiguration",x);
+                    return err;
+                } catch (Exception x) {
+                    log.debug("testConfiguration",x);
+                    return x.toString();
+                }
+
+                try {
+                    JMXServiceURL url =
+                        new JMXServiceURL("rmi",null,0,"/jndi/rmi://localhost:"+
+                                          port+"/jmxrmi");
+
+                    try {
+                        testCommunication(url);
+                    } catch (Exception x) {
+                        final String err = "Failed to connect to agent {url="+url+
+                            "}: " + x;
+                        log.trace("testConfiguration",err);
+                        log.debug("testConfiguration",x);
+                        return err;
+                    }
+                } catch (Exception x) {
+                    final String err = "Failed to test configuration "+config+
+                        ": "+x;
+                    log.trace("testConfiguration",err);
+                    log.debug("testConfiguration",x);
+                    return err;
+                } finally {
+                    try {
+                        cs.stop();
+                    } catch (Exception x) {
+                        final String err = "Failed to terminate: "+x;
+                        log.trace("testConfiguration",err);
+                        log.debug("testConfiguration",x);
+                    }
+                }
+                System.out.println("Configuration " + config + " successfully tested");
+                return null;
+            } catch(BindException ex) {
             }
         }
-        System.out.println("Configuration " + config + " successfully tested");
-        return null;
+        System.err.println("Cannot find a free port after " + MAX_GET_FREE_PORT_TRIES + " tries");
+        return "Failed: cannot find a free port after " + MAX_GET_FREE_PORT_TRIES + " tries";
     }
 
     /**
@@ -720,23 +718,16 @@
      * The test is assumed to have succeeded if the bootstrap fails.
      * @return null if the test succeeds, an error message otherwise.
      **/
-    private String testConfigurationKo(File conf,int port) {
+    private String testConfigurationKo(File conf) throws InterruptedException, IOException {
         String errStr = null;
-        for (int i = 0; i < PORT_TEST_LEN; i++) {
-            try {
-                errStr = testConfiguration(conf,port+testPort++);
-                break;
-            } catch (BindException e) {
-                // port conflict; try another port
-            }
-        }
+        errStr = testConfiguration(conf);
         if (errStr == null) {
             return "Configuration " +
                 conf + " should have failed!";
         }
         System.out.println("Configuration " +
                            conf + " failed as expected");
-        log.debug("runko","Error was: " + errStr);
+        log.debug("runko", "Error was: " + errStr);
         return null;
     }
 
@@ -747,26 +738,16 @@
      *     *ko.properties: bootstrap or connection should fail.
      * @return null if the test succeeds, an error message otherwise.
      **/
-    private String testConfigurationFile(String fileName) {
+    private String testConfigurationFile(String fileName) throws InterruptedException, IOException {
         File file = new File(fileName);
-        final String portStr = System.getProperty("rmi.port",null);
-        final int port       = portStr != null ?
-                                Integer.parseInt(portStr) : basePort;
 
         if (fileName.endsWith("ok.properties")) {
             String errStr = null;
-            for (int i = 0; i < PORT_TEST_LEN; i++) {
-                try {
-                    errStr = testConfiguration(file,port+testPort++);
-                    return errStr;
-                } catch (BindException e) {
-                    // port conflict; try another port
-                }
-            }
-            return "Can not locate available port";
+            errStr = testConfiguration(file);
+            return errStr;
         }
         if (fileName.endsWith("ko.properties")) {
-            return testConfigurationKo(file,port+testPort++);
+            return testConfigurationKo(file);
         }
         return fileName +
             ": test file suffix must be one of [ko|ok].properties";
@@ -777,17 +758,14 @@
      * (see findConfigurationFilesKo() and testConfigurationKo())
      * @throws RuntimeException if the test fails.
      **/
-    public void runko() {
-        final String portStr = System.getProperty("rmi.port",null);
-        final int port       = portStr != null ?
-                                Integer.parseInt(portStr) : basePort;
+    public void runko() throws InterruptedException, IOException {
         final File[] conf = findConfigurationFilesKo();
         if ((conf == null)||(conf.length == 0))
             throw new RuntimeException("No configuration found");
 
         String errStr;
         for (int i=0;i<conf.length;i++) {
-            errStr = testConfigurationKo(conf[i],port+testPort++);
+            errStr = testConfigurationKo(conf[i]);
             if (errStr != null) {
                 throw new RuntimeException(errStr);
             }
@@ -800,24 +778,14 @@
      * (see findConfigurationFilesOk() and testConfiguration())
      * @throws RuntimeException if the test fails.
      **/
-    public void runok() {
-        final String portStr = System.getProperty("rmi.port",null);
-        final int port       = portStr != null ?
-                                Integer.parseInt(portStr) : basePort;
+    public void runok() throws InterruptedException, IOException {
         final File[] conf = findConfigurationFilesOk();
         if ((conf == null)||(conf.length == 0))
             throw new RuntimeException("No configuration found");
 
         String errStr = null;
         for (int i=0;i<conf.length;i++) {
-            for (int j = 0; j < PORT_TEST_LEN; i++) {
-                try {
-                    errStr = testConfiguration(conf[i],port+testPort++);
-                    break;
-                } catch (BindException e) {
-                    // port conflict; try another port
-                }
-            }
+            errStr = testConfiguration(conf[i]);
             if (errStr != null) {
                 throw new RuntimeException(errStr);
             }
@@ -840,7 +808,7 @@
      * (see runko() and runok()).
      * @throws RuntimeException if the test fails.
      **/
-    public void run() {
+    public void run() throws InterruptedException, IOException {
         runok();
         runko();
     }
@@ -854,7 +822,7 @@
      * indicated by the System property "test.src".
      * @throws RuntimeException if the test fails.
      **/
-    public void run(String args[]) {
+    public void run(String args[]) throws InterruptedException, IOException {
         if (args.length == 0) {
             run() ; return;
         }
@@ -871,7 +839,11 @@
      * exit(1) if the test fails.
      **/
     public static void main(String args[]) throws Exception {
-        setupBasePort();
+        try {
+            MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
+        } catch (NumberFormatException ex) {
+        }
+
         RmiBootstrapTest manager = new RmiBootstrapTest();
         try {
             manager.run(args);
@@ -886,9 +858,4 @@
         System.out.println("**** Test  RmiBootstrap Passed ****");
     }
 
-    private static void setupBasePort() throws IOException {
-        try (ServerSocket s = new ServerSocket(0)) {
-            basePort = s.getLocalPort() + 1;
-        }
-    }
 }
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiBootstrapTest.sh	Fri Feb 28 12:57:35 2014 +0400
@@ -26,7 +26,12 @@
 # @bug     6528083
 # @summary Test RMI Bootstrap
 #
-# @build TestLogger RmiBootstrapTest Utils
+# @library /lib/testlibrary
+# @library /lib/testlibrary
+# @build jdk.testlibrary.Utils
+# @build TestLogger
+# @build Utils
+# @build RmiBootstrapTest
 # @run shell/timeout=300  RmiBootstrapTest.sh
 
 # Define the Java class test name
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
@@ -21,69 +21,193 @@
  * questions.
  */
 
-import java.rmi.registry.LocateRegistry;
-import java.rmi.registry.Registry;
-import javax.rmi.ssl.SslRMIClientSocketFactory;
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.Utils;
 
-public class RmiRegistrySslTest {
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.net.BindException;
+import java.nio.charset.Charset;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.regex.Pattern;
 
-    static final String ok = "OK: Found jmxrmi entry in RMIRegistry!";
-    static final String ko = "KO: Did not find jmxrmi entry in RMIRegistry!";
-    static final String ko2 = "KO: Did not get expected exception!";
-    static final String okException = "OK: Got expected exception!";
-    static final String koException = "KO: Got unexpected exception!";
-
-    public static void main(String args[]) throws Exception {
-
-        System.out.println("RmiRegistry lookup...");
+/**
+ * @test
+ * @library /lib/testlibrary
+ * @bug 6228231
+ * @summary Test that RMI registry uses SSL.
+ * @build jdk.testlibrary.Utils
+ * @build jdk.testlibrary.ProcessTools
+ * @build jdk.testlibrary.OutputAnalyzer
+ * @build RmiRegistrySslTestApp
+ * @run main/timeout=300 RmiRegistrySslTest
+ * @author Luis-Miguel Alventosa, Taras Ledkov
+ */
+public class RmiRegistrySslTest {
+    private final String TEST_CLASS_PATH = System.getProperty("test.class.path");
+    private final String TEST_CLASSES = System.getProperty("test.classes");
+    private final String TEST_SRC = System.getProperty("test.src");
+    private final FileSystem FS = FileSystems.getDefault();
 
-        String testID = System.getProperty("testID");
+    private final Path libDir = FS.getPath(TEST_CLASSES, "lib");
+    private final Path rmiRegistryTemplate = FS.getPath(TEST_SRC, "rmiregistry.properties");
+    private final Path rmiRegistrySslTemplate = FS.getPath(TEST_SRC, "rmiregistryssl.properties");
+    private final Path rmiRegistryFile = libDir.resolve("rmiregistry.properties");
+    private final Path rmiRegistrySslFile = libDir.resolve("rmiregistryssl.properties");
+    private final String className = "RmiRegistrySslTestApp";
+    private int failures = 0;
+    private int port = 4444;
+    private static int MAX_GET_FREE_PORT_TRIES = 10;
+    private Map<String, Object> model = new HashMap<>();
+
+    private RmiRegistrySslTest() {
+        try {
+            MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
+        } catch (NumberFormatException ex) {
+        }
+    }
 
-        if ("Test1".equals(testID)) {
+    private void initPort() {
+        try {
+            port = Utils.getFreePort();
+        } catch (Exception e) {
+        }
+        model.put("${getFreePort}", new Integer(port));
+    }
+
+    private void initTestEnvironment() throws IOException {
+        initPort();
+
+        Files.deleteIfExists(rmiRegistryFile);
+        Files.deleteIfExists(rmiRegistrySslFile);
+        libDir.toFile().mkdir();
+        createFileByTemplate(rmiRegistryTemplate, rmiRegistryFile, model);
+        createFileByTemplate(rmiRegistrySslTemplate, rmiRegistrySslFile, model);
+    }
+
+    public static void createFileByTemplate(Path template, Path out, Map<String, Object> model) throws IOException {
+        if (Files.exists(out) && Files.isRegularFile(out)) {
             try {
-                Registry registry = LocateRegistry.getRegistry(4444);
-                String[] list = registry.list();
-                if ("jmxrmi".equals(list[0])) {
-                    System.out.println(ok);
-                } else {
-                    System.out.println(ko);
-                    throw new IllegalArgumentException(ko);
-                }
-            } catch (Exception e) {
-                System.out.println(koException);
-                e.printStackTrace(System.out);
-                throw e;
+                Files.delete(out);
+            } catch (Exception ex) {
+                System.out.println("WARNING: " + out.toFile().getAbsolutePath() + " already exists - unable to remove old copy");
+                ex.printStackTrace();
             }
         }
 
-        if ("Test2".equals(testID)) {
-            try {
-                Registry registry = LocateRegistry.getRegistry(4444);
-                String[] list = registry.list();
-                throw new IllegalArgumentException(ko2);
-            } catch (Exception e) {
-                System.out.println(okException);
-                e.printStackTrace(System.out);
-                return;
-            }
-        }
+        try (BufferedReader br = Files.newBufferedReader(template, Charset.defaultCharset());
+             BufferedWriter bw = Files.newBufferedWriter(out, Charset.defaultCharset())) {
+            String line;
+            while ((line = br.readLine()) != null) {
+                if (model != null) {
+                    for (Map.Entry<String, Object> macro : model.entrySet()) {
+                        line = line.replaceAll(Pattern.quote(macro.getKey()), macro.getValue().toString());
+                    }
+                }
 
-        if ("Test3".equals(testID)) {
-            try {
-                Registry registry = LocateRegistry.getRegistry(
-                    null, 4444, new SslRMIClientSocketFactory());
-                String[] list = registry.list();
-                if ("jmxrmi".equals(list[0])) {
-                    System.out.println(ok);
-                } else {
-                    System.out.println(ko);
-                    throw new IllegalArgumentException(ko);
-                }
-            } catch (Exception e) {
-                System.out.println(koException);
-                e.printStackTrace(System.out);
-                throw e;
+                bw.write(line, 0, line.length());
+                bw.newLine();
             }
         }
     }
+
+    public void runTest(String[] args) throws Exception {
+
+        test1();
+        test2();
+        test3();
+
+        if (failures == 0) {
+            System.out.println("All test(s) passed");
+        } else {
+            throw new Error(String.format("%d test(s) failed", failures));
+        }
+    }
+
+    private void test1() throws Exception {
+        System.out.println("-------------------------------------------------------------");
+        System.out.println(getClass().getName() + " : Non SSL RMIRegistry - Non SSL Lookup");
+        System.out.println("-------------------------------------------------------------");
+
+        int res = doTest("-DtestID=Test1",
+                "-Dcom.sun.management.config.file=" + rmiRegistryFile.toFile().getAbsolutePath());
+
+        if (res != 0) {
+            ++failures;
+        }
+    }
+
+    private void test2() throws Exception {
+        System.out.println("-------------------------------------------------------------");
+        System.out.println(getClass().getName() + " : SSL RMIRegistry - Non SSL Lookup");
+        System.out.println("-------------------------------------------------------------");
+
+        int res = doTest("-DtestID=Test2",
+                "-Dcom.sun.management.config.file=" + rmiRegistrySslFile.toFile().getAbsolutePath());
+
+        if (res != 0) {
+            ++failures;
+        }
+    }
+
+    private void test3() throws Exception {
+
+        System.out.println("-------------------------------------------------------------");
+        System.out.println(getClass().getName() + " : SSL RMIRegistry - SSL Lookup");
+        System.out.println("-------------------------------------------------------------");
+
+        int res = doTest("-DtestID=Test3",
+                "-Djavax.net.ssl.keyStore=" + FS.getPath(TEST_SRC, "ssl", "keystore").toFile().getAbsolutePath(),
+                "-Djavax.net.ssl.keyStorePassword=password",
+                "-Djavax.net.ssl.trustStore=" + FS.getPath(TEST_SRC, "ssl", "truststore").toFile().getAbsolutePath(),
+                "-Djavax.net.ssl.trustStorePassword=trustword",
+                "-Dcom.sun.management.config.file=" + rmiRegistrySslFile.toFile().getAbsolutePath());
+
+        if (res != 0) {
+            ++failures;
+        }
+    }
+
+    private int doTest(String... args) throws Exception {
+
+        for (int i = 0; i < MAX_GET_FREE_PORT_TRIES; ++i) {
+
+            initTestEnvironment();
+
+            List<String> command = new ArrayList<>();
+            command.addAll(Utils.getVmOptions());
+            command.add("-Dtest.src=" + TEST_SRC);
+            command.add("-Dtest.rmi.port=" + port);
+            command.addAll(Arrays.asList(args));
+            command.add("-cp");
+            command.add(TEST_CLASS_PATH);
+            command.add(className);
+
+            ProcessBuilder processBuilder = ProcessTools.createJavaProcessBuilder(command.toArray(new String[command.size()]));
+
+            Process p = processBuilder.start();
+            OutputAnalyzer output = new OutputAnalyzer(p);
+
+            System.out.println("test output:");
+            System.out.println(output.getOutput());
+
+            if (!output.getOutput().contains("Exception thrown by the agent : " +
+                    "java.rmi.server.ExportException: Port already in use")) {
+                return p.exitValue();
+            }
+        }
+        throw new Error("Cannot find free port");
+    }
+
+    public static void main(String[] args) throws Exception {
+        RmiRegistrySslTest test = new RmiRegistrySslTest();
+
+        test.runTest(args);
+    }
 }
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,64 +0,0 @@
-#
-# Copyright (c) 2005, 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 6228231
-# @summary Test that RMI registry uses SSL.
-# @author Luis-Miguel Alventosa
-# @run clean RmiRegistrySslTest
-# @run build RmiRegistrySslTest
-# @run shell/timeout=300 RmiRegistrySslTest.sh
-
-echo -------------------------------------------------------------
-echo `basename $0 .sh` : Non SSL RMIRegistry - Non SSL Lookup
-echo -------------------------------------------------------------
-
-${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES} \
-    -Dtest.src=${TESTSRC} \
-    -DtestID=Test1 \
-    -Dcom.sun.management.config.file=${TESTSRC}/rmiregistry.properties \
-    RmiRegistrySslTest || exit $?
-
-echo -------------------------------------------------------------
-echo `basename $0 .sh` : SSL RMIRegistry - Non SSL Lookup
-echo -------------------------------------------------------------
-
-${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES} \
-    -Dtest.src=${TESTSRC} \
-    -DtestID=Test2 \
-    -Dcom.sun.management.config.file=${TESTSRC}/rmiregistryssl.properties \
-    RmiRegistrySslTest || exit $?
-
-echo -------------------------------------------------------------
-echo `basename $0 .sh` : SSL RMIRegistry - SSL Lookup
-echo -------------------------------------------------------------
-
-${TESTJAVA}/bin/java ${TESTVMOPTS} -classpath ${TESTCLASSES} \
-    -Dtest.src=${TESTSRC} \
-    -DtestID=Test3 \
-    -Djavax.net.ssl.keyStore=${TESTSRC}/ssl/keystore \
-    -Djavax.net.ssl.keyStorePassword=password \
-    -Djavax.net.ssl.trustStore=${TESTSRC}/ssl/truststore \
-    -Djavax.net.ssl.trustStorePassword=trustword \
-    -Dcom.sun.management.config.file=${TESTSRC}/rmiregistryssl.properties \
-    RmiRegistrySslTest || exit $?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiRegistrySslTestApp.java	Fri Feb 28 12:57:35 2014 +0400
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2005, 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.
+ */
+
+import java.rmi.registry.LocateRegistry;
+import java.rmi.registry.Registry;
+import javax.rmi.ssl.SslRMIClientSocketFactory;
+import jdk.testlibrary.Utils;
+
+
+public class RmiRegistrySslTestApp {
+
+    static final String ok = "OK: Found jmxrmi entry in RMIRegistry!";
+    static final String ko = "KO: Did not find jmxrmi entry in RMIRegistry!";
+    static final String ko2 = "KO: Did not get expected exception!";
+    static final String okException = "OK: Got expected exception!";
+    static final String koException = "KO: Got unexpected exception!";
+
+    public static void main(String args[]) throws Exception {
+
+        System.out.println("RmiRegistry lookup...");
+
+        String testID = System.getProperty("testID");
+        int port = Integer.parseInt(System.getProperty("test.rmi.port"));
+
+        if ("Test1".equals(testID)) {
+            try {
+                Registry registry = LocateRegistry.getRegistry(port);
+                String[] list = registry.list();
+                if ("jmxrmi".equals(list[0])) {
+                    System.out.println(ok);
+                } else {
+                    System.out.println(ko);
+                    throw new IllegalArgumentException(ko);
+                }
+            } catch (Exception e) {
+                System.out.println(koException);
+                e.printStackTrace(System.out);
+                throw e;
+            }
+        }
+
+        if ("Test2".equals(testID)) {
+            try {
+                Registry registry = LocateRegistry.getRegistry(port);
+                String[] list = registry.list();
+                throw new IllegalArgumentException(ko2);
+            } catch (Exception e) {
+                System.out.println(okException);
+                e.printStackTrace(System.out);
+                return;
+            }
+        }
+
+        if ("Test3".equals(testID)) {
+            try {
+                Registry registry = LocateRegistry.getRegistry(
+                    null, port, new SslRMIClientSocketFactory());
+                String[] list = registry.list();
+                if ("jmxrmi".equals(list[0])) {
+                    System.out.println(ok);
+                } else {
+                    System.out.println(ko);
+                    throw new IllegalArgumentException(ko);
+                }
+            } catch (Exception e) {
+                System.out.println(koException);
+                e.printStackTrace(System.out);
+                throw e;
+            }
+        }
+    }
+}
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslBootstrapTest.sh	Fri Feb 28 12:57:35 2014 +0400
@@ -26,7 +26,11 @@
 # @bug     6528083
 # @summary Test RMI Bootstrap with SSL
 #
-# @build TestLogger RmiBootstrapTest Utils
+# @library /lib/testlibrary
+# @build jdk.testlibrary.Utils
+# @build TestLogger
+# @build Utils
+# @build RmiBootstrapTest
 # @run shell/timeout=300  RmiSslBootstrapTest.sh
 
 # Define the Java class test name
--- a/jdk/test/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -45,8 +45,6 @@
 
 import sun.management.AgentConfigurationError;
 
-import util.TestLogger;
-
 /**
  * <p>This class implements unit test for RMI Bootstrap.
  * When called with no arguments main() looks in the directory indicated
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.java	Fri Feb 28 12:57:35 2014 +0400
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2013, 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.
+ */
+
+import java.io.IOException;
+
+/**
+ * @test
+ * @library /lib/testlibrary
+ * @bug 6557093
+ * @bug 6557093
+ * @build jdk.testlibrary.Utils
+ * @build jdk.testlibrary.ProcessTools
+ * @build jdk.testlibrary.OutputAnalyzer
+ * @build Dummy
+ * @build AbstractFilePermissionTest
+ * @summary Check SSL config file permission for out-of-the-box management
+ * @run main/timeout=300 SSLConfigFilePermissionTest
+ *
+ * @author Taras Ledkov
+ */
+public class SSLConfigFilePermissionTest extends AbstractFilePermissionTest {
+
+    private final String TEST_SRC = System.getProperty("test.src");
+
+    private SSLConfigFilePermissionTest() {
+        super("jmxremote.ssl.config");
+    }
+
+    public void testSetup() throws IOException {
+        createFile(mgmt,
+                "# management.properties",
+                "com.sun.management.jmxremote.authenticate=false",
+                "com.sun.management.jmxremote.ssl.config.file=" + file2PermissionTest.toFile().getAbsolutePath());
+
+        createFile(file2PermissionTest,
+                "# management.properties",
+                "javax.net.ssl.keyStore = " +
+                        FS.getPath(TEST_SRC, "ssl", "keystore").toFile().getAbsolutePath(),
+                "javax.net.ssl.keyStorePassword = password");
+    }
+
+    public static void main(String[] args) throws Exception {
+        SSLConfigFilePermissionTest test = new SSLConfigFilePermissionTest();
+
+        test.runTest(args);
+    }
+}
+
+
--- a/jdk/test/sun/management/jmxremote/bootstrap/SSLConfigFilePermissionTest.sh	Fri Feb 28 08:40:27 2014 +0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,128 +0,0 @@
-#!/bin/sh
-
-#
-# Copyright (c) 2007, 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 6557093
-# @summary Check SSL config file permission for out-of-the-box management
-#
-# @run shell SSLConfigFilePermissionTest.sh
-
-createJavaFile()
-{
-    cat << EOF > $1/$2.java
-    class $2 {
-        public static void main(String[] args) {
-            System.out.println("Inside main method...");
-        }
-    }
-EOF
-}
-
-createManagementConfigFile() {
-    cat << EOF > $1
-# management.properties
-com.sun.management.jmxremote.authenticate=false
-com.sun.management.jmxremote.ssl.config.file=$2
-EOF
-}
-
-createSSLConfigFile() {
-    if [ -f "$1" ] ; then
-	rm -f $1 || echo WARNING: $1 already exists - unable to remove old copy
-    fi
-    cat << EOF > $1
-javax.net.ssl.keyStore=$2
-javax.net.ssl.keyStorePassword=password
-EOF
-}
-
-# Check we are run from jtreg
-if [ -z "${TESTCLASSES}" ]; then
-    echo "Test is designed to be run from jtreg only"
-    exit 0
-fi
-
-# Test not suitable for Windows as chmod may not be able to
-# security the password file.
-
-os=`uname -s`
-if [ "$os" != "Linux" -a "$os" != "SunOS" ]; then
-    echo "Test not designed to run on this operating system, skipping..."
-    exit 0
-fi
-
-# Create management and SSL configuration files
-
-LIBDIR=${TESTCLASSES}/lib
-MGMT=${LIBDIR}/management.properties
-SSL=${LIBDIR}/jmxremote.ssl.config
-rm -f ${MGMT}
-rm -f ${SSL}
-mkdir ${LIBDIR} 2>&1
-createJavaFile ${TESTCLASSES} Dummy
-createManagementConfigFile ${MGMT} ${SSL}
-createSSLConfigFile ${SSL} ${TESTSRC}/ssl/keystore
-
-# Compile test
-
-${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} -d ${TESTCLASSES} ${TESTCLASSES}/Dummy.java
-
-JAVA=${TESTJAVA}/bin/java
-CLASSPATH=${TESTCLASSES}
-export CLASSPATH
-
-failures=0
-
-mp=-Dcom.sun.management.config.file=${MGMT}
-pp=-Dcom.sun.management.jmxremote.port=4999
-
-go() {
-    echo ''
-    sh -xc "$JAVA ${TESTVMOPTS} $1 $2 $3 $4 $5 $6 $7 $8" 2>&1
-    if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
-}
-
-# Test 1 - SSL config file is secure - VM should start
-chmod 700 ${SSL}
-sh -xc "$JAVA ${TESTVMOPTS} $mp $pp Dummy" 2>&1
-if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
-
-# Test 2 - SSL config file is not secure - VM should fail to start
-chmod o+rx ${SSL}
-sh -xc "$JAVA ${TESTVMOPTS} $mp $pp Dummy" 2>&1
-if [ $? = 0 ]; then failures=`expr $failures + 1`; fi
-
-# Reset the file permissions on the generated SSL config file
-chmod 777 ${SSL}
-
-#
-# Results
-#
-echo ''
-if [ $failures -gt 0 ];
-  then echo "$failures test(s) failed";
-  else echo "All test(s) passed"; fi
-exit $failures
--- a/jdk/test/sun/management/jmxremote/bootstrap/TestLogger.java	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/TestLogger.java	Fri Feb 28 12:57:35 2014 +0400
@@ -20,7 +20,6 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
-package util;
 
 import java.util.logging.Logger;
 import java.util.logging.Level;
--- a/jdk/test/sun/management/jmxremote/bootstrap/rmiregistry.properties	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/rmiregistry.properties	Fri Feb 28 12:57:35 2014 +0400
@@ -24,7 +24,7 @@
 # ################ Management Agent Port #########################
 # 
 # For setting the JMX RMI agent port use the following line
-com.sun.management.jmxremote.port=4444
+com.sun.management.jmxremote.port=${getFreePort}
 #
 # For setting the SNMP agent port use the following line
 # com.sun.management.snmp.port=<port-number>
--- a/jdk/test/sun/management/jmxremote/bootstrap/rmiregistryssl.properties	Fri Feb 28 08:40:27 2014 +0800
+++ b/jdk/test/sun/management/jmxremote/bootstrap/rmiregistryssl.properties	Fri Feb 28 12:57:35 2014 +0400
@@ -24,7 +24,7 @@
 # ################ Management Agent Port #########################
 # 
 # For setting the JMX RMI agent port use the following line
-com.sun.management.jmxremote.port=4444
+com.sun.management.jmxremote.port=${getFreePort}
 #
 # For setting the SNMP agent port use the following line
 # com.sun.management.snmp.port=<port-number>