TestLibrary.java 18.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * 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.
 *
19 20 21
 * 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.
D
duke 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 */

/**
 *
 *
 * @author Adrian Colley
 * @author Laird Dornin
 * @author Peter Jones
 * @author Ann Wollrath
 *
 * The rmi library directory contains a set of simple utiltity classes
 * for use in rmi regression tests.
 *
 * NOTE: The JavaTest group has recommended that regression tests do
 * not make use of packages.
 */

D
dmocek 已提交
39
import java.io.ByteArrayOutputStream;
D
duke 已提交
40 41 42 43 44 45
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
D
dmocek 已提交
46 47
import java.net.ServerSocket;
import java.net.URL;
D
duke 已提交
48 49
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
D
dmocek 已提交
50 51 52 53
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RemoteRef;
D
duke 已提交
54 55 56
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.Properties;
57

D
dmocek 已提交
58 59 60 61 62
import sun.rmi.registry.RegistryImpl;
import sun.rmi.server.UnicastServerRef;
import sun.rmi.transport.Endpoint;
import sun.rmi.transport.LiveRef;
import sun.rmi.transport.tcp.TCPEndpoint;
D
duke 已提交
63 64 65 66 67 68

/**
 * Class of utility/library methods (i.e. procedures) that assist with
 * the writing and maintainance of rmi regression tests.
 */
public class TestLibrary {
D
dmocek 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    /**
     *                       IMPORTANT!
     *
     * RMI tests are run concurrently and port conflicts result when a single
     * port number is used by multiple tests.  When needing a port, use
     * getUnusedRandomPort() wherever possible.  If getUnusedRandomPort() cannot
     * be used, reserve and specify a port to use for your test here.   This
     * will ensure there are no port conflicts amongst the RMI tests.  The
     * port numbers specified here may also be specified in the respective
     * tests.  Do not change the reserved port numbers here without also
     * changing the port numbers in the respective tests.
     *
     * When needing an instance of the RMIRegistry, use
     * createRegistryOnUnusedPort wherever possible to prevent port conflicts.
     *
     * Reserved port range: FIXED_PORT_MIN to FIXED_PORT_MAX (inclusive) for
     * tests which cannot use a random port.  If new fixed ports are added below
     * FIXED_PORT_MIN or above FIXED_PORT_MAX, then adjust
     * FIXED_PORT_MIN/MAX appropriately.
     */
89 90 91 92 93 94 95
    public final static int FIXED_PORT_MIN = 60001;
    public final static int FIXED_PORT_MAX = 60010;
    public final static int RMIDVIAINHERITEDCHANNEL_ACTIVATION_PORT = 60001;
    public final static int RMIDVIAINHERITEDCHANNEL_REGISTRY_PORT = 60002;
    public final static int INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT = 60003;
    public final static int INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT = 60004;
    public final static int READTEST_REGISTRY_PORT = 60005;
96
    private final static int MAX_SERVER_SOCKET_TRIES = 2*(FIXED_PORT_MAX-FIXED_PORT_MIN+1);
D
duke 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

    static void mesg(Object mesg) {
        System.err.println("TEST_LIBRARY: " + mesg.toString());
    }

    /**
     * Routines that enable rmi tests to fail in a uniformly
     * informative fashion.
     */
    public static void bomb(String message, Exception e) {
        String testFailed = "TEST FAILED: ";

        if ((message == null) && (e == null)) {
            testFailed += " No relevant information";
        } else if (e == null) {
            testFailed += message;
        }

        System.err.println(testFailed);
        if (e != null) {
            System.err.println("Test failed with: " +
                               e.getMessage());
            e.printStackTrace(System.err);
        }
        throw new TestFailedException(testFailed, e);
    }
    public static void bomb(String message) {
        bomb(message, null);
    }
    public static void bomb(Exception e) {
        bomb(null, e);
    }

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    /**
     * Helper method to determine if registry has started
     *
     * @param port The port number to check
     * @param msTimeout The amount of milliseconds to spend checking
     */

    public static boolean checkIfRegistryRunning(int port, int msTimeout) {
        long stopTime = System.currentTimeMillis() + msTimeout;
        do {
            try {
                Registry r = LocateRegistry.getRegistry(port);
                String[] s = r.list();
                // no exception. We're now happy that registry is running
                return true;
            } catch (RemoteException e) {
                // problem - not ready ? Try again
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {
                    // not expected
                }
            }
        } while (stopTime > System.currentTimeMillis());
        return false;
    }

D
duke 已提交
157 158 159
    public static String getProperty(String property, String defaultVal) {
        final String prop = property;
        final String def = defaultVal;
160 161 162
        return java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<String>() {
                public String run() {
D
duke 已提交
163 164
                    return System.getProperty(prop, def);
                }
165
            });
D
duke 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179
    }

    /**
     * Property mutators
     */
    public static void setBoolean(String property, boolean value) {
        setProperty(property, (new Boolean(value)).toString());
    }
    public static void setInteger(String property, int value) {
        setProperty(property, Integer.toString(value));
    }
    public static void setProperty(String property, String value) {
        final String prop = property;
        final String val = value;
180 181 182
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
D
duke 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
                    System.setProperty(prop, val);
                    return null;
                }
        });
    }

    /**
     * Routines to print out a test's properties environment.
     */
    public static void printEnvironment() {
        printEnvironment(System.err);
    }
    public static void printEnvironment(PrintStream out) {
        out.println("-------------------Test environment----------" +
                    "---------");

199
        for(Enumeration<?> keys = System.getProperties().keys();
D
duke 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
            keys.hasMoreElements();) {

            String property = (String) keys.nextElement();
            out.println(property + " = " + getProperty(property, null));
        }
        out.println("---------------------------------------------" +
                    "---------");
    }

    /**
     * Routine that "works-around" a limitation in jtreg.
     * Currently it is not possible for a test to specify that the
     * test harness should build a given source file and install the
     * resulting class in a location that is not accessible from the
     * test's classpath.  This method enables a test to move a
     * compiled test class file from the test's class directory into a
     * given "codebase" directory.  As a result the test can only
     * access the class file for <code>className</code>if the test loads
     * it from a classloader (e.g. RMIClassLoader).
     *
     * Tests that use this routine must have the following permissions
     * granted to them:
     *
     *   getProperty user.dir
     *   getProperty etc.
     */
    public static URL installClassInCodebase(String className,
                                             String codebase)
        throws MalformedURLException
    {
        return installClassInCodebase(className, codebase, true);
    }

    public static URL installClassInCodebase(String className,
                                             String codebase,
                                             boolean delete)
        throws MalformedURLException
    {
        /*
         * NOTES/LIMITATIONS: The class must not be in a named package,
         * and the codebase must be a relative path (it's created relative
         * to the working directory).
         */
        String classFileName = className + ".class";

        /*
         * Specify the file to contain the class definition.  Make sure
         * that the codebase directory exists (underneath the working
         * directory).
         */
        File dstDir = (new File(getProperty("user.dir", "."), codebase));

        if (!dstDir.exists()) {
            if (!dstDir.mkdir()) {
                throw new RuntimeException(
                    "could not create codebase directory");
            }
        }
        File dstFile = new File(dstDir, classFileName);

        /*
         * Obtain the URL for the codebase.
         */
263
        URL codebaseURL = dstDir.toURI().toURL();
D
duke 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

        /*
         * Specify where we will copy the class definition from, if
         * necessary.  After the test is built, the class file can be
         * found in the "test.classes" directory.
         */
        File srcDir = new File(getProperty("test.classes", "."));
        File srcFile = new File(srcDir, classFileName);

        mesg(srcFile);
        mesg(dstFile);

        /*
         * If the class definition is not already located at the codebase,
         * copy it there from the test build area.
         */
        if (!dstFile.exists()) {
            if (!srcFile.exists()) {
                throw new RuntimeException(
                    "could not find class file to install in codebase " +
                    "(try rebuilding the test): " + srcFile);
            }

            try {
                copyFile(srcFile, dstFile);
            } catch (IOException e) {
                throw new RuntimeException(
                    "could not install class file in codebase");
            }

            mesg("Installed class \"" + className +
                "\" in codebase " + codebaseURL);
        }

        /*
         * After the class definition is successfully installed at the
         * codebase, delete it from the test's CLASSPATH, so that it will
         * not be found there first before the codebase is searched.
         */
        if (srcFile.exists()) {
            if (delete && !srcFile.delete()) {
                throw new RuntimeException(
                    "could not delete duplicate class file in CLASSPATH");
            }
        }

        return codebaseURL;
    }

    public static void copyFile(File srcFile, File dstFile)
        throws IOException
    {
        FileInputStream src = new FileInputStream(srcFile);
        FileOutputStream dst = new FileOutputStream(dstFile);

        byte[] buf = new byte[32768];
        while (true) {
            int count = src.read(buf);
            if (count < 0) {
                break;
            }
            dst.write(buf, 0, count);
        }

        dst.close();
        src.close();
    }

    /** routine to unexport an object */
    public static void unexport(Remote obj) {
        if (obj != null) {
            try {
                mesg("unexporting object...");
                UnicastRemoteObject.unexportObject(obj, true);
            } catch (NoSuchObjectException munch) {
            } catch (Exception e) {
                e.getMessage();
                e.printStackTrace();
            }
        }
    }

    /**
     * Allow test framework to control the security manager set in
     * each test.
     *
     * @param managerClassName The class name of the security manager
     *                         to be instantiated and set if no security
     *                         manager has already been set.
     */
    public static void suggestSecurityManager(String managerClassName) {
        SecurityManager manager = null;

        if (System.getSecurityManager() == null) {
            try {
                if (managerClassName == null) {
                    managerClassName = TestParams.defaultSecurityManager;
                }
                manager = ((SecurityManager) Class.
                           forName(managerClassName).newInstance());
            } catch (ClassNotFoundException cnfe) {
                bomb("Security manager could not be found: " +
                     managerClassName, cnfe);
            } catch (Exception e) {
                bomb("Error creating security manager. ", e);
            }

            System.setSecurityManager(manager);
        }
    }

D
dmocek 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    /**
     * Creates an RMI {@link Registry} on a random, un-reserved port.
     *
     * @returns an RMI Registry, using a random port.
     * @throws RemoteException if there was a problem creating a Registry.
     */
    public static Registry createRegistryOnUnusedPort() throws RemoteException {
        return LocateRegistry.createRegistry(getUnusedRandomPort());
    }

    /**
     * Returns the port number the RMI {@link Registry} is running on.
     *
     * @param registry the registry to find the port of.
     * @return the port number the registry is using.
     * @throws RuntimeException if there was a problem getting the port number.
     */
    public static int getRegistryPort(Registry registry) {
        int port = -1;

        try {
            RemoteRef remoteRef = ((RegistryImpl)registry).getRef();
            LiveRef liveRef = ((UnicastServerRef)remoteRef).getLiveRef();
            Endpoint endpoint = liveRef.getChannel().getEndpoint();
            TCPEndpoint tcpEndpoint = (TCPEndpoint) endpoint;
            port = tcpEndpoint.getPort();
        } catch (Exception ex) {
            throw new RuntimeException("Error getting registry port.", ex);
        }

        return port;
    }

    /**
     * Returns an unused random port number which is not a reserved port.  Will
     * try up to 10 times to get a random port before giving up and throwing a
     * RuntimeException.
     *
     * @return an unused random port number.
     * @throws RuntimeException if there was a problem getting a port.
     */
    public static int getUnusedRandomPort() {
        int numTries = 0;
418
        IOException ex = null;
D
dmocek 已提交
419

420 421
        while (numTries++ < MAX_SERVER_SOCKET_TRIES) {
            int unusedRandomPort = -1;
D
dmocek 已提交
422 423 424 425
            ex = null; //reset

            try (ServerSocket ss = new ServerSocket(0)) {
                unusedRandomPort = ss.getLocalPort();
426
            } catch (IOException e) {
D
dmocek 已提交
427
                ex = e;
428 429 430 431 432 433 434
                // temporarily print stack trace here until we find out why
                // tests are failing.
                System.err.println("TestLibrary.getUnusedRandomPort() caught "
                        + "exception on iteration " + numTries
                        + (numTries==MAX_SERVER_SOCKET_TRIES ? " (the final try)."
                        : "."));
                ex.printStackTrace();
D
dmocek 已提交
435 436
            }

437 438 439 440 441 442 443 444 445 446
            if (unusedRandomPort >= 0) {
                if (isReservedPort(unusedRandomPort)) {
                    System.out.println("INFO: On try # " + numTries
                        + (numTries==MAX_SERVER_SOCKET_TRIES ? ", the final try, ": ",")
                        + " ServerSocket(0) returned the reserved port "
                        + unusedRandomPort
                        + " in TestLibrary.getUnusedRandomPort() ");
                } else {
                    return unusedRandomPort;
                }
D
dmocek 已提交
447 448 449 450 451
            }
        }

        // If we're here, then either an exception was thrown or the port is
        // a reserved port.
452 453 454 455 456 457
        if (ex==null) {
            throw new RuntimeException("Error getting unused random port. The"
                    +" last port returned by ServerSocket(0) was a reserved port");
        } else {
            throw new RuntimeException("Error getting unused random port.", ex);
        }
D
dmocek 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471
    }

    /**
     * Determines if a port is one of the reserved port numbers.
     *
     * @param port the port to test.
     * @return {@code true} if the port is a reserved port, otherwise
     *         {@code false}.
     */
    public static boolean isReservedPort(int port) {
        return ((port >= FIXED_PORT_MIN) && (port <= FIXED_PORT_MAX) ||
                (port == 1099));
    }

D
duke 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    /**
     * Method to capture the stack trace of an exception and return it
     * as a string.
     */
    public String stackTraceToString(Exception e) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        e.printStackTrace(ps);
        return bos.toString();
    }

    /** extra properties */
    private static Properties props;

    /**
     * Returns extra test properties. Looks for the file "../../test.props"
     * and reads it in as a Properties file. Assuming the working directory
     * is "<path>/JTwork/scratch", this will find "<path>/test.props".
     */
    private static synchronized Properties getExtraProperties() {
        if (props != null) {
            return props;
        }
        props = new Properties();
        File f = new File(".." + File.separator + ".." + File.separator +
                          "test.props");
        if (!f.exists()) {
            return props;
        }
        try {
            FileInputStream in = new FileInputStream(f);
            try {
                props.load(in);
            } finally {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("extra property setup failed", e);
        }
        return props;
    }

    /**
     * Returns an extra test property. Looks for the file "../../test.props"
     * and reads it in as a Properties file. Assuming the working directory
     * is "<path>/JTwork/scratch", this will find "<path>/test.props".
     * If the property isn't found, defaultVal is returned.
     */
    public static String getExtraProperty(String property, String defaultVal) {
        return getExtraProperties().getProperty(property, defaultVal);
    }
}