Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/rmi/testlibrary/TestLibrary.java
41149 views
1
/*
2
* Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
/**
25
*
26
*
27
* @author Adrian Colley
28
* @author Laird Dornin
29
* @author Peter Jones
30
* @author Ann Wollrath
31
*
32
* The rmi library directory contains a set of simple utiltity classes
33
* for use in rmi regression tests.
34
*
35
* NOTE: The JavaTest group has recommended that regression tests do
36
* not make use of packages.
37
*/
38
39
import java.io.ByteArrayOutputStream;
40
import java.io.File;
41
import java.io.FileInputStream;
42
import java.io.FileOutputStream;
43
import java.io.IOException;
44
import java.io.PrintStream;
45
import java.net.MalformedURLException;
46
import java.net.ServerSocket;
47
import java.net.URL;
48
import java.rmi.NoSuchObjectException;
49
import java.rmi.Remote;
50
import java.rmi.RemoteException;
51
import java.rmi.registry.LocateRegistry;
52
import java.rmi.registry.Registry;
53
import java.rmi.server.RemoteRef;
54
import java.rmi.server.UnicastRemoteObject;
55
import java.util.Enumeration;
56
import java.util.Properties;
57
58
import sun.rmi.registry.RegistryImpl;
59
import sun.rmi.server.UnicastServerRef;
60
import sun.rmi.transport.Endpoint;
61
import sun.rmi.transport.LiveRef;
62
import sun.rmi.transport.tcp.TCPEndpoint;
63
64
/**
65
* Class of utility/library methods (i.e. procedures) that assist with
66
* the writing and maintainance of rmi regression tests.
67
*/
68
public class TestLibrary {
69
/**
70
* IMPORTANT!
71
*
72
* RMI tests are run concurrently and port conflicts result when a single
73
* port number is used by multiple tests. When needing a port, use
74
* getUnusedRandomPort() wherever possible. If getUnusedRandomPort() cannot
75
* be used, reserve and specify a port to use for your test here. This
76
* will ensure there are no port conflicts amongst the RMI tests. The
77
* port numbers specified here may also be specified in the respective
78
* tests. Do not change the reserved port numbers here without also
79
* changing the port numbers in the respective tests.
80
*
81
* When needing an instance of the RMIRegistry, use
82
* createRegistryOnUnusedPort wherever possible to prevent port conflicts.
83
*
84
* Reserved port range: FIXED_PORT_MIN to FIXED_PORT_MAX (inclusive) for
85
* tests which cannot use a random port. If new fixed ports are added below
86
* FIXED_PORT_MIN or above FIXED_PORT_MAX, then adjust
87
* FIXED_PORT_MIN/MAX appropriately.
88
*/
89
public final static int FIXED_PORT_MIN = 60001;
90
public final static int FIXED_PORT_MAX = 60010;
91
public final static int INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT = 60003;
92
public final static int INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT = 60004;
93
public final static int READTEST_REGISTRY_PORT = 60005;
94
private final static int MAX_SERVER_SOCKET_TRIES = 2*(FIXED_PORT_MAX-FIXED_PORT_MIN+1);
95
96
static void mesg(Object mesg) {
97
System.err.println("TEST_LIBRARY: " + mesg.toString());
98
}
99
100
/**
101
* Routines that enable rmi tests to fail in a uniformly
102
* informative fashion.
103
*/
104
public static void bomb(String message, Exception e) {
105
String testFailed = "TEST FAILED: ";
106
107
if ((message == null) && (e == null)) {
108
testFailed += " No relevant information";
109
} else if (e == null) {
110
testFailed += message;
111
}
112
113
System.err.println(testFailed);
114
if (e != null) {
115
System.err.println("Test failed with: " +
116
e.getMessage());
117
e.printStackTrace(System.err);
118
}
119
throw new TestFailedException(testFailed, e);
120
}
121
public static void bomb(String message) {
122
bomb(message, null);
123
}
124
public static void bomb(Exception e) {
125
bomb(null, e);
126
}
127
128
/**
129
* Helper method to determine if registry has started
130
*
131
* @param port The port number to check
132
* @param msTimeout The amount of milliseconds to spend checking
133
*/
134
135
public static boolean checkIfRegistryRunning(int port, int msTimeout) {
136
final long POLLTIME_MS = 100L;
137
long stopTime = computeDeadline(System.currentTimeMillis(), msTimeout);
138
do {
139
try {
140
Registry r = LocateRegistry.getRegistry(port);
141
String[] s = r.list();
142
// no exception. We're now happy that registry is running
143
return true;
144
} catch (RemoteException e) {
145
// problem - not ready ? Try again
146
try {
147
Thread.sleep(POLLTIME_MS);
148
} catch (InterruptedException ie) {
149
// not expected
150
}
151
}
152
} while (System.currentTimeMillis() < stopTime);
153
return false;
154
}
155
156
public static String getProperty(final String property,
157
final String defaultVal) {
158
try {
159
return java.security.AccessController.doPrivileged(
160
new java.security.PrivilegedAction<String>() {
161
public String run() {
162
return System.getProperty(property, defaultVal);
163
}
164
});
165
} catch (Exception ex) {
166
bomb("Exception getting property " + property, ex);
167
throw new AssertionError("this should be unreachable");
168
}
169
}
170
171
public static double getTimeoutFactor() {
172
String prop = getProperty("test.timeout.factor", "1.0");
173
double timeoutFactor = 1.0;
174
175
try {
176
timeoutFactor = Double.parseDouble(prop);
177
} catch (NumberFormatException ignore) { }
178
179
return timeoutFactor;
180
}
181
182
/**
183
* Computes a deadline from a timestamp and a timeout value.
184
* Maximum timeout (before multipliers are applied) is one hour.
185
*/
186
public static long computeDeadline(long timestamp, long timeout) {
187
if (timeout < 0L) {
188
throw new IllegalArgumentException("timeout " + timeout + "ms out of range");
189
}
190
191
return timestamp + (long)(timeout * getTimeoutFactor());
192
}
193
194
/**
195
* Property mutators
196
*/
197
public static void setBoolean(String property, boolean value) {
198
setProperty(property, (new Boolean(value)).toString());
199
}
200
public static void setInteger(String property, int value) {
201
setProperty(property, Integer.toString(value));
202
}
203
public static void setProperty(String property, String value) {
204
final String prop = property;
205
final String val = value;
206
java.security.AccessController.doPrivileged(
207
new java.security.PrivilegedAction<Void>() {
208
public Void run() {
209
System.setProperty(prop, val);
210
return null;
211
}
212
});
213
}
214
215
/**
216
* Routines to print out a test's properties environment.
217
*/
218
public static void printEnvironment() {
219
printEnvironment(System.err);
220
}
221
public static void printEnvironment(PrintStream out) {
222
out.println("-------------------Test environment----------" +
223
"---------");
224
225
for(Enumeration<?> keys = System.getProperties().keys();
226
keys.hasMoreElements();) {
227
228
String property = (String) keys.nextElement();
229
out.println(property + " = " + getProperty(property, null));
230
}
231
out.println("---------------------------------------------" +
232
"---------");
233
}
234
235
/**
236
* Routine that "works-around" a limitation in jtreg.
237
* Currently it is not possible for a test to specify that the
238
* test harness should build a given source file and install the
239
* resulting class in a location that is not accessible from the
240
* test's classpath. This method enables a test to move a
241
* compiled test class file from the test's class directory into a
242
* given "codebase" directory. As a result the test can only
243
* access the class file for <code>className</code>if the test loads
244
* it from a classloader (e.g. RMIClassLoader).
245
*
246
* Tests that use this routine must have the following permissions
247
* granted to them:
248
*
249
* getProperty user.dir
250
* getProperty etc.
251
*/
252
public static URL installClassInCodebase(String className,
253
String codebase)
254
throws MalformedURLException
255
{
256
return installClassInCodebase(className, codebase, true);
257
}
258
259
public static URL installClassInCodebase(String className,
260
String codebase,
261
boolean delete)
262
throws MalformedURLException
263
{
264
/*
265
* NOTES/LIMITATIONS: The class must not be in a named package,
266
* and the codebase must be a relative path (it's created relative
267
* to the working directory).
268
*/
269
String classFileName = className + ".class";
270
271
/*
272
* Specify the file to contain the class definition. Make sure
273
* that the codebase directory exists (underneath the working
274
* directory).
275
*/
276
File dstDir = (new File(getProperty("user.dir", "."), codebase));
277
278
if (!dstDir.exists()) {
279
if (!dstDir.mkdir()) {
280
throw new RuntimeException(
281
"could not create codebase directory");
282
}
283
}
284
File dstFile = new File(dstDir, classFileName);
285
286
/*
287
* Obtain the URL for the codebase.
288
*/
289
URL codebaseURL = dstDir.toURI().toURL();
290
291
/*
292
* Specify where we will copy the class definition from, if
293
* necessary. After the test is built, the class file can be
294
* found in the "test.classes" directory.
295
*/
296
File srcDir = new File(getProperty("test.classes", "."));
297
File srcFile = new File(srcDir, classFileName);
298
299
mesg(srcFile);
300
mesg(dstFile);
301
302
/*
303
* If the class definition is not already located at the codebase,
304
* copy it there from the test build area.
305
*/
306
if (!dstFile.exists()) {
307
if (!srcFile.exists()) {
308
throw new RuntimeException(
309
"could not find class file to install in codebase " +
310
"(try rebuilding the test): " + srcFile);
311
}
312
313
try {
314
copyFile(srcFile, dstFile);
315
} catch (IOException e) {
316
throw new RuntimeException(
317
"could not install class file in codebase");
318
}
319
320
mesg("Installed class \"" + className +
321
"\" in codebase " + codebaseURL);
322
}
323
324
/*
325
* After the class definition is successfully installed at the
326
* codebase, delete it from the test's CLASSPATH, so that it will
327
* not be found there first before the codebase is searched.
328
*/
329
if (srcFile.exists()) {
330
if (delete && !srcFile.delete()) {
331
throw new RuntimeException(
332
"could not delete duplicate class file in CLASSPATH");
333
}
334
}
335
336
return codebaseURL;
337
}
338
339
public static void copyFile(File srcFile, File dstFile)
340
throws IOException
341
{
342
FileInputStream src = new FileInputStream(srcFile);
343
FileOutputStream dst = new FileOutputStream(dstFile);
344
345
byte[] buf = new byte[32768];
346
while (true) {
347
int count = src.read(buf);
348
if (count < 0) {
349
break;
350
}
351
dst.write(buf, 0, count);
352
}
353
354
dst.close();
355
src.close();
356
}
357
358
/** routine to unexport an object */
359
public static void unexport(Remote obj) {
360
if (obj != null) {
361
try {
362
mesg("unexporting object...");
363
UnicastRemoteObject.unexportObject(obj, true);
364
} catch (NoSuchObjectException munch) {
365
} catch (Exception e) {
366
e.getMessage();
367
e.printStackTrace();
368
}
369
}
370
}
371
372
/**
373
* Allow test framework to control the security manager set in
374
* each test.
375
*
376
* @param managerClassName The class name of the security manager
377
* to be instantiated and set if no security
378
* manager has already been set.
379
*/
380
public static void suggestSecurityManager(String managerClassName) {
381
SecurityManager manager = null;
382
383
if (System.getSecurityManager() == null) {
384
try {
385
if (managerClassName == null) {
386
managerClassName = TestParams.defaultSecurityManager;
387
}
388
manager = ((SecurityManager) Class.
389
forName(managerClassName).newInstance());
390
} catch (ClassNotFoundException cnfe) {
391
bomb("Security manager could not be found: " +
392
managerClassName, cnfe);
393
} catch (Exception e) {
394
bomb("Error creating security manager. ", e);
395
}
396
397
System.setSecurityManager(manager);
398
}
399
}
400
401
/**
402
* Creates an RMI {@link Registry} on a random, un-reserved port.
403
*
404
* @returns an RMI Registry, using a random port.
405
* @throws RemoteException if there was a problem creating a Registry.
406
*/
407
public static Registry createRegistryOnUnusedPort() throws RemoteException {
408
return LocateRegistry.createRegistry(getUnusedRandomPort());
409
}
410
411
/**
412
* Creates an RMI {@link Registry} on an ephemeral port.
413
*
414
* @returns an RMI Registry
415
* @throws RemoteException if there was a problem creating a Registry.
416
*/
417
public static Registry createRegistryOnEphemeralPort() throws RemoteException {
418
return LocateRegistry.createRegistry(0);
419
}
420
421
/**
422
* Returns the port number the RMI {@link Registry} is running on.
423
*
424
* @param registry the registry to find the port of.
425
* @return the port number the registry is using.
426
* @throws RuntimeException if there was a problem getting the port number.
427
*/
428
public static int getRegistryPort(Registry registry) {
429
int port = -1;
430
431
try {
432
RemoteRef remoteRef = ((RegistryImpl)registry).getRef();
433
LiveRef liveRef = ((UnicastServerRef)remoteRef).getLiveRef();
434
Endpoint endpoint = liveRef.getChannel().getEndpoint();
435
TCPEndpoint tcpEndpoint = (TCPEndpoint) endpoint;
436
port = tcpEndpoint.getPort();
437
} catch (Exception ex) {
438
throw new RuntimeException("Error getting registry port.", ex);
439
}
440
441
return port;
442
}
443
444
/**
445
* Returns an unused random port number which is not a reserved port. Will
446
* try up to 10 times to get a random port before giving up and throwing a
447
* RuntimeException.
448
*
449
* @return an unused random port number.
450
* @throws RuntimeException if there was a problem getting a port.
451
*/
452
public static int getUnusedRandomPort() {
453
int numTries = 0;
454
IOException ex = null;
455
456
while (numTries++ < MAX_SERVER_SOCKET_TRIES) {
457
int unusedRandomPort = -1;
458
ex = null; //reset
459
460
try (ServerSocket ss = new ServerSocket(0)) {
461
unusedRandomPort = ss.getLocalPort();
462
} catch (IOException e) {
463
ex = e;
464
// temporarily print stack trace here until we find out why
465
// tests are failing.
466
System.err.println("TestLibrary.getUnusedRandomPort() caught "
467
+ "exception on iteration " + numTries
468
+ (numTries==MAX_SERVER_SOCKET_TRIES ? " (the final try)."
469
: "."));
470
ex.printStackTrace();
471
}
472
473
if (unusedRandomPort >= 0) {
474
if (isReservedPort(unusedRandomPort)) {
475
System.out.println("INFO: On try # " + numTries
476
+ (numTries==MAX_SERVER_SOCKET_TRIES ? ", the final try, ": ",")
477
+ " ServerSocket(0) returned the reserved port "
478
+ unusedRandomPort
479
+ " in TestLibrary.getUnusedRandomPort() ");
480
} else {
481
return unusedRandomPort;
482
}
483
}
484
}
485
486
// If we're here, then either an exception was thrown or the port is
487
// a reserved port.
488
if (ex==null) {
489
throw new RuntimeException("Error getting unused random port. The"
490
+" last port returned by ServerSocket(0) was a reserved port");
491
} else {
492
throw new RuntimeException("Error getting unused random port.", ex);
493
}
494
}
495
496
/**
497
* Determines if a port is one of the reserved port numbers.
498
*
499
* @param port the port to test.
500
* @return {@code true} if the port is a reserved port, otherwise
501
* {@code false}.
502
*/
503
public static boolean isReservedPort(int port) {
504
return ((port >= FIXED_PORT_MIN) && (port <= FIXED_PORT_MAX) ||
505
(port == 1099));
506
}
507
508
/**
509
* Method to capture the stack trace of an exception and return it
510
* as a string.
511
*/
512
public String stackTraceToString(Exception e) {
513
ByteArrayOutputStream bos = new ByteArrayOutputStream();
514
PrintStream ps = new PrintStream(bos);
515
516
e.printStackTrace(ps);
517
return bos.toString();
518
}
519
520
/** extra properties */
521
private static Properties props;
522
523
/**
524
* Returns extra test properties. Looks for the file "../../test.props"
525
* and reads it in as a Properties file. Assuming the working directory
526
* is "<path>/JTwork/scratch", this will find "<path>/test.props".
527
*/
528
private static synchronized Properties getExtraProperties() {
529
if (props != null) {
530
return props;
531
}
532
props = new Properties();
533
File f = new File(".." + File.separator + ".." + File.separator +
534
"test.props");
535
if (!f.exists()) {
536
return props;
537
}
538
try {
539
FileInputStream in = new FileInputStream(f);
540
try {
541
props.load(in);
542
} finally {
543
in.close();
544
}
545
} catch (IOException e) {
546
e.printStackTrace();
547
throw new RuntimeException("extra property setup failed", e);
548
}
549
return props;
550
}
551
552
/**
553
* Returns an extra test property. Looks for the file "../../test.props"
554
* and reads it in as a Properties file. Assuming the working directory
555
* is "<path>/JTwork/scratch", this will find "<path>/test.props".
556
* If the property isn't found, defaultVal is returned.
557
*/
558
public static String getExtraProperty(String property, String defaultVal) {
559
return getExtraProperties().getProperty(property, defaultVal);
560
}
561
}
562
563