提交 4d0e56aa 编写于 作者: V valeriep

Merge

......@@ -134,7 +134,7 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
} else {
try {
(new NativeUnpack(this)).run(in0, out);
} catch (UnsatisfiedLinkError ule) {
} catch (UnsatisfiedLinkError | NoClassDefFoundError ex) {
// failover to java implementation
(new DoUnpack()).run(in0, out);
}
......
......@@ -52,6 +52,7 @@ import javax.management.NotCompliantMBeanException;
import com.sun.jmx.remote.util.EnvHelp;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import javax.management.AttributeNotFoundException;
import javax.management.openmbean.CompositeData;
import sun.reflect.misc.MethodUtil;
......@@ -64,7 +65,11 @@ import sun.reflect.misc.ReflectUtil;
* @since 1.5
*/
public class Introspector {
final public static boolean ALLOW_NONPUBLIC_MBEAN;
static {
String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic"));
ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(val);
}
/*
* ------------------------------------------
......@@ -223,11 +228,27 @@ public class Introspector {
return testCompliance(baseClass, null);
}
/**
* Tests the given interface class for being a compliant MXBean interface.
* A compliant MXBean interface is any publicly accessible interface
* following the {@link MXBean} conventions.
* @param interfaceClass An interface class to test for the MXBean compliance
* @throws NotCompliantMBeanException Thrown when the tested interface
* is not public or contradicts the {@link MXBean} conventions.
*/
public static void testComplianceMXBeanInterface(Class<?> interfaceClass)
throws NotCompliantMBeanException {
MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
}
/**
* Tests the given interface class for being a compliant MBean interface.
* A compliant MBean interface is any publicly accessible interface
* following the {@code MBean} conventions.
* @param interfaceClass An interface class to test for the MBean compliance
* @throws NotCompliantMBeanException Thrown when the tested interface
* is not public or contradicts the {@code MBean} conventions.
*/
public static void testComplianceMBeanInterface(Class<?> interfaceClass)
throws NotCompliantMBeanException{
StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass);
......@@ -299,18 +320,18 @@ public class Introspector {
* not a JMX compliant Standard MBean.
*/
public static <T> Class<? super T> getStandardMBeanInterface(Class<T> baseClass)
throws NotCompliantMBeanException {
Class<? super T> current = baseClass;
Class<? super T> mbeanInterface = null;
while (current != null) {
mbeanInterface =
findMBeanInterface(current, current.getName());
if (mbeanInterface != null) break;
current = current.getSuperclass();
}
if (mbeanInterface != null) {
return mbeanInterface;
} else {
throws NotCompliantMBeanException {
Class<? super T> current = baseClass;
Class<? super T> mbeanInterface = null;
while (current != null) {
mbeanInterface =
findMBeanInterface(current, current.getName());
if (mbeanInterface != null) break;
current = current.getSuperclass();
}
if (mbeanInterface != null) {
return mbeanInterface;
} else {
final String msg =
"Class " + baseClass.getName() +
" is not a JMX compliant Standard MBean";
......@@ -507,8 +528,11 @@ public class Introspector {
}
Class<?>[] interfaces = c.getInterfaces();
for (int i = 0;i < interfaces.length; i++) {
if (interfaces[i].getName().equals(clMBeanName))
if (interfaces[i].getName().equals(clMBeanName) &&
(Modifier.isPublic(interfaces[i].getModifiers()) ||
ALLOW_NONPUBLIC_MBEAN)) {
return Util.cast(interfaces[i]);
}
}
return null;
......
......@@ -28,6 +28,8 @@ package com.sun.jmx.mbeanserver;
import static com.sun.jmx.mbeanserver.Util.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
......@@ -50,7 +52,6 @@ import javax.management.NotCompliantMBeanException;
* @since 1.6
*/
class MBeanAnalyzer<M> {
static interface MBeanVisitor<M> {
public void visitAttribute(String attributeName,
M getter,
......@@ -107,6 +108,10 @@ class MBeanAnalyzer<M> {
if (!mbeanType.isInterface()) {
throw new NotCompliantMBeanException("Not an interface: " +
mbeanType.getName());
} else if (!Modifier.isPublic(mbeanType.getModifiers()) &&
!Introspector.ALLOW_NONPUBLIC_MBEAN) {
throw new NotCompliantMBeanException("Interface is not public: " +
mbeanType.getName());
}
try {
......
......@@ -252,13 +252,12 @@ public abstract class AbstractSaslImpl {
/**
* Outputs a byte array and converts
* Outputs a byte array. Can be null.
*/
protected static final void traceOutput(String srcClass, String srcMethod,
String traceTag, byte[] output) {
if (output != null) {
traceOutput(srcClass, srcMethod, traceTag, output, 0, output.length);
}
traceOutput(srcClass, srcMethod, traceTag, output, 0,
output == null ? 0 : output.length);
}
protected static final void traceOutput(String srcClass, String srcMethod,
......@@ -274,13 +273,20 @@ public abstract class AbstractSaslImpl {
lev = Level.FINEST;
}
ByteArrayOutputStream out = new ByteArrayOutputStream(len);
new HexDumpEncoder().encodeBuffer(
new ByteArrayInputStream(output, offset, len), out);
String content;
if (output != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream(len);
new HexDumpEncoder().encodeBuffer(
new ByteArrayInputStream(output, offset, len), out);
content = out.toString();
} else {
content = "NULL";
}
// Message id supplied by caller as part of traceTag
logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
new Object[] {traceTag, new Integer(origlen), out.toString()});
new Object[] {traceTag, new Integer(origlen), content});
} catch (Exception e) {
logger.logp(Level.WARNING, srcClass, srcMethod,
"SASLIMPL09:Error generating trace output: {0}", e);
......
......@@ -1910,7 +1910,7 @@ public class File
}
String name = prefix + Long.toString(n) + suffix;
File f = new File(dir, name);
if (!name.equals(f.getName()))
if (!name.equals(f.getName()) || f.isInvalid())
throw new IOException("Unable to create temporary file");
return f;
}
......@@ -1996,19 +1996,26 @@ public class File
File tmpdir = (directory != null) ? directory
: TempDirectory.location();
SecurityManager sm = System.getSecurityManager();
File f;
try {
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
} while (f.exists());
if (!f.createNewFile())
throw new IOException("Unable to create temporary file");
} catch (SecurityException se) {
// don't reveal temporary directory location
if (directory == null)
throw new SecurityException("Unable to create temporary file");
throw se;
}
do {
f = TempDirectory.generateFile(prefix, suffix, tmpdir);
if (sm != null) {
try {
sm.checkWrite(f.getPath());
} catch (SecurityException se) {
// don't reveal temporary directory location
if (directory == null)
throw new SecurityException("Unable to create temporary file");
throw se;
}
}
} while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0);
if (!fs.createFileExclusively(f.getPath()))
throw new IOException("Unable to create temporary file");
return f;
}
......
/*
* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
......@@ -42,7 +42,7 @@ import sun.management.LockInfoCompositeData;
* {@link ReentrantReadWriteLock ReentrantReadWriteLock} are
* two examples of ownable synchronizers provided by the platform.
*
* <h4><a name="MappedType">MXBean Mapping</a></h4>
* <h3><a name="MappedType">MXBean Mapping</a></h3>
* <tt>LockInfo</tt> is mapped to a {@link CompositeData CompositeData}
* as specified in the {@link #from from} method.
*
......@@ -105,7 +105,7 @@ public class LockInfo {
* given {@code CompositeData}.
* The given {@code CompositeData} must contain the following attributes:
* <blockquote>
* <table border>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......
......@@ -61,7 +61,7 @@ import sun.management.ManagementFactoryHelper;
* the management interface of a component of the Java virtual
* machine.
* <p>
* <h4><a name="MXBean">Platform MXBeans</a></h4>
* <h3><a name="MXBean">Platform MXBeans</a></h3>
* <p>
* A platform MXBean is a <i>managed bean</i> that
* conforms to the <a href="../../../javax/management/package-summary.html">JMX</a>
......@@ -87,7 +87,7 @@ import sun.management.ManagementFactoryHelper;
*
* <p>
* An application can access a platform MXBean in the following ways:
* <h5>1. Direct access to an MXBean interface</h5>
* <h4>1. Direct access to an MXBean interface</h4>
* <blockquote>
* <ul>
* <li>Get an MXBean instance by calling the
......@@ -107,7 +107,7 @@ import sun.management.ManagementFactoryHelper;
* an MXBean of another running virtual machine.
* </li>
* </ul>
* <h5>2. Indirect access to an MXBean interface via MBeanServer</h5>
* <h4>2. Indirect access to an MXBean interface via MBeanServer</h4>
* <ul>
* <li>Go through the platform {@code MBeanServer} to access MXBeans
* locally or a specific <tt>MBeanServerConnection</tt> to access
......@@ -135,7 +135,7 @@ import sun.management.ManagementFactoryHelper;
* interfaces:
*
* <blockquote>
* <table border>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
......@@ -178,7 +178,7 @@ import sun.management.ManagementFactoryHelper;
* the following management interfaces.
*
* <blockquote>
* <table border>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
......@@ -195,7 +195,7 @@ import sun.management.ManagementFactoryHelper;
* A Java virtual machine may have one or more instances of the following
* management interfaces.
* <blockquote>
* <table border>
* <table border summary="The list of Management Interfaces and their single instances">
* <tr>
* <th>Management Interface</th>
* <th>ObjectName</th>
......@@ -561,6 +561,12 @@ public class ManagementFactory {
* in the format of {@link ObjectName ObjectName}.
* @param mxbeanInterface the MXBean interface to be implemented
* by the proxy.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return a proxy for a platform MXBean interface of a
* given <a href="#MXBeanNames">MXBean name</a>
* that forwards its method calls through the given
* <tt>MBeanServerConnection</tt>, or {@code null} if not exist.
*
* @throws IllegalArgumentException if
* <ul>
......@@ -635,6 +641,7 @@ public class ManagementFactory {
* @param mxbeanInterface a management interface for a platform
* MXBean with one single instance in the Java virtual machine
* if implemented.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the platform MXBean that implements
* {@code mxbeanInterface}, or {@code null} if not exist.
......@@ -670,6 +677,7 @@ public class ManagementFactory {
*
* @param mxbeanInterface a management interface for a platform
* MXBean
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the list of platform MXBeans that implement
* {@code mxbeanInterface}.
......@@ -707,6 +715,7 @@ public class ManagementFactory {
* @param mxbeanInterface a management interface for a platform
* MXBean with one single instance in the Java virtual machine
* being monitored, if implemented.
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the platform MXBean proxy for
* forwarding the method calls of the {@code mxbeanInterface}
......@@ -750,6 +759,7 @@ public class ManagementFactory {
* @param connection the {@code MBeanServerConnection} to forward to.
* @param mxbeanInterface a management interface for a platform
* MXBean
* @param <T> an {@code mxbeanInterface} type parameter
*
* @return the list of platform MXBean proxies for
* forwarding the method calls of the {@code mxbeanInterface}
......
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -49,11 +49,11 @@ import javax.management.openmbean.CompositeData;
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4> Memory </h4>
* <h3> Memory </h3>
* The memory system of the Java virtual machine manages
* the following kinds of memory:
*
* <h4> 1. Heap </h4>
* <h3> 1. Heap </h3>
* The Java virtual machine has a <i>heap</i> that is the runtime
* data area from which memory for all class instances and arrays
* are allocated. It is created at the Java virtual machine start-up.
......@@ -63,7 +63,7 @@ import javax.management.openmbean.CompositeData;
* <p>The heap may be of a fixed size or may be expanded and shrunk.
* The memory for the heap does not need to be contiguous.
*
* <h4> 2. Non-Heap Memory</h4>
* <h3> 2. Non-Heap Memory</h3>
* The Java virtual machine manages memory other than the heap
* (referred as <i>non-heap memory</i>).
*
......@@ -87,7 +87,7 @@ import javax.management.openmbean.CompositeData;
* machine code translated from the Java virtual machine code for
* high performance.
*
* <h4>Memory Pools and Memory Managers</h4>
* <h3>Memory Pools and Memory Managers</h3>
* {@link MemoryPoolMXBean Memory pools} and
* {@link MemoryManagerMXBean memory managers} are the abstract entities
* that monitor and manage the memory system
......@@ -105,7 +105,7 @@ import javax.management.openmbean.CompositeData;
* add or remove memory managers during execution.
* A memory pool can be managed by more than one memory manager.
*
* <h4>Memory Usage Monitoring</h4>
* <h3>Memory Usage Monitoring</h3>
*
* Memory usage is a very important monitoring attribute for the memory system.
* The memory usage, for example, could indicate:
......@@ -131,7 +131,7 @@ import javax.management.openmbean.CompositeData;
* certain threshold. It is not intended for an application to detect
* and recover from a low memory condition.
*
* <h4>Notifications</h4>
* <h3>Notifications</h3>
*
* <p>This <tt>MemoryMXBean</tt> is a
* {@link javax.management.NotificationEmitter NotificationEmitter}
......@@ -169,7 +169,7 @@ import javax.management.openmbean.CompositeData;
* MemoryNotificationInfo}.
*
* <hr>
* <h4>NotificationEmitter</h4>
* <h3>NotificationEmitter</h3>
* The <tt>MemoryMXBean</tt> object returned by
* {@link ManagementFactory#getMemoryMXBean} implements
* the {@link javax.management.NotificationEmitter NotificationEmitter}
......
/*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -212,7 +212,7 @@ public class MemoryNotificationInfo {
* The given <tt>CompositeData</tt> must contain
* the following attributes:
* <blockquote>
* <table border>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -49,7 +49,7 @@ package java.lang.management;
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4>Memory Type</h4>
* <h3>Memory Type</h3>
* <p>The Java virtual machine has a heap for object allocation and also
* maintains non-heap memory for the method area and the Java virtual
* machine execution. The Java virtual machine can have one or more
......@@ -60,7 +60,7 @@ package java.lang.management;
* <li>{@link MemoryType#NON_HEAP non-heap}</li>
* </ul>
*
* <h4>Memory Usage Monitoring</h4>
* <h3>Memory Usage Monitoring</h3>
*
* A memory pool has the following attributes:
* <ul>
......@@ -71,7 +71,7 @@ package java.lang.management;
* (only supported by some <em>garbage-collected</em> memory pools)</li>
* </ul>
*
* <h4><a name="Usage">1. Memory Usage</a></h4>
* <h3><a name="Usage">1. Memory Usage</a></h3>
*
* The {@link #getUsage} method provides an estimate
* of the current usage of a memory pool.
......@@ -86,14 +86,14 @@ package java.lang.management;
* the current memory usage. An implementation should document when
* this is the case.
*
* <h4><a name="PeakUsage">2. Peak Memory Usage</a></h4>
* <h3><a name="PeakUsage">2. Peak Memory Usage</a></h3>
*
* The Java virtual machine maintains the peak memory usage of a memory
* pool since the virtual machine was started or the peak was reset.
* The peak memory usage is returned by the {@link #getPeakUsage} method
* and reset by calling the {@link #resetPeakUsage} method.
*
* <h4><a name="UsageThreshold">3. Usage Threshold</a></h4>
* <h3><a name="UsageThreshold">3. Usage Threshold</a></h3>
*
* Each memory pool has a manageable attribute
* called the <i>usage threshold</i> which has a default value supplied
......@@ -304,7 +304,7 @@ package java.lang.management;
* </li>
* </ol>
*
* <h4><a name="CollectionThreshold">4. Collection Usage Threshold</a></h4>
* <h3><a name="CollectionThreshold">4. Collection Usage Threshold</a></h3>
*
* Collection usage threshold is a manageable attribute only applicable
* to some garbage-collected memory pools.
......
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -36,8 +36,7 @@ import sun.management.MemoryUsageCompositeData;
* the heap or non-heap memory of the Java virtual machine as a whole.
*
* <p> A <tt>MemoryUsage</tt> object contains four values:
* <ul>
* <table>
* <table summary="Describes the MemoryUsage object content">
* <tr>
* <td valign=top> <tt>init</tt> </td>
* <td valign=top> represents the initial amount of memory (in bytes) that
......@@ -78,7 +77,6 @@ import sun.management.MemoryUsageCompositeData;
* </td>
* </tr>
* </table>
* </ul>
*
* Below is a picture showing an example of a memory pool:
* <p>
......@@ -98,7 +96,7 @@ import sun.management.MemoryUsageCompositeData;
* max
* </pre>
*
* <h4>MXBean Mapping</h4>
* <h3>MXBean Mapping</h3>
* <tt>MemoryUsage</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in the {@link #from from} method.
*
......@@ -254,7 +252,7 @@ public class MemoryUsage {
* must contain the following attributes:
* <p>
* <blockquote>
* <table border>
* <table border summary="The attributes and the types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
......@@ -32,7 +32,7 @@ import sun.management.MonitorInfoCompositeData;
* Information about an object monitor lock. An object monitor is locked
* when entering a synchronization block or method on that object.
*
* <h4>MXBean Mapping</h4>
* <h3>MXBean Mapping</h3>
* <tt>MonitorInfo</tt> is mapped to a {@link CompositeData CompositeData}
* with attributes as specified in
* the {@link #from from} method.
......@@ -106,7 +106,7 @@ public class MonitorInfo extends LockInfo {
* <a href="LockInfo.html#MappedType">
* mapped type</a> for the {@link LockInfo} class:
* <blockquote>
* <table border>
* <table border summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -272,7 +272,7 @@ public interface RuntimeMXBean extends PlatformManagedObject {
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>List<String></tt> is <tt>String[]</tt>.
* The mapped type of {@code List<String>} is <tt>String[]</tt>.
*
* @return a list of <tt>String</tt> objects; each element
* is an argument passed to the Java virtual machine.
......@@ -312,7 +312,7 @@ public interface RuntimeMXBean extends PlatformManagedObject {
* {@link javax.management.openmbean.TabularData TabularData}
* with two items in each row as follows:
* <blockquote>
* <table border>
* <table border summary="Name and Type for each item">
* <tr>
* <th>Item Name</th>
* <th>Item Type</th>
......
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -33,13 +33,13 @@ import static java.lang.Thread.State.*;
/**
* Thread information. <tt>ThreadInfo</tt> contains the information
* about a thread including:
* <h4>General thread information</h4>
* <h3>General thread information</h3>
* <ul>
* <li>Thread ID.</li>
* <li>Name of the thread.</li>
* </ul>
*
* <h4>Execution information</h4>
* <h3>Execution information</h3>
* <ul>
* <li>Thread state.</li>
* <li>The object upon which the thread is blocked due to:
......@@ -652,7 +652,7 @@ public class ThreadInfo {
* The given <tt>CompositeData</tt> must contain the following attributes
* unless otherwise specified below:
* <blockquote>
* <table border>
* <table border summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......@@ -722,7 +722,7 @@ public class ThreadInfo {
* Each element is a <tt>CompositeData</tt> representing
* StackTraceElement containing the following attributes:
* <blockquote>
* <table cellspacing=1 cellpadding=0>
* <table cellspacing=1 cellpadding=0 summary="The attributes and their types the given CompositeData contains">
* <tr>
* <th align=left>Attribute Name</th>
* <th align=left>Type</th>
......
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -49,7 +49,7 @@ import java.util.Map;
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4>Thread ID</h4>
* <h3>Thread ID</h3>
* Thread ID is a positive long value returned by calling the
* {@link java.lang.Thread#getId} method for a thread.
* The thread ID is unique during its lifetime. When a thread
......@@ -58,7 +58,7 @@ import java.util.Map;
* <p> Some methods in this interface take a thread ID or an array
* of thread IDs as the input parameter and return per-thread information.
*
* <h4>Thread CPU time</h4>
* <h3>Thread CPU time</h3>
* A Java virtual machine implementation may support measuring
* the CPU time for the current thread, for any thread, or for no threads.
*
......@@ -83,7 +83,7 @@ import java.util.Map;
* Enabling thread CPU measurement could be expensive in some
* Java virtual machine implementations.
*
* <h4>Thread Contention Monitoring</h4>
* <h3>Thread Contention Monitoring</h3>
* Some Java virtual machines may support thread contention monitoring.
* When thread contention monitoring is enabled, the accumulated elapsed
* time that the thread has blocked for synchronization or waited for
......@@ -96,7 +96,7 @@ import java.util.Map;
* {@link #setThreadContentionMonitoringEnabled} method can be used to enable
* thread contention monitoring.
*
* <h4>Synchronization Information and Deadlock Detection</h4>
* <h3>Synchronization Information and Deadlock Detection</h3>
* Some Java virtual machines may support monitoring of
* {@linkplain #isObjectMonitorUsageSupported object monitor usage} and
* {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}.
......
......@@ -2592,14 +2592,18 @@ public class BigDecimal extends Number implements Comparable<BigDecimal> {
* the {@code BigDecimal} value {@code 600.0}, which has
* [{@code BigInteger}, {@code scale}] components equals to
* [6000, 1], yields {@code 6E2} with [{@code BigInteger},
* {@code scale}] components equals to [6, -2]
* {@code scale}] components equals to [6, -2]. If
* this BigDecimal is numerically equal to zero, then
* {@code BigDecimal.ZERO} is returned.
*
* @return a numerically equal {@code BigDecimal} with any
* trailing zeros removed.
* @since 1.5
*/
public BigDecimal stripTrailingZeros() {
if(intCompact!=INFLATED) {
if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {
return BigDecimal.ZERO;
} else if (intCompact != INFLATED) {
return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
} else {
return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
......
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
......@@ -75,6 +75,8 @@ public interface CookieStore {
* @return an immutable list of HttpCookie,
* return empty list if no cookies match the given URI
*
* @param uri the uri associated with the cookies to be returned
*
* @throws NullPointerException if <tt>uri</tt> is <tt>null</tt>
*
* @see #add
......
......@@ -47,6 +47,7 @@ import java.security.Permission;
* in {@link java.io.FilePermission}. There are three different ways
* as the following examples show:
* <table border>
* <caption>URL Examples</caption>
* <tr><th>Example url</th><th>Description</th></tr>
* <tr><td style="white-space:nowrap;">http://www.oracle.com/a/b/c.html</td>
* <td>A url which identifies a specific (single) resource</td>
......@@ -57,7 +58,7 @@ import java.security.Permission;
* which only differ in the final path component, represented by the '*'.
* </td>
* </tr>
* <tr><td>http://www.oracle.com/a/b/-</li>
* <tr><td>http://www.oracle.com/a/b/-</td>
* <td>The '-' character refers to all resources recursively below the
* preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this
* example).
......@@ -164,6 +165,8 @@ public final class HttpURLPermission extends Permission {
* methods and request headers by invoking the two argument
* constructor as follows: HttpURLPermission(url, "*:*")
*
* @param url the url string
*
* @throws IllegalArgumentException if url does not result in a valid {@link URI}
*/
public HttpURLPermission(String url) {
......@@ -204,11 +207,10 @@ public final class HttpURLPermission extends Permission {
* <li>if the path or paths specified by p's url are contained in the
* set of paths specified by this's url, then return true
* <li>otherwise, return false</li>
* </ol>
* <p>
* Some examples of how paths are matched are shown below:
* <p>
* <table border>
* </ul>
* <p>Some examples of how paths are matched are shown below:
* <p><table border>
* <caption>Examples of Path Matching</caption>
* <tr><th>this's path</th><th>p's path</th><th>match</th></tr>
* <tr><td>/a/b</td><td>/a/b</td><td>yes</td></tr>
* <tr><td>/a/b/*</td><td>/a/b/c</td><td>yes</td></tr>
......
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 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
......@@ -36,7 +36,7 @@ import java.io.ObjectStreamException;
* and <a href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
* Administratively Scoped IP Multicast</i></a>
*
* <h4> <A NAME="format">Textual representation of IP addresses</a> </h4>
* <h3> <A NAME="format">Textual representation of IP addresses</a> </h3>
*
* Textual representation of IPv4 address used as input to methods
* takes one of the following forms:
......
......@@ -35,7 +35,7 @@ import java.util.Enumeration;
* Defined by <a href="http://www.ietf.org/rfc/rfc2373.txt">
* <i>RFC&nbsp;2373: IP Version 6 Addressing Architecture</i></a>.
*
* <h4> <A NAME="format">Textual representation of IP addresses</a> </h4>
* <h3> <A NAME="format">Textual representation of IP addresses</a> </h3>
*
* Textual representation of IPv6 address used as input to methods
* takes one of the following forms:
......@@ -156,7 +156,7 @@ import java.util.Enumeration;
* system. Usually, the numeric values can be determined through administration
* tools on the system. Each interface may have multiple values, one for each
* scope. If the scope is unspecified, then the default value used is zero.</li>
* <p><li><i>As a string.</i> This must be the exact string that is returned by
* <li><i>As a string.</i> This must be the exact string that is returned by
* {@link java.net.NetworkInterface#getName()} for the particular interface in
* question. When an Inet6Address is created in this way, the numeric scope-id
* is determined at the time the object is created by querying the relevant
......
/*
* Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 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
......@@ -65,7 +65,7 @@ import sun.net.spi.nameservice.*;
* with a host name or whether it has already done reverse host name
* resolution).
*
* <h4> Address types </h4>
* <h3> Address types </h3>
*
* <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
* <tr><th valign=top><i>unicast</i></th>
......@@ -165,7 +165,6 @@ import sun.net.spi.nameservice.*;
* <p>
* A value of -1 indicates "cache forever".
* </dd>
* <p>
* <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
* <dd>Indicates the caching policy for un-successful name lookups
* from the name service. The value is specified as as integer to
......
/*
* Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 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
......@@ -34,6 +34,8 @@ package java.net;
public interface ProtocolFamily {
/**
* Returns the name of the protocol family.
*
* @return the name of the protocol family
*/
String name();
}
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 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
......@@ -45,11 +45,15 @@ public interface SocketOption<T> {
/**
* Returns the name of the socket option.
*
* @return the name of the socket option
*/
String name();
/**
* Returns the type of the socket option value.
*
* @return the type of the socket option value
*/
Class<T> type();
}
/*
* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 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
......@@ -61,13 +61,13 @@ import java.lang.NullPointerException; // for javadoc
* and relativizing URI instances. Instances of this class are immutable.
*
*
* <h4> URI syntax and components </h4>
* <h3> URI syntax and components </h3>
*
* At the highest level a URI reference (hereinafter simply "URI") in string
* form has the syntax
*
* <blockquote>
* [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
* [<i>scheme</i><tt><b>:</b></tt>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
* </blockquote>
*
* where square brackets [...] delineate optional components and the characters
......@@ -334,14 +334,14 @@ import java.lang.NullPointerException; // for javadoc
*
* <ul>
*
* <li><p> The {@link #URI(java.lang.String) <code>single-argument
* constructor</code>} requires any illegal characters in its argument to be
* <li><p> The {@linkplain #URI(java.lang.String) single-argument
* constructor} requires any illegal characters in its argument to be
* quoted and preserves any escaped octets and <i>other</i> characters that
* are present. </p></li>
*
* <li><p> The {@link
* <li><p> The {@linkplain
* #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
* <code>multi-argument constructors</code>} quote illegal characters as
* multi-argument constructors} quote illegal characters as
* required by the components in which they appear. The percent character
* (<tt>'%'</tt>) is always quoted by these constructors. Any <i>other</i>
* characters are preserved. </p></li>
......
......@@ -34,6 +34,8 @@ import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This class consists exclusively of static methods that operate on or return
......@@ -1510,6 +1512,86 @@ public class Collections {
// Need to cast to raw in order to work around a limitation in the type system
super((Set)s);
}
static <K, V> Consumer<Map.Entry<K, V>> entryConsumer(Consumer<? super Entry<K, V>> action) {
return e -> action.accept(new UnmodifiableEntry<>(e));
}
public void forEach(Consumer<? super Entry<K, V>> action) {
Objects.requireNonNull(action);
c.forEach(entryConsumer(action));
}
static final class UnmodifiableEntrySetSpliterator<K, V>
implements Spliterator<Entry<K,V>> {
final Spliterator<Map.Entry<K, V>> s;
UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {
this.s = s;
}
@Override
public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
Objects.requireNonNull(action);
return s.tryAdvance(entryConsumer(action));
}
@Override
public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
Objects.requireNonNull(action);
s.forEachRemaining(entryConsumer(action));
}
@Override
public Spliterator<Entry<K, V>> trySplit() {
Spliterator<Entry<K, V>> split = s.trySplit();
return split == null
? null
: new UnmodifiableEntrySetSpliterator<>(split);
}
@Override
public long estimateSize() {
return s.estimateSize();
}
@Override
public long getExactSizeIfKnown() {
return s.getExactSizeIfKnown();
}
@Override
public int characteristics() {
return s.characteristics();
}
@Override
public boolean hasCharacteristics(int characteristics) {
return s.hasCharacteristics(characteristics);
}
@Override
public Comparator<? super Entry<K, V>> getComparator() {
return s.getComparator();
}
}
@SuppressWarnings("unchecked")
public Spliterator<Entry<K,V>> spliterator() {
return new UnmodifiableEntrySetSpliterator<>(
(Spliterator<Map.Entry<K, V>>) c.spliterator());
}
@Override
public Stream<Entry<K,V>> stream() {
return StreamSupport.stream(spliterator());
}
@Override
public Stream<Entry<K,V>> parallelStream() {
return StreamSupport.parallelStream(spliterator());
}
public Iterator<Map.Entry<K,V>> iterator() {
return new Iterator<Map.Entry<K,V>>() {
private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
......
......@@ -190,7 +190,7 @@ import sun.misc.FormattedFloatingDecimal;
* <p> The optional <i>flags</i> is a set of characters that modify the output
* format. The set of valid flags depends on the conversion.
*
* <p> The optional <i>width</i> is a non-negative decimal integer indicating
* <p> The optional <i>width</i> is a positive decimal integer indicating
* the minimum number of characters to be written to the output.
*
* <p> The optional <i>precision</i> is a non-negative decimal integer usually
......
......@@ -62,10 +62,10 @@ import java.util.function.LongConsumer;
* New characteristics may be defined in the future, so implementors should not
* assign meanings to unlisted values.
*
* <p><a name="binding"/>A Spliterator that does not report {@code IMMUTABLE} or
* <p><a name="binding">A Spliterator that does not report {@code IMMUTABLE} or
* {@code CONCURRENT} is expected to have a documented policy concerning:
* when the spliterator <em>binds</em> to the element source; and detection of
* structural interference of the element source detected after binding. A
* structural interference of the element source detected after binding.</a> A
* <em>late-binding</em> Spliterator binds to the source of elements at the
* point of first traversal, first split, or first query for estimated size,
* rather than at the time the Spliterator is created. A Spliterator that is
......@@ -429,6 +429,7 @@ public interface Spliterator<T> {
* The default implementation returns true if the corresponding bits
* of the given characteristics are set.
*
* @param characteristics the characteristics to check for
* @return {@code true} if all the specified characteristics are present,
* else {@code false}
*/
......
因为 它太大了无法显示 source diff 。你可以改为 查看blob
......@@ -39,8 +39,8 @@ import java.util.Objects;
import java.util.function.BiFunction;
/**
* A {@link java.util.Map} providing additional atomic
* {@code putIfAbsent}, {@code remove}, and {@code replace} methods.
* A {@link java.util.Map} providing thread safety and atomicity
* guarantees.
*
* <p>Memory consistency effects: As with other concurrent
* collections, actions in a thread prior to placing an object into a
......@@ -89,11 +89,11 @@ public interface ConcurrentMap<K, V> extends Map<K, V> {
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with the specified key, or
* <tt>null</tt> if there was no mapping for the key.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with the key,
* {@code null} if there was no mapping for the key.
* (A {@code null} return can also indicate that the map
* previously associated {@code null} with the key,
* if the implementation supports null values.)
* @throws UnsupportedOperationException if the <tt>put</tt> operation
* @throws UnsupportedOperationException if the {@code put} operation
* is not supported by this map
* @throws ClassCastException if the class of the specified key or value
* prevents it from being stored in this map
......
......@@ -101,7 +101,7 @@ public interface ConcurrentNavigableMap<K,V>
* reflected in the descending map, and vice-versa.
*
* <p>The returned map has an ordering equivalent to
* <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>.
* {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}.
* The expression {@code m.descendingMap().descendingMap()} returns a
* view of {@code m} essentially equivalent to {@code m}.
*
......
......@@ -92,22 +92,51 @@ abstract class AbstractShortCircuitTask<P_IN, P_OUT, R,
*/
protected abstract R getEmptyResult();
/**
* Overrides AbstractTask version to include checks for early
* exits while splitting or computing.
*/
@Override
protected boolean canCompute() {
// Have we already found an answer?
if (sharedResult.get() != null) {
tryComplete();
return false;
} else if (taskCanceled()) {
setLocalResult(getEmptyResult());
tryComplete();
return false;
}
else {
return true;
public void compute() {
Spliterator<P_IN> rs = spliterator, ls;
long sizeEstimate = rs.estimateSize();
long sizeThreshold = getTargetSize(sizeEstimate);
boolean forkRight = false;
@SuppressWarnings("unchecked") K task = (K) this;
AtomicReference<R> sr = sharedResult;
R result;
while ((result = sr.get()) == null) {
if (task.taskCanceled()) {
result = task.getEmptyResult();
break;
}
if (sizeEstimate <= sizeThreshold || (ls = rs.trySplit()) == null) {
result = task.doLeaf();
break;
}
K leftChild, rightChild, taskToFork;
task.leftChild = leftChild = task.makeChild(ls);
task.rightChild = rightChild = task.makeChild(rs);
task.setPendingCount(1);
if (forkRight) {
forkRight = false;
rs = ls;
task = leftChild;
taskToFork = rightChild;
}
else {
forkRight = true;
task = rightChild;
taskToFork = leftChild;
}
taskToFork.fork();
sizeEstimate = rs.estimateSize();
}
task.setLocalResult(result);
task.tryComplete();
}
/**
* Declares that a globally valid result has been found. If another task has
* not already found the answer, the result is installed in
......
......@@ -102,7 +102,7 @@ abstract class AbstractTask<P_IN, P_OUT, R,
protected Spliterator<P_IN> spliterator;
/** Target leaf size, common to all tasks in a computation */
protected final long targetSize;
protected long targetSize; // may be laziliy initialized
/**
* The left child.
......@@ -134,7 +134,7 @@ abstract class AbstractTask<P_IN, P_OUT, R,
super(null);
this.helper = helper;
this.spliterator = spliterator;
this.targetSize = suggestTargetSize(spliterator.estimateSize());
this.targetSize = 0L;
}
/**
......@@ -182,27 +182,13 @@ abstract class AbstractTask<P_IN, P_OUT, R,
}
/**
* Returns a suggestion whether it is advisable to split the provided
* spliterator based on target size and other considerations, such as pool
* state.
*
* @return {@code true} if a split is advised otherwise {@code false}
* Returns the targetSize, initializing it via the supplied
* size estimate if not already initialized.
*/
public static boolean suggestSplit(Spliterator spliterator,
long targetSize) {
long remaining = spliterator.estimateSize();
return (remaining > targetSize);
// @@@ May additionally want to fold in pool characteristics such as surplus task count
}
/**
* Returns a suggestion whether it is adviseable to split this task based on
* target size and other considerations.
*
* @return {@code true} if a split is advised otherwise {@code false}
*/
public boolean suggestSplit() {
return suggestSplit(spliterator, targetSize);
protected final long getTargetSize(long sizeEstimate) {
long s;
return ((s = targetSize) != 0 ? s :
(targetSize = suggestTargetSize(sizeEstimate)));
}
/**
......@@ -285,43 +271,46 @@ abstract class AbstractTask<P_IN, P_OUT, R,
}
/**
* Decides whether or not to split a task further or compute it directly. If
* computing directly, call {@code doLeaf} and pass the result to
* {@code setRawResult}. If splitting, set up the child-related fields,
* create the child tasks, fork the leftmost (prefix) child tasks, and
* compute the rightmost (remaining) child tasks.
* Decides whether or not to split a task further or compute it
* directly. If computing directly, calls {@code doLeaf} and pass
* the result to {@code setRawResult}. Otherwise splits off
* subtasks, forking one and continuing as the other.
*
* <p>
* Computing will continue for rightmost tasks while a task can be computed
* as determined by {@link #canCompute()} and that task should and can be
* split into left and right tasks.
*
* <p>
* The rightmost tasks are computed in a loop rather than recursively to
* avoid potential stack overflows when computing with a right-balanced
* tree, such as that produced when splitting with a {@link Spliterator}
* created from an {@link java.util.Iterator}.
* <p> The method is structured to conserve resources across a
* range of uses. The loop continues with one of the child tasks
* when split, to avoid deep recursion. To cope with spliterators
* that may be systematically biased toward left-heavy or
* right-heavy splits, we alternate which child is forked versus
* continued in the loop.
*/
@Override
public final void compute() {
@SuppressWarnings("unchecked")
K task = (K) this;
while (task.canCompute()) {
Spliterator<P_IN> split;
if (!task.suggestSplit() || (split = task.spliterator.trySplit()) == null) {
task.setLocalResult(task.doLeaf());
task.tryComplete();
return;
public void compute() {
Spliterator<P_IN> rs = spliterator, ls; // right, left spliterators
long sizeEstimate = rs.estimateSize();
long sizeThreshold = getTargetSize(sizeEstimate);
boolean forkRight = false;
@SuppressWarnings("unchecked") K task = (K) this;
while (sizeEstimate > sizeThreshold && (ls = rs.trySplit()) != null) {
K leftChild, rightChild, taskToFork;
task.leftChild = leftChild = task.makeChild(ls);
task.rightChild = rightChild = task.makeChild(rs);
task.setPendingCount(1);
if (forkRight) {
forkRight = false;
rs = ls;
task = leftChild;
taskToFork = rightChild;
}
else {
K l = task.leftChild = task.makeChild(split);
K r = task.rightChild = task.makeChild(task.spliterator);
task.spliterator = null;
task.setPendingCount(1);
l.fork();
task = r;
forkRight = true;
task = rightChild;
taskToFork = leftChild;
}
taskToFork.fork();
sizeEstimate = rs.estimateSize();
}
task.setLocalResult(task.doLeaf());
task.tryComplete();
}
/**
......@@ -338,21 +327,6 @@ abstract class AbstractTask<P_IN, P_OUT, R,
leftChild = rightChild = null;
}
/**
* Determines if the task can be computed.
*
* @implSpec The default always returns true
*
* @return {@code true} if this task can be computed to either calculate the
* leaf via {@link #doLeaf()} or split, otherwise false if this task
* cannot be computed, for example if this task has been canceled
* and/or a result for the computation has been found by another
* task.
*/
protected boolean canCompute() {
return true;
}
/**
* Returns whether this node is a "leftmost" node -- whether the path from
* the root to this node involves only traversing leftmost child links. For
......
......@@ -28,6 +28,7 @@ import java.util.Objects;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountedCompleter;
import java.util.concurrent.ForkJoinTask;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
......@@ -128,7 +129,7 @@ final class ForEachOps {
*
* @param <T> the output type of the stream pipeline
*/
private static abstract class ForEachOp<T>
static abstract class ForEachOp<T>
implements TerminalOp<T, Void>, TerminalSink<T, Void> {
private final boolean ordered;
......@@ -169,7 +170,7 @@ final class ForEachOps {
// Implementations
/** Implementation class for reference streams */
private static class OfRef<T> extends ForEachOp<T> {
static final class OfRef<T> extends ForEachOp<T> {
final Consumer<? super T> consumer;
OfRef(Consumer<? super T> consumer, boolean ordered) {
......@@ -184,7 +185,7 @@ final class ForEachOps {
}
/** Implementation class for {@code IntStream} */
private static class OfInt extends ForEachOp<Integer>
static final class OfInt extends ForEachOp<Integer>
implements Sink.OfInt {
final IntConsumer consumer;
......@@ -205,7 +206,7 @@ final class ForEachOps {
}
/** Implementation class for {@code LongStream} */
private static class OfLong extends ForEachOp<Long>
static final class OfLong extends ForEachOp<Long>
implements Sink.OfLong {
final LongConsumer consumer;
......@@ -226,7 +227,7 @@ final class ForEachOps {
}
/** Implementation class for {@code DoubleStream} */
private static class OfDouble extends ForEachOp<Double>
static final class OfDouble extends ForEachOp<Double>
implements Sink.OfDouble {
final DoubleConsumer consumer;
......@@ -248,20 +249,20 @@ final class ForEachOps {
}
/** A {@code ForkJoinTask} for performing a parallel for-each operation */
private static class ForEachTask<S, T> extends CountedCompleter<Void> {
static final class ForEachTask<S, T> extends CountedCompleter<Void> {
private Spliterator<S> spliterator;
private final Sink<S> sink;
private final PipelineHelper<T> helper;
private final long targetSize;
private long targetSize;
ForEachTask(PipelineHelper<T> helper,
Spliterator<S> spliterator,
Sink<S> sink) {
super(null);
this.spliterator = spliterator;
this.sink = sink;
this.targetSize = AbstractTask.suggestTargetSize(spliterator.estimateSize());
this.helper = helper;
this.spliterator = spliterator;
this.targetSize = 0L;
}
ForEachTask(ForEachTask<S, T> parent, Spliterator<S> spliterator) {
......@@ -272,28 +273,40 @@ final class ForEachOps {
this.helper = parent.helper;
}
// Similar to AbstractTask but doesn't need to track child tasks
public void compute() {
Spliterator<S> rightSplit = spliterator, leftSplit;
long sizeEstimate = rightSplit.estimateSize(), sizeThreshold;
if ((sizeThreshold = targetSize) == 0L)
targetSize = sizeThreshold = AbstractTask.suggestTargetSize(sizeEstimate);
boolean isShortCircuit = StreamOpFlag.SHORT_CIRCUIT.isKnown(helper.getStreamAndOpFlags());
while (true) {
if (isShortCircuit && sink.cancellationRequested()) {
propagateCompletion();
spliterator = null;
return;
boolean forkRight = false;
Sink<S> taskSink = sink;
ForEachTask<S, T> task = this;
while (!isShortCircuit || !taskSink.cancellationRequested()) {
if (sizeEstimate <= sizeThreshold ||
(leftSplit = rightSplit.trySplit()) == null) {
task.helper.copyInto(taskSink, rightSplit);
break;
}
Spliterator<S> split;
if (!AbstractTask.suggestSplit(spliterator, targetSize)
|| (split = spliterator.trySplit()) == null) {
helper.copyInto(sink, spliterator);
propagateCompletion();
spliterator = null;
return;
ForEachTask<S, T> leftTask = new ForEachTask<>(task, leftSplit);
task.addToPendingCount(1);
ForEachTask<S, T> taskToFork;
if (forkRight) {
forkRight = false;
rightSplit = leftSplit;
taskToFork = task;
task = leftTask;
}
else {
addToPendingCount(1);
new ForEachTask<>(this, split).fork();
forkRight = true;
taskToFork = leftTask;
}
taskToFork.fork();
sizeEstimate = rightSplit.estimateSize();
}
task.spliterator = null;
task.propagateCompletion();
}
}
......@@ -301,7 +314,7 @@ final class ForEachOps {
* A {@code ForkJoinTask} for performing a parallel for-each operation
* which visits the elements in encounter order
*/
private static class ForEachOrderedTask<S, T> extends CountedCompleter<Void> {
static final class ForEachOrderedTask<S, T> extends CountedCompleter<Void> {
private final PipelineHelper<T> helper;
private Spliterator<S> spliterator;
private final long targetSize;
......@@ -343,39 +356,49 @@ final class ForEachOps {
}
private static <S, T> void doCompute(ForEachOrderedTask<S, T> task) {
while (true) {
Spliterator<S> split;
if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize)
|| (split = task.spliterator.trySplit()) == null) {
if (task.getPendingCount() == 0) {
task.helper.wrapAndCopyInto(task.action, task.spliterator);
}
else {
Node.Builder<T> nb = task.helper.makeNodeBuilder(
task.helper.exactOutputSizeIfKnown(task.spliterator),
size -> (T[]) new Object[size]);
task.node = task.helper.wrapAndCopyInto(nb, task.spliterator).build();
}
task.tryComplete();
return;
Spliterator<S> rightSplit = task.spliterator, leftSplit;
long sizeThreshold = task.targetSize;
boolean forkRight = false;
while (rightSplit.estimateSize() > sizeThreshold &&
(leftSplit = rightSplit.trySplit()) != null) {
ForEachOrderedTask<S, T> leftChild =
new ForEachOrderedTask<>(task, leftSplit, task.leftPredecessor);
ForEachOrderedTask<S, T> rightChild =
new ForEachOrderedTask<>(task, rightSplit, leftChild);
task.completionMap.put(leftChild, rightChild);
task.addToPendingCount(1); // forking
rightChild.addToPendingCount(1); // right pending on left child
if (task.leftPredecessor != null) {
leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine
if (task.completionMap.replace(task.leftPredecessor, task, leftChild))
task.addToPendingCount(-1); // transfer my "right child" count to my left child
else
leftChild.addToPendingCount(-1); // left child is ready to go when ready
}
ForEachOrderedTask<S, T> taskToFork;
if (forkRight) {
forkRight = false;
rightSplit = leftSplit;
task = leftChild;
taskToFork = rightChild;
}
else {
ForEachOrderedTask<S, T> leftChild = new ForEachOrderedTask<>(task, split, task.leftPredecessor);
ForEachOrderedTask<S, T> rightChild = new ForEachOrderedTask<>(task, task.spliterator, leftChild);
task.completionMap.put(leftChild, rightChild);
task.addToPendingCount(1); // forking
rightChild.addToPendingCount(1); // right pending on left child
if (task.leftPredecessor != null) {
leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine
if (task.completionMap.replace(task.leftPredecessor, task, leftChild))
task.addToPendingCount(-1); // transfer my "right child" count to my left child
else
leftChild.addToPendingCount(-1); // left child is ready to go when ready
}
leftChild.fork();
forkRight = true;
task = rightChild;
taskToFork = leftChild;
}
taskToFork.fork();
}
if (task.getPendingCount() == 0) {
task.helper.wrapAndCopyInto(task.action, rightSplit);
}
else {
Node.Builder<T> nb = task.helper.makeNodeBuilder(
task.helper.exactOutputSizeIfKnown(rightSplit),
size -> (T[]) new Object[size]);
task.node = task.helper.wrapAndCopyInto(nb, rightSplit).build();
}
task.tryComplete();
}
@Override
......
......@@ -1829,25 +1829,20 @@ final class Nodes {
@Override
public void compute() {
SizedCollectorTask<P_IN, P_OUT, T_SINK, K> task = this;
while (true) {
Spliterator<P_IN> leftSplit;
if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize)
|| ((leftSplit = task.spliterator.trySplit()) == null)) {
if (task.offset + task.length >= MAX_ARRAY_SIZE)
throw new IllegalArgumentException("Stream size exceeds max array size");
T_SINK sink = (T_SINK) task;
task.helper.wrapAndCopyInto(sink, task.spliterator);
task.propagateCompletion();
return;
}
else {
task.setPendingCount(1);
long leftSplitSize = leftSplit.estimateSize();
task.makeChild(leftSplit, task.offset, leftSplitSize).fork();
task = task.makeChild(task.spliterator, task.offset + leftSplitSize,
task.length - leftSplitSize);
}
}
Spliterator<P_IN> rightSplit = spliterator, leftSplit;
while (rightSplit.estimateSize() > task.targetSize &&
(leftSplit = rightSplit.trySplit()) != null) {
task.setPendingCount(1);
long leftSplitSize = leftSplit.estimateSize();
task.makeChild(leftSplit, task.offset, leftSplitSize).fork();
task = task.makeChild(rightSplit, task.offset + leftSplitSize,
task.length - leftSplitSize);
}
if (task.offset + task.length >= MAX_ARRAY_SIZE)
throw new IllegalArgumentException("Stream size exceeds max array size");
T_SINK sink = (T_SINK) task;
task.helper.wrapAndCopyInto(sink, rightSplit);
task.propagateCompletion();
}
abstract K makeChild(Spliterator<P_IN> spliterator, long offset, long size);
......
......@@ -160,6 +160,10 @@ public class JMX {
* example, then the return type is {@code MyMBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a <a href="package-summary.html#mgIface">compliant MBean
* interface</a>
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
......@@ -200,6 +204,10 @@ public class JMX {
* example, then the return type is {@code MyMBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a <a href="package-summary.html#mgIface">compliant MBean
* interface</a>
*/
public static <T> T newMBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
......@@ -298,6 +306,9 @@ public class JMX {
* example, then the return type is {@code MyMXBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a {@link javax.management.MXBean compliant MXBean interface}
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
......@@ -338,6 +349,9 @@ public class JMX {
* example, then the return type is {@code MyMXBean}.
*
* @return the new proxy instance.
*
* @throws IllegalArgumentException if {@code interfaceClass} is not
* a {@link javax.management.MXBean compliant MXBean interface}
*/
public static <T> T newMXBeanProxy(MBeanServerConnection connection,
ObjectName objectName,
......@@ -348,21 +362,25 @@ public class JMX {
/**
* <p>Test whether an interface is an MXBean interface.
* An interface is an MXBean interface if it is annotated
* {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
* An interface is an MXBean interface if it is public,
* annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
* or if it does not have an {@code @MXBean} annotation
* and its name ends with "{@code MXBean}".</p>
*
* @param interfaceClass The candidate interface.
*
* @return true if {@code interfaceClass} is an interface and
* meets the conditions described.
* @return true if {@code interfaceClass} is a
* {@link javax.management.MXBean compliant MXBean interface}
*
* @throws NullPointerException if {@code interfaceClass} is null.
*/
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
if (!interfaceClass.isInterface())
return false;
if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
!Introspector.ALLOW_NONPUBLIC_MBEAN) {
return false;
}
MXBean a = interfaceClass.getAnnotation(MXBean.class);
if (a != null)
return a.value();
......@@ -389,9 +407,6 @@ public class JMX {
boolean notificationEmitter,
boolean isMXBean) {
if (System.getSecurityManager() != null) {
checkProxyInterface(interfaceClass);
}
try {
if (isMXBean) {
// Check interface for MXBean compliance
......@@ -419,17 +434,4 @@ public class JMX {
handler);
return interfaceClass.cast(proxy);
}
/**
* Checks for the M(X)Bean proxy interface being public and not restricted
* @param interfaceClass MBean proxy interface
* @throws SecurityException when the proxy interface comes from a restricted
* package or is not public
*/
private static void checkProxyInterface(Class<?> interfaceClass) {
if (!Modifier.isPublic(interfaceClass.getModifiers())) {
throw new SecurityException("mbean proxy interface non-public");
}
ReflectUtil.checkPackageAccess(interfaceClass);
}
}
......@@ -225,7 +225,7 @@ public class MBeanServerInvocationHandler implements InvocationHandler {
*
* @return the new proxy instance.
*
* @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class)
* @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class, boolean)
*/
public static <T> T newProxyInstance(MBeanServerConnection connection,
ObjectName objectName,
......
......@@ -54,9 +54,9 @@ import javax.management.openmbean.TabularType;
/**
<p>Annotation to mark an interface explicitly as being an MXBean
interface, or as not being an MXBean interface. By default, an
interface is an MXBean interface if its name ends with {@code
MXBean}, as in {@code SomethingMXBean}. The following interfaces
are MXBean interfaces:</p>
interface is an MXBean interface if it is public and its name ends
with {@code MXBean}, as in {@code SomethingMXBean}. The following
interfaces are MXBean interfaces:</p>
<pre>
public interface WhatsitMXBean {}
......@@ -71,6 +71,8 @@ import javax.management.openmbean.TabularType;
<p>The following interfaces are not MXBean interfaces:</p>
<pre>
interface NonPublicInterfaceNotMXBean{}
public interface Whatsit3Interface{}
&#64;MXBean(false)
......
......@@ -53,8 +53,8 @@ questions.
<p>The fundamental notion of the JMX API is the <em>MBean</em>.
An MBean is a named <em>managed object</em> representing a
resource. It has a <em>management interface</em> consisting
of:</p>
resource. It has a <em id="mgIface">management interface</em>
which must be <em>public</em> and consist of:</p>
<ul>
<li>named and typed attributes that can be read and/or
......
......@@ -196,18 +196,17 @@ public interface ScriptEngineFactory {
/**
* Returns A valid scripting language executable progam with given statements.
* Returns a valid scripting language executable progam with given statements.
* For instance an implementation for a PHP engine might be:
* <p>
* <pre>{@code
* public String getProgram(String... statements) {
* $retval = "<?\n";
* String retval = "<?\n";
* int len = statements.length;
* for (int i = 0; i < len; i++) {
* $retval += statements[i] + ";\n";
* retval += statements[i] + ";\n";
* }
* $retval += "?>";
*
* return retval += "?>";
* }
* }</pre>
*
......
......@@ -147,18 +147,20 @@ public class ManagementFactoryHelper {
}
}
// The logging MXBean object is an instance of
// PlatformLoggingMXBean and java.util.logging.LoggingMXBean
// but it can't directly implement two MXBean interfaces
// as a compliant MXBean implements exactly one MXBean interface,
// or if it implements one interface that is a subinterface of
// all the others; otherwise, it is a non-compliant MXBean
// and MBeanServer will throw NotCompliantMBeanException.
// See the Definition of an MXBean section in javax.management.MXBean spec.
//
// To create a compliant logging MXBean, define a LoggingMXBean interface
// that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
interface LoggingMXBean
/**
* The logging MXBean object is an instance of
* PlatformLoggingMXBean and java.util.logging.LoggingMXBean
* but it can't directly implement two MXBean interfaces
* as a compliant MXBean implements exactly one MXBean interface,
* or if it implements one interface that is a subinterface of
* all the others; otherwise, it is a non-compliant MXBean
* and MBeanServer will throw NotCompliantMBeanException.
* See the Definition of an MXBean section in javax.management.MXBean spec.
*
* To create a compliant logging MXBean, define a LoggingMXBean interface
* that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean
*/
public interface LoggingMXBean
extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean {
}
......
......@@ -27,6 +27,7 @@
* @summary Basic Test for HotSpotDiagnosticMXBean.setVMOption()
* and getDiagnosticOptions().
* @author Mandy Chung
* @author Jaroslav Bachorik
*
* @run main/othervm -XX:+PrintGCDetails SetVMOption
*/
......@@ -36,7 +37,6 @@ import java.util.*;
import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption;
import com.sun.management.VMOption.Origin;
import sun.misc.Version;
public class SetVMOption {
private static String PRINT_GC_DETAILS = "PrintGCDetails";
......@@ -47,17 +47,8 @@ public class SetVMOption {
private static HotSpotDiagnosticMXBean mbean;
public static void main(String[] args) throws Exception {
List<HotSpotDiagnosticMXBean> list =
ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
// The following test is transitional only and should be removed
// once build 52 is promoted.
int build = Version.jvmBuildNumber();
if (build > 0 && build < 52) {
// JVM support is integrated in build 52
// this test is skipped if running with VM earlier than 52
return;
}
mbean =
ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
VMOption option = findPrintGCDetailsOption();
if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) {
......
/*
* 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.
*/
/* @test
* @bug 8017212
* @summary Examine methods in File.java that access the file system do the
* right permission check when a security manager exists.
* @author Dan Xu
*/
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileFilter;
import java.io.IOException;
import java.security.Permission;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CheckPermission {
private static final String CHECK_PERMISSION_TEST = "CheckPermissionTest";
public enum FileOperation {
READ, WRITE, DELETE, EXEC
}
static class Checks {
private List<Permission> permissionsChecked = new ArrayList<>();
private Set<String> propertiesChecked = new HashSet<>();
private Map<FileOperation, List<String>> fileOperationChecked =
new EnumMap<>(FileOperation.class);
List<Permission> permissionsChecked() {
return permissionsChecked;
}
Set<String> propertiesChecked() {
return propertiesChecked;
}
List<String> fileOperationChecked(FileOperation op) {
return fileOperationChecked.get(op);
}
void addFileOperation(FileOperation op, String file) {
List<String> opList = fileOperationChecked.get(op);
if (opList == null) {
opList = new ArrayList<>();
fileOperationChecked.put(op, opList);
}
opList.add(file);
}
}
static ThreadLocal<Checks> myChecks = new ThreadLocal<>();
static void prepare() {
myChecks.set(new Checks());
}
static class LoggingSecurityManager extends SecurityManager {
static void install() {
System.setSecurityManager(new LoggingSecurityManager());
}
private void checkFileOperation(FileOperation op, String file) {
Checks checks = myChecks.get();
if (checks != null)
checks.addFileOperation(op, file);
}
@Override
public void checkRead(String file) {
checkFileOperation(FileOperation.READ, file);
}
@Override
public void checkWrite(String file) {
checkFileOperation(FileOperation.WRITE, file);
}
@Override
public void checkDelete(String file) {
checkFileOperation(FileOperation.DELETE, file);
}
@Override
public void checkExec(String file) {
checkFileOperation(FileOperation.EXEC, file);
}
@Override
public void checkPermission(Permission perm) {
Checks checks = myChecks.get();
if (checks != null)
checks.permissionsChecked().add(perm);
}
@Override
public void checkPropertyAccess(String key) {
Checks checks = myChecks.get();
if (checks != null)
checks.propertiesChecked().add(key);
}
}
static void assertCheckPermission(Class<? extends Permission> type,
String name)
{
for (Permission perm : myChecks.get().permissionsChecked()) {
if (type.isInstance(perm) && perm.getName().equals(name))
return;
}
throw new RuntimeException(type.getName() + "(\"" + name
+ "\") not checked");
}
static void assertCheckPropertyAccess(String key) {
if (!myChecks.get().propertiesChecked().contains(key))
throw new RuntimeException("Property " + key + " not checked");
}
static void assertChecked(File file, List<String> list) {
if (list != null && !list.isEmpty()) {
for (String path : list) {
if (path.equals(file.getPath()))
return;
}
}
throw new RuntimeException("Access not checked");
}
static void assertNotChecked(File file, List<String> list) {
if (list != null && !list.isEmpty()) {
for (String path : list) {
if (path.equals(file.getPath()))
throw new RuntimeException("Access checked");
}
}
}
static void assertCheckOperation(File file, Set<FileOperation> ops) {
for (FileOperation op : ops)
assertChecked(file, myChecks.get().fileOperationChecked(op));
}
static void assertNotCheckOperation(File file, Set<FileOperation> ops) {
for (FileOperation op : ops)
assertNotChecked(file, myChecks.get().fileOperationChecked(op));
}
static void assertOnlyCheckOperation(File file,
EnumSet<FileOperation> ops)
{
assertCheckOperation(file, ops);
assertNotCheckOperation(file, EnumSet.complementOf(ops));
}
static File testFile, another;
static void setup() {
testFile = new File(CHECK_PERMISSION_TEST + System.currentTimeMillis());
if (testFile.exists()) {
testFile.delete();
}
another = new File(CHECK_PERMISSION_TEST + "Another"
+ System.currentTimeMillis());
if (another.exists()) {
another.delete();
}
LoggingSecurityManager.install();
}
public static void main(String[] args) throws IOException {
setup();
prepare();
testFile.canRead();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.canWrite();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.exists();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.isDirectory();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.isFile();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.isHidden();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.lastModified();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.length();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.createNewFile();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.list();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return false;
}
});
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.listFiles();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return false;
}
});
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return false;
}
});
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
prepare();
testFile.mkdir();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
if (testFile.exists()) {
prepare();
testFile.mkdirs();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
}
if (!another.exists()) {
prepare();
another.mkdirs();
assertOnlyCheckOperation(another,
EnumSet.of(FileOperation.READ, FileOperation.WRITE));
}
prepare();
another.delete();
assertOnlyCheckOperation(another, EnumSet.of(FileOperation.DELETE));
prepare();
boolean renRst = testFile.renameTo(another);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
assertOnlyCheckOperation(another, EnumSet.of(FileOperation.WRITE));
if (renRst) {
if (testFile.exists())
throw new RuntimeException(testFile + " is already renamed to "
+ another);
testFile = another;
}
prepare();
testFile.setLastModified(0);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setReadOnly();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setWritable(true, true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setWritable(true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setReadable(true, true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setReadable(true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setExecutable(true, true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.setExecutable(true);
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE));
prepare();
testFile.canExecute();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.EXEC));
prepare();
testFile.getTotalSpace();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
assertCheckPermission(RuntimePermission.class,
"getFileSystemAttributes");
prepare();
testFile.getFreeSpace();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
assertCheckPermission(RuntimePermission.class,
"getFileSystemAttributes");
prepare();
testFile.getUsableSpace();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ));
assertCheckPermission(RuntimePermission.class,
"getFileSystemAttributes");
prepare();
File tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null);
assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE));
tmpFile.delete();
assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE));
prepare();
tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null, null);
assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE));
tmpFile.delete();
assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE));
prepare();
testFile.deleteOnExit();
assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.DELETE));
}
}
......@@ -612,8 +612,13 @@ public class NulFile {
try {
File.createTempFile(prefix, suffix, directory);
} catch (IOException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
String err = "Unable to create temporary file";
if (err.equals(ex.getMessage()))
exceptionThrown = true;
else {
throw new RuntimeException("Get IOException with message, "
+ ex.getMessage() + ", expect message, "+ err);
}
}
}
if (!exceptionThrown) {
......
......@@ -23,9 +23,8 @@
/*
* @test
* @bug 8013827 8011950
* @bug 8013827 8011950 8017212
* @summary Check whether File.createTempFile can handle special parameters
* on Windows platforms
* @author Dan Xu
*/
......@@ -64,6 +63,17 @@ public class SpecialTempFile {
}
public static void main(String[] args) throws Exception {
// Common test
final String name = "SpecialTempFile";
File f = new File(System.getProperty("java.io.tmpdir"), name);
if (!f.exists()) {
f.createNewFile();
}
String[] nulPre = { name + "\u0000" };
String[] nulSuf = { ".test" };
test("NulName", nulPre, nulSuf);
// Windows tests
if (!System.getProperty("os.name").startsWith("Windows"))
return;
......
......@@ -23,9 +23,9 @@
/**
* @test
* @bug 7038914
* @bug 7038914 8016341
* @summary Verify that the reference handler does not die after an OOME allocating the InterruptedException object
* @run main/othervm -Xmx16M -XX:-UseTLAB OOMEInReferenceHandler
* @run main/othervm -Xmx24M -XX:-UseTLAB OOMEInReferenceHandler
* @author peter.levart@gmail.com
*/
......@@ -107,6 +107,6 @@ public class OOMEInReferenceHandler {
}
// no sure answer after 10 seconds
throw new IllegalStateException("Reference Handler thread stuck.");
throw new IllegalStateException("Reference Handler thread stuck. weakRef.get(): " + weakRef.get());
}
}
......@@ -45,8 +45,17 @@ public class StrippingZerosTest {
{new BigDecimal("1234.56780"), new BigDecimal("1234.5678")},
{new BigDecimal("1234.567800000"), new BigDecimal("1234.5678")},
{new BigDecimal("0"), new BigDecimal("0")},
{new BigDecimal("0e100"), new BigDecimal("0e100")},
{new BigDecimal("0e-100"), new BigDecimal("0e-100")},
{new BigDecimal("0e2"), BigDecimal.ZERO},
{new BigDecimal("0e-2"), BigDecimal.ZERO},
{new BigDecimal("0e42"), BigDecimal.ZERO},
{new BigDecimal("+0e42"), BigDecimal.ZERO},
{new BigDecimal("-0e42"), BigDecimal.ZERO},
{new BigDecimal("0e-42"), BigDecimal.ZERO},
{new BigDecimal("+0e-42"), BigDecimal.ZERO},
{new BigDecimal("-0e-42"), BigDecimal.ZERO},
{new BigDecimal("0e-2"), BigDecimal.ZERO},
{new BigDecimal("0e100"), BigDecimal.ZERO},
{new BigDecimal("0e-100"), BigDecimal.ZERO},
{new BigDecimal("10"), new BigDecimal("1e1")},
{new BigDecimal("20"), new BigDecimal("2e1")},
{new BigDecimal("100"), new BigDecimal("1e2")},
......
/*
* 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.
*/
/**
* @test
* @run testng UnmodifiableMapEntrySet
* @summary Unit tests for wrapping classes should delegate to default methods
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Spliterator;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.assertEquals;
@Test(groups = "unit")
public class UnmodifiableMapEntrySet {
static Object[][] collections;
static <M extends Map<Integer, Integer>> M fillMap(int size, M m) {
for (int i = 0; i < size; i++) {
m.put(i, i);
}
return m;
}
@DataProvider(name="maps")
static Object[][] mapCases() {
if (collections != null) {
return collections;
}
List<Object[]> cases = new ArrayList<>();
for (int size : new int[] {1, 2, 16}) {
cases.add(new Object[] {
String.format("new HashMap(%d)", size),
(Supplier<Map<Integer, Integer>>)
() -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) });
cases.add(new Object[] {
String.format("new TreeMap(%d)", size),
(Supplier<Map<Integer, Integer>>)
() -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) });
}
return cases.toArray(new Object[0][]);
}
static class EntryConsumer implements Consumer<Map.Entry<Integer, Integer>> {
int updates;
@Override
public void accept(Map.Entry<Integer, Integer> me) {
try {
me.setValue(Integer.MAX_VALUE);
updates++;
} catch (UnsupportedOperationException e) {
}
}
void assertNoUpdates() {
assertEquals(updates, 0, "Updates to entries");
}
}
void testWithEntryConsumer(Consumer<EntryConsumer> c) {
EntryConsumer ec = new EntryConsumer();
c.accept(ec);
ec.assertNoUpdates();
}
@Test(dataProvider = "maps")
public void testForEach(String d, Supplier<Map<Integer, Integer>> ms) {
testWithEntryConsumer(
ec -> ms.get().entrySet().forEach(ec));
}
@Test(dataProvider = "maps")
public void testIteratorForEachRemaining(String d, Supplier<Map<Integer, Integer>> ms) {
testWithEntryConsumer(
ec -> ms.get().entrySet().iterator().forEachRemaining(ec));
}
@Test(dataProvider = "maps")
public void testIteratorNext(String d, Supplier<Map<Integer, Integer>> ms) {
testWithEntryConsumer(ec -> {
for (Map.Entry<Integer, Integer> me : ms.get().entrySet()) {
ec.accept(me);
}
});
}
@Test(dataProvider = "maps")
public void testSpliteratorForEachRemaining(String d, Supplier<Map<Integer, Integer>> ms) {
testSpliterator(
ms.get().entrySet()::spliterator,
// Higher order function returning a consumer that
// traverses all spliterator elements using an EntryConsumer
s -> ec -> s.forEachRemaining(ec));
}
@Test(dataProvider = "maps")
public void testSpliteratorTryAdvance(String d, Supplier<Map<Integer, Integer>> ms) {
testSpliterator(
ms.get().entrySet()::spliterator,
// Higher order function returning a consumer that
// traverses all spliterator elements using an EntryConsumer
s -> ec -> { while (s.tryAdvance(ec)); });
}
void testSpliterator(Supplier<Spliterator<Map.Entry<Integer, Integer>>> ss,
// Higher order function that given a spliterator returns a
// consumer for that spliterator which traverses elements
// using an EntryConsumer
Function<Spliterator<Map.Entry<Integer, Integer>>, Consumer<EntryConsumer>> sc) {
testWithEntryConsumer(sc.apply(ss.get()));
Spliterator<Map.Entry<Integer, Integer>> s = ss.get();
Spliterator<Map.Entry<Integer, Integer>> split = s.trySplit();
if (split != null) {
testWithEntryConsumer(sc.apply(split));
testWithEntryConsumer(sc.apply(s));
}
}
@Test(dataProvider = "maps")
public void testStreamForEach(String d, Supplier<Map<Integer, Integer>> ms) {
testWithEntryConsumer(ec -> ms.get().entrySet().stream().forEach(ec));
}
@Test(dataProvider = "maps")
public void testParallelStreamForEach(String d, Supplier<Map<Integer, Integer>> ms) {
testWithEntryConsumer(ec -> ms.get().entrySet().parallelStream().forEach(ec));
}
}
/*
* 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 javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/*
* @test
* @bug 8010285
* @summary Test fallback for private MBean interfaces.
* It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
* system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
* @author Jaroslav Bachorik
* @run clean MBeanFallbackTest
* @run build MBeanFallbackTest
* @run main MBeanFallbackTest
*/
public class MBeanFallbackTest {
private static interface PrivateMBean {
public int[] getInts();
}
public static class Private implements PrivateMBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
private static int failures = 0;
public static void main(String[] args) throws Exception {
System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
testPrivate(PrivateMBean.class, new Private());
if (failures == 0)
System.out.println("Test passed");
else
throw new Exception("TEST FAILURES: " + failures);
}
private static void fail(String msg) {
failures++;
System.out.println("FAIL: " + msg);
}
private static void success(String msg) {
System.out.println("OK: " + msg);
}
private static void testPrivate(Class<?> iface, Object bean) throws Exception {
try {
System.out.println("Registering a private MBean " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Compliant");
mbs.registerMBean(bean, on);
success("Registered a private MBean - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
fail("MBean not registered");
} else {
throw e;
}
}
}
}
/*
* 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 javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/*
* @test
* @bug 8010285
* @summary General MBean test.
* @author Jaroslav Bachorik
* @run clean MBeanTest
* @run build MBeanTest
* @run main MBeanTest
*/
public class MBeanTest {
private static interface PrivateMBean {
public int[] getInts();
}
public static class Private implements PrivateMBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
public static interface NonCompliantMBean {
public boolean getInt();
public boolean isInt();
public void setInt(int a);
public void setInt(long b);
}
public static class NonCompliant implements NonCompliantMBean {
public boolean getInt() {
return false;
}
public boolean isInt() {
return true;
}
public void setInt(int a) {
}
public void setInt(long b) {
}
}
public static interface CompliantMBean {
public boolean isFlag();
public int getInt();
public void setInt(int value);
}
public static class Compliant implements CompliantMBean {
public boolean isFlag() {
return false;
}
public int getInt() {
return 1;
}
public void setInt(int value) {
}
}
private static int failures = 0;
public static void main(String[] args) throws Exception {
testCompliant(CompliantMBean.class, new Compliant());
testNonCompliant(PrivateMBean.class, new Private());
testNonCompliant(NonCompliantMBean.class, new NonCompliant());
if (failures == 0)
System.out.println("Test passed");
else
throw new Exception("TEST FAILURES: " + failures);
}
private static void fail(String msg) {
failures++;
System.out.println("FAIL: " + msg);
}
private static void success(String msg) {
System.out.println("OK: " + msg);
}
private static void testNonCompliant(Class<?> iface, Object bean) throws Exception {
try {
System.out.println("Registering a non-compliant MBean " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=NonCompliant");
mbs.registerMBean(bean, on);
fail("Registered a non-compliant MBean - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
success("MBean not registered");
} else {
throw e;
}
}
}
private static void testCompliant(Class<?> iface, Object bean) throws Exception {
try {
System.out.println("Registering a compliant MBean " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Compliant");
mbs.registerMBean(bean, on);
success("Registered a compliant MBean - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
fail("MBean not registered");
} else {
throw e;
}
}
}
}
/*
* Copyright (c) 2005, 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.
*/
/*
* @test
* @bug 8010285
* @summary Test for the private MXBean interface fallback.
* It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
* system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
* @author Jaroslav Bachorik
* @run clean MXBeanFallbackTest
* @run build MXBeanFallbackTest
* @run main MXBeanFallbackTest
*/
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
public class MXBeanFallbackTest {
public static void main(String[] args) throws Exception {
System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
testPrivateMXBean("Private", new Private());
if (failures == 0)
System.out.println("Test passed");
else
throw new Exception("TEST FAILURES: " + failures);
}
private static int failures = 0;
private static interface PrivateMXBean {
public int[] getInts();
}
public static class Private implements PrivateMXBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
private static void testPrivateMXBean(String type, Object bean) throws Exception {
System.out.println(type + " MXBean test...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=" + type);
try {
mbs.registerMBean(bean, on);
success("Private MXBean registered");
} catch (NotCompliantMBeanException e) {
failure("Failed to register the private MXBean - " +
bean.getClass().getInterfaces()[0].getName());
}
}
private static void success(String what) {
System.out.println("OK: " + what);
}
private static void failure(String what) {
System.out.println("FAILED: " + what);
failures++;
}
}
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 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
......@@ -23,9 +23,10 @@
/*
* @test
* @bug 6175517 6278707 6318827 6305746 6392303 6600709
* @bug 6175517 6278707 6318827 6305746 6392303 6600709 8010285
* @summary General MXBean test.
* @author Eamonn McManus
* @author Jaroslav Bachorik
* @run clean MXBeanTest MerlinMXBean TigerMXBean
* @run build MXBeanTest MerlinMXBean TigerMXBean
* @run main MXBeanTest
......@@ -51,6 +52,7 @@ import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.MBeanServerInvocationHandler;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import javax.management.openmbean.ArrayType;
......@@ -75,6 +77,8 @@ public class MXBeanTest {
testExplicitMXBean();
testSubclassMXBean();
testIndirectMXBean();
testNonCompliantMXBean("Private", new Private());
testNonCompliantMXBean("NonCompliant", new NonCompliant());
if (failures == 0)
System.out.println("Test passed");
......@@ -84,6 +88,39 @@ public class MXBeanTest {
private static int failures = 0;
private static interface PrivateMXBean {
public int[] getInts();
}
public static class Private implements PrivateMXBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
public static interface NonCompliantMXBean {
public boolean getInt();
public boolean isInt();
public void setInt(int a);
public void setInt(long b);
}
public static class NonCompliant implements NonCompliantMXBean {
public boolean getInt() {
return false;
}
public boolean isInt() {
return true;
}
public void setInt(int a) {
}
public void setInt(long b) {
}
}
public static interface ExplicitMXBean {
public int[] getInts();
}
......@@ -110,6 +147,19 @@ public class MXBeanTest {
}
}
private static void testNonCompliantMXBean(String type, Object bean) throws Exception {
System.out.println(type + " MXBean test...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=" + type);
try {
mbs.registerMBean(bean, on);
failure(bean.getClass().getInterfaces()[0].getName() + " is not a compliant "
+ "MXBean interface");
} catch (NotCompliantMBeanException e) {
success("Non-compliant MXBean not registered");
}
}
private static void testExplicitMXBean() throws Exception {
System.out.println("Explicit MXBean test...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
......
/*
* 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 javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/*
* @test
* @bug 8010285
* @summary Tests the fallback for creating JMX proxies for private interfaces
* It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic"
* system property must be set before c.s.j.m.MBeanAnalyzer has been loaded.
* @author Jaroslav Bachorik
* @run clean JMXProxyFallbackTest
* @run build JMXProxyFallbackTest
* @run main JMXProxyFallbackTest
*/
public class JMXProxyFallbackTest {
private static interface PrivateMBean {
public int[] getInts();
}
private static interface PrivateMXBean {
public int[] getInts();
}
public static class Private implements PrivateMXBean, PrivateMBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
private static int failures = 0;
public static void main(String[] args) throws Exception {
System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true");
testPrivate(PrivateMBean.class);
testPrivate(PrivateMXBean.class);
if (failures == 0)
System.out.println("Test passed");
else
throw new Exception("TEST FAILURES: " + failures);
}
private static void fail(String msg) {
failures++;
System.out.println("FAIL: " + msg);
}
private static void success(String msg) {
System.out.println("OK: " + msg);
}
private static void testPrivate(Class<?> iface) throws Exception {
try {
System.out.println("Creating a proxy for private M(X)Bean " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Proxy");
JMX.newMBeanProxy(mbs, on, iface);
success("Created a proxy for private M(X)Bean - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
fail("Proxy not created");
} else {
throw e;
}
}
}
}
/*
* 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 javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
/*
* @test
* @bug 8010285
* @summary Tests that javax.management.JMX creates proxies only for the
* compliant MBeans/MXBeans
* @author Jaroslav Bachorik
* @run clean JMXProxyTest
* @run build JMXProxyTest
* @run main JMXProxyTest
*/
public class JMXProxyTest {
private static interface PrivateMBean {
public int[] getInts();
}
private static interface PrivateMXBean {
public int[] getInts();
}
public static class Private implements PrivateMXBean, PrivateMBean {
public int[] getInts() {
return new int[]{1,2,3};
}
}
public static interface NonCompliantMBean {
public boolean getInt();
public boolean isInt();
public void setInt(int a);
public void setInt(long b);
}
public static interface NonCompliantMXBean {
public boolean getInt();
public boolean isInt();
public void setInt(int a);
public void setInt(long b);
}
public static class NonCompliant implements NonCompliantMXBean, NonCompliantMBean {
public boolean getInt() {
return false;
}
public boolean isInt() {
return true;
}
public void setInt(int a) {
}
public void setInt(long b) {
}
}
public static interface CompliantMBean {
public boolean isFlag();
public int getInt();
public void setInt(int value);
}
public static interface CompliantMXBean {
public boolean isFlag();
public int getInt();
public void setInt(int value);
}
public static class Compliant implements CompliantMXBean, CompliantMBean {
public boolean isFlag() {
return false;
}
public int getInt() {
return 1;
}
public void setInt(int value) {
}
}
private static int failures = 0;
public static void main(String[] args) throws Exception {
testCompliant(CompliantMBean.class, false);
testCompliant(CompliantMXBean.class, true);
testNonCompliant(PrivateMBean.class, false);
testNonCompliant(PrivateMXBean.class, true);
testNonCompliant(NonCompliantMBean.class, false);
testNonCompliant(NonCompliantMXBean.class, true);
if (failures == 0)
System.out.println("Test passed");
else
throw new Exception("TEST FAILURES: " + failures);
}
private static void fail(String msg) {
failures++;
System.out.println("FAIL: " + msg);
}
private static void success(String msg) {
System.out.println("OK: " + msg);
}
private static void testNonCompliant(Class<?> iface, boolean isMx) throws Exception {
try {
System.out.println("Creating a proxy for non-compliant " +
(isMx ? "MXBean" : "MBean") + " " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Proxy");
if (isMx) {
JMX.newMXBeanProxy(mbs, on, iface);
} else {
JMX.newMBeanProxy(mbs, on, iface);
}
fail("Created a proxy for non-compliant " +
(isMx ? "MXBean" : "MBean") + " - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
success("Proxy not created");
} else {
throw e;
}
}
}
private static void testCompliant(Class<?> iface, boolean isMx) throws Exception {
try {
System.out.println("Creating a proxy for compliant " +
(isMx ? "MXBean" : "MBean") + " " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Proxy");
if (isMx) {
JMX.newMXBeanProxy(mbs, on, iface);
} else {
JMX.newMBeanProxy(mbs, on, iface);
}
success("Created a proxy for compliant " +
(isMx ? "MXBean" : "MBean") + " - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
fail("Proxy not created");
} else {
throw e;
}
}
}
}
......@@ -23,7 +23,7 @@
/*
* @test
* @bug 8012082
* @bug 8012082 8019267
* @summary SASL: auth-conf negotiated, but unencrypted data is accepted,
* reset to unencrypt
* @compile -XDignore.symbol.file SaslGSS.java
......@@ -37,9 +37,16 @@ import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ietf.jgss.*;
import sun.security.jgss.GSSUtil;
......@@ -79,14 +86,28 @@ public class SaslGSS {
}
});
// Handshake
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream oldErr = System.err;
System.setErr(new PrintStream(bout));
Logger.getLogger("javax.security.sasl").setLevel(Level.ALL);
Handler h = new ConsoleHandler();
h.setLevel(Level.ALL);
Logger.getLogger("javax.security.sasl").addHandler(h);
byte[] token = new byte[0];
token = sc.initSecContext(token, 0, token.length);
token = ss.evaluateResponse(token);
token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
ss.evaluateResponse(token);
try {
// Handshake
token = sc.initSecContext(token, 0, token.length);
token = ss.evaluateResponse(token);
token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
ss.evaluateResponse(token);
} finally {
System.setErr(oldErr);
}
// Talk
// 1. Client sends a auth-int message
......@@ -102,5 +123,15 @@ public class SaslGSS {
if (!qop.getPrivacy()) {
throw new Exception();
}
for (String s: bout.toString().split("\\n")) {
if (s.contains("KRB5SRV04") && s.contains("NULL")) {
return;
}
}
System.out.println("=======================");
System.out.println(bout.toString());
System.out.println("=======================");
throw new Exception("Haven't seen KRB5SRV04 with NULL");
}
}
/*
* Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 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
......@@ -36,7 +36,7 @@ public class TestRSAKeyLength extends PKCS11Test {
main(new TestRSAKeyLength());
}
public void main(Provider p) throws Exception {
boolean isValidKeyLength[] = { true, true, false, false };
boolean isValidKeyLength[] = { true, true, true, false, false };
String algos[] = { "SHA1withRSA", "SHA224withRSA", "SHA256withRSA",
"SHA384withRSA", "SHA512withRSA" };
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p);
......@@ -45,6 +45,10 @@ public class TestRSAKeyLength extends PKCS11Test {
PrivateKey privKey = kp.getPrivate();
PublicKey pubKey = kp.getPublic();
if (algos.length != isValidKeyLength.length) {
throw new Exception("Internal Error: number of test algos" +
" and results length mismatch!");
}
for (int i = 0; i < algos.length; i++) {
Signature sig = Signature.getInstance(algos[i], p);
System.out.println("Testing RSA signature " + algos[i]);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册