# HG changeset patch # User alanb # Date 1301443223 -3600 # Node ID 799504d1fdcca1ecc6e8a5c8a04fe743d998c0e5 # Parent 6679e1339581ac873886d9d6641669b68ff5f0d8# Parent 117374ccf1b7b840f5319dd5befa396723dbe04d Merge diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/com/sun/security/auth/PolicyParser.java --- a/jdk/src/share/classes/com/sun/security/auth/PolicyParser.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/com/sun/security/auth/PolicyParser.java Wed Mar 30 01:00:23 2011 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2011, 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 @@ -30,13 +30,14 @@ import java.net.MalformedURLException; import java.net.SocketPermission; import java.net.URL; +import java.security.GeneralSecurityException; +import java.text.MessageFormat; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedList; import java.util.ListIterator; import java.util.Vector; import java.util.StringTokenizer; -import java.security.GeneralSecurityException; import sun.security.util.PropertyExpander; /** @@ -368,8 +369,8 @@ "WILDCARD class but no WILDCARD name"); throw new ParsingException (st.lineno(), - rb.getString("can.not.specify.Principal.with.a.") + - rb.getString("wildcard.class.without.a.wildcard.name")); + rb.getString("can.not.specify.Principal.with.a." + + "wildcard.class.without.a.wildcard.name")); } try { @@ -525,9 +526,10 @@ rb.getString("number.") + String.valueOf(st.nval)); case StreamTokenizer.TT_EOF: - throw new ParsingException - (rb.getString("expected.") + expect + - rb.getString(".read.end.of.file")); + MessageFormat form = new MessageFormat( + rb.getString("expected.expect.read.end.of.file.")); + Object[] source = {expect}; + throw new ParsingException(form.format(source)); case StreamTokenizer.TT_WORD: if (expect.equalsIgnoreCase(st.sval)) { lookahead = st.nextToken(); diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/BufferPoolMXBean.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/lang/management/BufferPoolMXBean.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2007, 2008, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ + +package java.lang.management; + +/** + * The management interface for a buffer pool, for example a pool of + * {@link java.nio.ByteBuffer#allocateDirect direct} or {@link + * java.nio.MappedByteBuffer mapped} buffers. + * + *

A class implementing this interface is an + * {@link javax.management.MXBean}. A Java + * virtual machine has one or more implementations of this interface. The {@link + * java.lang.management.ManagementFactory#getPlatformMXBeans getPlatformMXBeans} + * method can be used to obtain the list of {@code BufferPoolMXBean} objects + * representing the management interfaces for pools of buffers as follows: + *

+ *     List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
+ * 
+ * + *

The management interfaces are also registered with the platform {@link + * javax.management.MBeanServer MBeanServer}. The {@link + * javax.management.ObjectName ObjectName} that uniquely identifies the + * management interface within the {@code MBeanServer} takes the form: + *

+ *     java.nio:type=BufferPool,name=pool name
+ * 
+ * where pool name is the {@link #getName name} of the buffer pool. + * + * @since 1.7 + */ +public interface BufferPoolMXBean extends PlatformManagedObject { + + /** + * Returns the name representing this buffer pool. + * + * @return The name of this buffer pool. + */ + String getName(); + + /** + * Returns an estimate of the number of buffers in the pool. + * + * @return An estimate of the number of buffers in this pool + */ + long getCount(); + + /** + * Returns an estimate of the total capacity of the buffers in this pool. + * A buffer's capacity is the number of elements it contains and the value + * returned by this method is an estimate of the total capacity of buffers + * in the pool in bytes. + * + * @return An estimate of the total capacity of the buffers in this pool + * in bytes + */ + long getTotalCapacity(); + + /** + * Returns an estimate of the memory that the Java virtual machine is using + * for this buffer pool. The value returned by this method may differ + * from the estimate of the total {@link #getTotalCapacity capacity} of + * the buffers in this pool. This difference is explained by alignment, + * memory allocator, and other implementation specific reasons. + * + * @return An estimate of the memory that the Java virtual machine is using + * for this buffer pool in bytes, or {@code -1L} if an estimate of + * the memory usage is not available + */ + long getMemoryUsed(); +} diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/ManagementFactory.java --- a/jdk/src/share/classes/java/lang/management/ManagementFactory.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java Wed Mar 30 01:00:23 2011 +0100 @@ -40,8 +40,9 @@ import javax.management.StandardEmitterMBean; import javax.management.StandardMBean; import java.util.Collections; -import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.TreeSet; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; @@ -51,37 +52,63 @@ import sun.management.ManagementFactoryHelper; /** - * The ManagementFactory class is a factory class for getting + * The {@code ManagementFactory} class is a factory class for getting * managed beans for the Java platform. * This class consists of static methods each of which returns - * one or more platform MXBean(s) representing + * one or more platform MXBeans representing * the management interface of a component of the Java virtual * machine. + *

+ *

Platform MXBeans

+ *

+ * A platform MXBean is a managed bean that + * conforms to the JMX + * Instrumentation Specification and only uses a set of basic data types. + * A JMX management application and the {@linkplain + * #getPlatformMBeanServer platform MBeanServer} + * can interoperate without requiring classes for MXBean specific + * data types. + * The data types being transmitted between the JMX connector + * server and the connector client are + * {@linkplain javax.management.openmbean.OpenType open types} + * and this allows interoperation across versions. + * See + * the specification of MXBeans for details. + * + * + *

Each platform MXBean is a {@link PlatformManagedObject} + * and it has a unique + * {@link javax.management.ObjectName ObjectName} for + * registration in the platform {@code MBeanServer} as returned by + * by the {@link PlatformManagedObject#getObjectName getObjectName} + * method. * *

* An application can access a platform MXBean in the following ways: + *

1. Direct access to an MXBean interface
+ *
* + *
2. Indirect access to an MXBean interface via MBeanServer
+ * - * - *

Platform MXBeans

- * A platform MXBean is a managed bean that conforms to - * the JMX Instrumentation Specification and only uses - * a set of basic data types described below. - * See - * the specification of MXBeans for details. - * All platform MXBean interfaces extend {@link PlatformManagedObject}s - * and new methods may be added in these interfaces - * in future Java SE releases. - *

- * A JMX management application and the platform MBeanServer - * can interoperate without requiring classes for MXBean specific - * data types. - * The data types being transmitted between the JMX connector - * server and the connector client are - * {@linkplain javax.management.openmbean.OpenType open types} - * and this allows interoperation across versions. - *

- * The platform MXBean interfaces use only the following data types: - *

+ *
* *

- * When an attribute or operation of a platform MXBean - * is accessed via an MBeanServer, the data types are mapped - * as follows: - *

- * - * The {@link javax.management.MBeanInfo MBeanInfo} - * for a platform MXBean - * describes the data types of the attributes and operations - * as primitive or open types mapped as specified above. - * + * The {@link #getPlatformManagementInterfaces getPlatformManagementInterfaces} + * method returns all management interfaces supported in the Java virtual machine + * including the standard management interfaces listed in the tables + * below as well as the management interfaces extended by the JDK implementation. *

- * For example, the {@link MemoryMXBean} - * interface has the following getter and setter methods: - * - *

- * public MemoryUsage getHeapMemoryUsage();
- * public boolean isVerbose();
- * public void setVerbose(boolean value);
- * 
- * - * These attributes in the MBeanInfo - * of the MemoryMXBean have the following names and types: - * - *
- * - * - * - * - * - * - * - * - * - * - * - * - * - *
Attribute NameType
HeapMemoryUsage{@link MemoryUsage#from - * CompositeData representing MemoryUsage}
Verboseboolean
- *
- * - *

MXBean Names

- * Each platform MXBean for a Java virtual machine has a unique - * {@link javax.management.ObjectName ObjectName} for - * registration in the platform MBeanServer that can - * be obtained by calling the {@link PlatformManagedObject#getObjectName} - * method. - * * A Java virtual machine has a single instance of the following management * interfaces: * @@ -228,27 +141,32 @@ * * {@link ClassLoadingMXBean} * {@link #CLASS_LOADING_MXBEAN_NAME - * java.lang:type=ClassLoading} + * java.lang:type=ClassLoading} * * * {@link MemoryMXBean} * {@link #MEMORY_MXBEAN_NAME - * java.lang:type=Memory} + * java.lang:type=Memory} * * * {@link ThreadMXBean} * {@link #THREAD_MXBEAN_NAME - * java.lang:type=Threading} + * java.lang:type=Threading} * * * {@link RuntimeMXBean} * {@link #RUNTIME_MXBEAN_NAME - * java.lang:type=Runtime} + * java.lang:type=Runtime} * * * {@link OperatingSystemMXBean} * {@link #OPERATING_SYSTEM_MXBEAN_NAME - * java.lang:type=OperatingSystem} + * java.lang:type=OperatingSystem} + * + * + * {@link PlatformLoggingMXBean} + * {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME + * java.util.logging:type=Logging} * * * @@ -266,7 +184,7 @@ * * {@link CompilationMXBean} * {@link #COMPILATION_MXBEAN_NAME - * java.lang:type=Compilation} + * java.lang:type=Compilation} * * * @@ -283,17 +201,21 @@ * * {@link GarbageCollectorMXBean} * {@link #GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE - * java.lang:type=GarbageCollector},name=collector's name + * java.lang:type=GarbageCollector},name=collector's name * * * {@link MemoryManagerMXBean} * {@link #MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE - * java.lang:type=MemoryManager},name=manager's name + * java.lang:type=MemoryManager},name=manager's name * * * {@link MemoryPoolMXBean} * {@link #MEMORY_POOL_MXBEAN_DOMAIN_TYPE - * java.lang:type=MemoryPool},name=pool's name + * java.lang:type=MemoryPool},name=pool's name + * + * + * {@link BufferPoolMXBean} + * {@code java.nio:type=BufferPool,name=}pool name * * * @@ -302,7 +224,6 @@ * JMX Specification * @see * Ways to Access Management Metrics - * @see java.util.logging.LoggingMXBean * @see javax.management.MXBean * * @author Mandy Chung @@ -496,35 +417,35 @@ /** * Returns the platform {@link javax.management.MBeanServer MBeanServer}. * On the first call to this method, it first creates the platform - * MBeanServer by calling the + * {@code MBeanServer} by calling the * {@link javax.management.MBeanServerFactory#createMBeanServer * MBeanServerFactory.createMBeanServer} - * method and registers the platform MXBeans in this platform - * MBeanServer using the MXBean names - * defined in the class description. + * method and registers each platform MXBean in this platform + * {@code MBeanServer} with its + * {@link PlatformManagedObject#getObjectName ObjectName}. * This method, in subsequent calls, will simply return the - * initially created platform MBeanServer. + * initially created platform {@code MBeanServer}. *

* MXBeans that get created and destroyed dynamically, for example, * memory {@link MemoryPoolMXBean pools} and * {@link MemoryManagerMXBean managers}, * will automatically be registered and deregistered into the platform - * MBeanServer. + * {@code MBeanServer}. *

- * If the system property javax.management.builder.initial - * is set, the platform MBeanServer creation will be done + * If the system property {@code javax.management.builder.initial} + * is set, the platform {@code MBeanServer} creation will be done * by the specified {@link javax.management.MBeanServerBuilder}. *

* It is recommended that this platform MBeanServer also be used * to register other application managed beans * besides the platform MXBeans. * This will allow all MBeans to be published through the same - * MBeanServer and hence allow for easier network publishing + * {@code MBeanServer} and hence allow for easier network publishing * and discovery. * Name conflicts with the platform MXBeans should be avoided. * - * @return the platform MBeanServer; the platform - * MXBeans are registered into the platform MBeanServer + * @return the platform {@code MBeanServer}; the platform + * MXBeans are registered into the platform {@code MBeanServer} * at the first time this method is called. * * @exception SecurityException if there is a security manager @@ -671,7 +592,9 @@ try { final ObjectName objName = new ObjectName(mxbeanName); - if (!connection.isInstanceOf(objName, interfaceClass.getName())) { + // skip the isInstanceOf check for LoggingMXBean + String intfName = interfaceClass.getName(); + if (!connection.isInstanceOf(objName, intfName)) { throw new IllegalArgumentException(mxbeanName + " is not an instance of " + interfaceClass); } @@ -683,55 +606,128 @@ // create an MXBean proxy return JMX.newMXBeanProxy(connection, objName, mxbeanInterface, emitter); - } catch (InstanceNotFoundException e) { - final IllegalArgumentException iae = - new IllegalArgumentException(mxbeanName + - " not found in the connection."); - iae.initCause(e); - throw iae; - } catch (MalformedObjectNameException e) { - final IllegalArgumentException iae = - new IllegalArgumentException(mxbeanName + - " is not a valid ObjectName format."); - iae.initCause(e); - throw iae; + } catch (InstanceNotFoundException|MalformedObjectNameException e) { + throw new IllegalArgumentException(e); } } /** - * Returns the list of platform MXBeans that implement - * the given {@code mxbeanInterface} in the running Java + * Returns the platform MXBean implementing + * the given {@code mxbeanInterface} which is specified + * to have one single instance in the Java virtual machine. + * This method may return {@code null} if the management interface + * is not implemented in the Java virtual machine (for example, + * a Java virtual machine with no compilation system does not + * implement {@link CompilationMXBean}); + * otherwise, this method is equivalent to calling: + *

+     *    {@link #getPlatformMXBeans(Class)
+     *      getPlatformMXBeans(mxbeanInterface)}.get(0);
+     * 
+ * + * @param mxbeanInterface a management interface for a platform + * MXBean with one single instance in the Java virtual machine + * if implemented. + * + * @return the platform MXBean that implements + * {@code mxbeanInterface}, or {@code null} if not exist. + * + * @throws IllegalArgumentException if {@code mxbeanInterface} + * is not a platform management interface or + * not a singleton platform MXBean. + * + * @since 1.7 + */ + public static + T getPlatformMXBean(Class mxbeanInterface) { + PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface); + if (pc == null) + throw new IllegalArgumentException(mxbeanInterface.getName() + + " is not a platform management interface"); + if (!pc.isSingleton()) + throw new IllegalArgumentException(mxbeanInterface.getName() + + " can have zero or more than one instances"); + + return pc.getSingletonMXBean(mxbeanInterface); + } + + /** + * Returns the list of platform MXBeans implementing + * the given {@code mxbeanInterface} in the Java * virtual machine. * The returned list may contain zero, one, or more instances. * The number of instances in the returned list is defined * in the specification of the given management interface. + * The order is undefined and there is no guarantee that + * the list returned is in the same order as previous invocations. * * @param mxbeanInterface a management interface for a platform * MXBean * - * @return the list of platform MXBeans that implements + * @return the list of platform MXBeans that implement * {@code mxbeanInterface}. * * @throws IllegalArgumentException if {@code mxbeanInterface} - * is not a management interface for the platform. + * is not a platform management interface. * * @since 1.7 */ public static List getPlatformMXBeans(Class mxbeanInterface) { - String className = mxbeanInterface.getName(); - for (PlatformComponent component: PlatformComponent.values()) { - // comparing the class name first instead of the Class instance - // to avoid causing unnecessary class loading of - // the other MXBean interfaces - if (className.equals(component.getMXBeanInterfaceName())) { - if (component.getMXBeanInterface() == mxbeanInterface) { - return component.getMXBeans(mxbeanInterface); - } - } - } - throw new IllegalArgumentException(mxbeanInterface.getName() + - " is not implemented by any of the platform MXBeans."); + PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface); + if (pc == null) + throw new IllegalArgumentException(mxbeanInterface.getName() + + " is not a platform management interface"); + return Collections.unmodifiableList(pc.getMXBeans(mxbeanInterface)); + } + + /** + * Returns the platform MXBean proxy for + * {@code mxbeanInterface} which is specified to have one single + * instance in a Java virtual machine and the proxy will + * forward the method calls through the given {@code MBeanServerConnection}. + * This method may return {@code null} if the management interface + * is not implemented in the Java virtual machine being monitored + * (for example, a Java virtual machine with no compilation system + * does not implement {@link CompilationMXBean}); + * otherwise, this method is equivalent to calling: + *
+     *     {@link #getPlatformMXBeans(MBeanServerConnection, Class)
+     *        getPlatformMXBeans(connection, mxbeanInterface)}.get(0);
+     * 
+ * + * @param connection the {@code MBeanServerConnection} to forward to. + * @param mxbeanInterface a management interface for a platform + * MXBean with one single instance in the Java virtual machine + * being monitored, if implemented. + * + * @return the platform MXBean proxy for + * forwarding the method calls of the {@code mxbeanInterface} + * through the given {@code MBeanServerConnection}, + * or {@code null} if not exist. + * + * @throws IllegalArgumentException if {@code mxbeanInterface} + * is not a platform management interface or + * not a singleton platform MXBean. + * @throws java.io.IOException if a communication problem + * occurred when accessing the {@code MBeanServerConnection}. + * + * @see #newPlatformMXBeanProxy + * @since 1.7 + */ + public static + T getPlatformMXBean(MBeanServerConnection connection, + Class mxbeanInterface) + throws java.io.IOException + { + PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface); + if (pc == null) + throw new IllegalArgumentException(mxbeanInterface.getName() + + " is not a platform management interface"); + if (!pc.isSingleton()) + throw new IllegalArgumentException(mxbeanInterface.getName() + + " can have zero or more than one instances"); + return pc.getSingletonMXBean(connection, mxbeanInterface); } /** @@ -741,6 +737,8 @@ * The returned list may contain zero, one, or more instances. * The number of instances in the returned list is defined * in the specification of the given management interface. + * The order is undefined and there is no guarantee that + * the list returned is in the same order as previous invocations. * * @param connection the {@code MBeanServerConnection} to forward to. * @param mxbeanInterface a management interface for a platform @@ -751,54 +749,49 @@ * through the given {@code MBeanServerConnection}. * * @throws IllegalArgumentException if {@code mxbeanInterface} - * is not a management interface for the platform. + * is not a platform management interface. * * @throws java.io.IOException if a communication problem * occurred when accessing the {@code MBeanServerConnection}. * + * @see #newPlatformMXBeanProxy * @since 1.7 */ public static - List getPlatformMXBeans(MBeanServerConnection connection, - Class mxbeanInterface) + List getPlatformMXBeans(MBeanServerConnection connection, + Class mxbeanInterface) throws java.io.IOException { - String className = mxbeanInterface.getName(); - for (PlatformComponent component: PlatformComponent.values()) { - // comparing the class name first instead of the Class instance - // to avoid causing unnecessary class loading of - // the other MXBean interfaces - if (className.equals(component.getMXBeanInterfaceName())) { - if (component.getMXBeanInterface() == mxbeanInterface) { - return component.getMXBeans(connection, - mxbeanInterface); - } - } + PlatformComponent pc = PlatformComponent.getPlatformComponent(mxbeanInterface); + if (pc == null) { + throw new IllegalArgumentException(mxbeanInterface.getName() + + " is not a platform management interface"); } - throw new IllegalArgumentException(mxbeanInterface.getName() + - " is not implemented by any of the platform MXBeans."); + return Collections.unmodifiableList(pc.getMXBeans(connection, mxbeanInterface)); } /** - * Returns a list of {@code Class} objects, subinterface of + * Returns the set of {@code Class} objects, subinterface of * {@link PlatformManagedObject}, representing * all management interfaces for * monitoring and managing the Java platform. * - * @return a list of {@code Class} objects, subinterface of + * @return the set of {@code Class} objects, subinterface of * {@link PlatformManagedObject} representing * the management interfaces for * monitoring and managing the Java platform. * * @since 1.7 */ - public static List> getAllPlatformMXBeanInterfaces() { - List> result = - new ArrayList<>(); + public static Set> + getPlatformManagementInterfaces() + { + Set> result = + new TreeSet<>(); for (PlatformComponent component: PlatformComponent.values()) { result.add(component.getMXBeanInterface()); } - return result; + return Collections.unmodifiableSet(result); } private static final String NOTIF_EMITTER = @@ -810,7 +803,9 @@ private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) { // Make DynamicMBean out of MXBean by wrapping it with a StandardMBean final DynamicMBean dmbean; - if (pmo instanceof NotificationEmitter) { + if (pmo instanceof DynamicMBean) { + dmbean = DynamicMBean.class.cast(pmo); + } else if (pmo instanceof NotificationEmitter) { dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo); } else { dmbean = new StandardMBean(pmo, null, true); diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/PlatformComponent.java --- a/jdk/src/share/classes/java/lang/management/PlatformComponent.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/lang/management/PlatformComponent.java Wed Mar 30 01:00:23 2011 +0100 @@ -29,9 +29,9 @@ import java.util.Collections; import java.util.List; import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; import java.util.Set; -import java.util.logging.PlatformLoggingMXBean; -import java.nio.BufferPoolMXBean; import javax.management.MBeanServerConnection; import javax.management.ObjectName; @@ -66,6 +66,7 @@ CLASS_LOADING( "java.lang.management.ClassLoadingMXBean", "java.lang", "ClassLoading", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getClassLoadingMXBean()); @@ -78,6 +79,7 @@ COMPILATION( "java.lang.management.CompilationMXBean", "java.lang", "Compilation", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { CompilationMXBean m = ManagementFactoryHelper.getCompilationMXBean(); @@ -95,6 +97,7 @@ MEMORY( "java.lang.management.MemoryMXBean", "java.lang", "Memory", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getMemoryMXBean()); @@ -107,6 +110,7 @@ GARBAGE_COLLECTOR( "java.lang.management.GarbageCollectorMXBean", "java.lang", "GarbageCollector", keyProperties("name"), + false, // zero or more instances new MXBeanFetcher() { public List getMXBeans() { return ManagementFactoryHelper. @@ -120,6 +124,7 @@ MEMORY_MANAGER( "java.lang.management.MemoryManagerMXBean", "java.lang", "MemoryManager", keyProperties("name"), + false, // zero or more instances new MXBeanFetcher() { public List getMXBeans() { return ManagementFactoryHelper.getMemoryManagerMXBeans(); @@ -133,6 +138,7 @@ MEMORY_POOL( "java.lang.management.MemoryPoolMXBean", "java.lang", "MemoryPool", keyProperties("name"), + false, // zero or more instances new MXBeanFetcher() { public List getMXBeans() { return ManagementFactoryHelper.getMemoryPoolMXBeans(); @@ -145,6 +151,7 @@ OPERATING_SYSTEM( "java.lang.management.OperatingSystemMXBean", "java.lang", "OperatingSystem", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getOperatingSystemMXBean()); @@ -157,6 +164,7 @@ RUNTIME( "java.lang.management.RuntimeMXBean", "java.lang", "Runtime", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getRuntimeMXBean()); @@ -169,6 +177,7 @@ THREADING( "java.lang.management.ThreadMXBean", "java.lang", "Threading", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getThreadMXBean()); @@ -180,11 +189,17 @@ * Logging facility. */ LOGGING( - "java.util.logging.PlatformLoggingMXBean", + "java.lang.management.PlatformLoggingMXBean", "java.util.logging", "Logging", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { - return ManagementFactoryHelper.getLoggingMXBean(); + PlatformLoggingMXBean m = ManagementFactoryHelper.getPlatformLoggingMXBean(); + if (m == null) { + return Collections.emptyList(); + } else { + return Collections.singletonList(m); + } } }), @@ -192,8 +207,9 @@ * Buffer pools. */ BUFFER_POOL( - "java.nio.BufferPoolMXBean", + "java.lang.management.BufferPoolMXBean", "java.nio", "BufferPool", keyProperties("name"), + false, // zero or more instances new MXBeanFetcher() { public List getMXBeans() { return ManagementFactoryHelper.getBufferPoolMXBeans(); @@ -209,6 +225,7 @@ SUN_GARBAGE_COLLECTOR( "com.sun.management.GarbageCollectorMXBean", "java.lang", "GarbageCollector", keyProperties("name"), + false, // zero or more instances new MXBeanFetcher() { public List getMXBeans() { return getGcMXBeanList(com.sun.management.GarbageCollectorMXBean.class); @@ -222,6 +239,7 @@ SUN_OPERATING_SYSTEM( "com.sun.management.OperatingSystemMXBean", "java.lang", "OperatingSystem", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return getOSMXBeanList(com.sun.management.OperatingSystemMXBean.class); @@ -234,6 +252,7 @@ SUN_UNIX_OPERATING_SYSTEM( "com.sun.management.UnixOperatingSystemMXBean", "java.lang", "OperatingSystem", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return getOSMXBeanList(com.sun.management.UnixOperatingSystemMXBean.class); @@ -246,6 +265,7 @@ HOTSPOT_DIAGNOSTIC( "com.sun.management.HotSpotDiagnosticMXBean", "com.sun.management", "HotSpotDiagnostic", defaultKeyProperties(), + true, // singleton new MXBeanFetcher() { public List getMXBeans() { return Collections.singletonList(ManagementFactoryHelper.getDiagnosticMXBean()); @@ -296,27 +316,19 @@ private final Set keyProperties; private final MXBeanFetcher fetcher; private final PlatformComponent[] subComponents; + private final boolean singleton; private PlatformComponent(String intfName, String domain, String type, Set keyProperties, - MXBeanFetcher fetcher) { - this.mxbeanInterfaceName = intfName; - this.domain = domain; - this.type = type; - this.keyProperties = keyProperties; - this.fetcher = fetcher; - this.subComponents = new PlatformComponent[0]; - } - private PlatformComponent(String intfName, - String domain, String type, - Set keyProperties, + boolean singleton, MXBeanFetcher fetcher, PlatformComponent... subComponents) { this.mxbeanInterfaceName = intfName; this.domain = domain; this.type = type; this.keyProperties = keyProperties; + this.singleton = singleton; this.fetcher = fetcher; this.subComponents = subComponents; } @@ -338,6 +350,10 @@ return set; } + boolean isSingleton() { + return singleton; + } + String getMXBeanInterfaceName() { return mxbeanInterfaceName; } @@ -360,8 +376,35 @@ return fetcher.getMXBeans(); } + T getSingletonMXBean(Class mxbeanInterface) + { + if (!singleton) + throw new IllegalArgumentException(mxbeanInterfaceName + + " can have zero or more than one instances"); + + List list = fetcher.getMXBeans(); + assert list.size() == 1; + return list.isEmpty() ? null : list.get(0); + } + - List getMXBeans(MBeanServerConnection mbs, Class mxbeanInterface) + T getSingletonMXBean(MBeanServerConnection mbs, Class mxbeanInterface) + throws java.io.IOException + { + if (!singleton) + throw new IllegalArgumentException(mxbeanInterfaceName + + " can have zero or more than one instances"); + + // ObjectName of a singleton MXBean contains only domain and type + assert keyProperties.size() == 1; + String on = domain + ":type=" + type; + return ManagementFactory.newPlatformMXBeanProxy(mbs, + on, + mxbeanInterface); + } + + + List getMXBeans(MBeanServerConnection mbs, Class mxbeanInterface) throws java.io.IOException { List result = new ArrayList<>(); @@ -391,5 +434,34 @@ return set; } + // a map from MXBean interface name to PlatformComponent + private static Map enumMap; + private static synchronized void ensureInitialized() { + if (enumMap == null) { + enumMap = new HashMap<>(); + for (PlatformComponent pc: PlatformComponent.values()) { + // Use String as the key rather than Class to avoid + // causing unnecessary class loading of management interface + enumMap.put(pc.getMXBeanInterfaceName(), pc); + } + } + } + + static boolean isPlatformMXBean(String cn) { + ensureInitialized(); + return enumMap.containsKey(cn); + } + + static + PlatformComponent getPlatformComponent(Class mxbeanInterface) + { + ensureInitialized(); + String cn = mxbeanInterface.getName(); + PlatformComponent pc = enumMap.get(cn); + if (pc != null && pc.getMXBeanInterface() == mxbeanInterface) + return pc; + return null; + } + private static final long serialVersionUID = 6992337162326171013L; } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/PlatformLoggingMXBean.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/share/classes/java/lang/management/PlatformLoggingMXBean.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2009, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ + +package java.lang.management; + +/** + * The management interface for the {@linkplain java.util.logging logging} facility. + * + *

There is a single global instance of the PlatformLoggingMXBean. + * The {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) + * ManagementFactory.getPlatformMXBean} method can be used to obtain + * the {@code PlatformLoggingMXBean} object as follows: + *

+ *     PlatformLoggingMXBean logging = ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class);
+ * 
+ * The {@code PlatformLoggingMXBean} object is also registered with the + * platform {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer + * MBeanServer}. + * The {@link javax.management.ObjectName ObjectName} for uniquely + * identifying the {@code PlatformLoggingMXBean} within an MBeanServer is: + *
+ *      {@link java.util.logging.LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
+ * 
+ * + *

The instance registered in the platform MBeanServer with + * this {@code ObjectName} implements all attributes defined by + * {@link java.util.logging.LoggingMXBean}. + * + * @since 1.7 + */ +public interface PlatformLoggingMXBean extends PlatformManagedObject { + + /** + * Returns the list of the currently registered + * {@linkplain java.util.logging.Logger logger} names. This method + * calls {@link java.util.logging.LogManager#getLoggerNames} and + * returns a list of the logger names. + * + * @return A list of {@code String} each of which is a + * currently registered {@code Logger} name. + */ + java.util.List getLoggerNames(); + + /** + * Gets the name of the log {@linkplain java.util.logging.Logger#getLevel + * level} associated with the specified logger. + * If the specified logger does not exist, {@code null} + * is returned. + * This method first finds the logger of the given name and + * then returns the name of the log level by calling: + *

+ * {@link java.util.logging.Logger#getLevel + * Logger.getLevel()}.{@link java.util.logging.Level#getName getName()}; + *
+ * + *

+ * If the {@code Level} of the specified logger is {@code null}, + * which means that this logger's effective level is inherited + * from its parent, an empty string will be returned. + * + * @param loggerName The name of the {@code Logger} to be retrieved. + * + * @return The name of the log level of the specified logger; or + * an empty string if the log level of the specified logger + * is {@code null}. If the specified logger does not + * exist, {@code null} is returned. + * + * @see java.util.logging.Logger#getLevel + */ + String getLoggerLevel(String loggerName); + + /** + * Sets the specified logger to the specified new + * {@linkplain java.util.logging.Logger#setLevel level}. + * If the {@code levelName} is not {@code null}, the level + * of the specified logger is set to the parsed + * {@link java.util.logging.Level Level} + * matching the {@code levelName}. + * If the {@code levelName} is {@code null}, the level + * of the specified logger is set to {@code null} and + * the effective level of the logger is inherited from + * its nearest ancestor with a specific (non-null) level value. + * + * @param loggerName The name of the {@code Logger} to be set. + * Must be non-null. + * @param levelName The name of the level to set on the specified logger, + * or {@code null} if setting the level to inherit + * from its nearest ancestor. + * + * @throws IllegalArgumentException if the specified logger + * does not exist, or {@code levelName} is not a valid level name. + * + * @throws SecurityException if a security manager exists and if + * the caller does not have LoggingPermission("control"). + * + * @see java.util.logging.Logger#setLevel + */ + void setLoggerLevel(String loggerName, String levelName); + + /** + * Returns the name of the + * {@linkplain java.util.logging.Logger#getParent parent} + * for the specified logger. + * If the specified logger does not exist, {@code null} is returned. + * If the specified logger is the root {@code Logger} in the namespace, + * the result will be an empty string. + * + * @param loggerName The name of a {@code Logger}. + * + * @return the name of the nearest existing parent logger; + * an empty string if the specified logger is the root logger. + * If the specified logger does not exist, {@code null} + * is returned. + */ + String getParentLoggerName(String loggerName); +} diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/PlatformManagedObject.java --- a/jdk/src/share/classes/java/lang/management/PlatformManagedObject.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/lang/management/PlatformManagedObject.java Wed Mar 30 01:00:23 2011 +0100 @@ -46,7 +46,7 @@ * intended for the management interfaces for the platform to extend but * not for applications. * - * @see Platform MXBeans + * @see ManagementFactory * @since 1.7 */ public interface PlatformManagedObject { diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/lang/management/package.html --- a/jdk/src/share/classes/java/lang/management/package.html Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/lang/management/package.html Wed Mar 30 01:00:23 2011 +0100 @@ -27,160 +27,124 @@ -Provides the management interface for monitoring and management of the -Java virtual machine as well as the operating system on which the -Java virtual machine is running. It allows both local and remote -monitoring and management of the running Java virtual machine. - -

Platform MXBeans

- -This package defines the management interface of the following -components: +Provides the management interfaces for monitoring and management of the +Java virtual machine and other components in the Java runtime. +It allows both local and remote +monitoring and management of the running Java virtual machine. +

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Management Interface

Description

{@link java.lang.management.ClassLoadingMXBean} Class loading system of the Java virtual machine.
{@link java.lang.management.CompilationMXBean} Compilation system of the Java virtual machine.
{@link java.lang.management.MemoryMXBean} Memory system of the Java virtual machine.
{@link java.lang.management.ThreadMXBean} Threads system of the Java virtual machine.
{@link java.lang.management.RuntimeMXBean} Runtime system of the Java virtual machine.
{@link java.lang.management.OperatingSystemMXBean} Operating system on which the Java virtual machine is running.
{@link java.lang.management.GarbageCollectorMXBean} Garbage collector in the Java virtual machine.
{@link java.lang.management.MemoryManagerMXBean} Memory manager in the Java virtual machine.
{@link java.lang.management.MemoryPoolMXBean} Memory pool in the Java virtual machine.
-
- +

Platform MXBean

-A platform MXBean is a managed bean that defines the management -interface for one component for the platform and is specified in the - -ManagementFactory class. - -

An application can monitor the instrumentation of the -Java virtual machine and manage certain characteristics in -the following ways: -

    -
  • Direct access to an MXBean interface -
      -
    1. Get the MXBean instance through the static factory method - and access the MXBean interface locally of the running - virtual machine.
    2. -
    3. Construct an MXBean proxy instance that - forwards the method calls to a given - {@link javax.management.MBeanServer MBeanServer} - by calling - {@link java.lang.management.ManagementFactory#newPlatformMXBeanProxy - ManagementFactory.newPlatformMXBeanProxy}. - A proxy is typically constructed to remotely access - an MXBean of another running virtual machine.
    4. -
  • -
  • Indirect access via {@link javax.management.MBeanServer MBeanServer} - interface -
      -
    1. Go through the - {@link java.lang.management.ManagementFactory#getPlatformMBeanServer - platform MBeanServer} to access MXBeans locally or - a specific MBeanServerConnection to access - MXBeans remotely. - The attributes and operations of an MXBean use only - JMX open types which include basic data types, - {@link javax.management.openmbean.CompositeData CompositeData}, - and {@link javax.management.openmbean.TabularData TabularData} - defined in {@link javax.management.openmbean.OpenType OpenType}. -
    2. -
  • -
- -Below shows a few examples of different -ways to access MXBeans. - +A platform MXBean is a managed bean that +conforms to the JMX +Instrumentation Specification and only uses a set of basic data types. +Each platform MXBean is a {@link java.lang.management.PlatformManagedObject} +with a unique +{@linkplain java.lang.management.PlatformManagedObject#getObjectName name}. +

ManagementFactory

-The {@link java.lang.management.ManagementFactory} class is the management -factory class for the Java platform. This class provides a set of +

The {@link java.lang.management.ManagementFactory} class is the management +factory class for the Java platform. This class provides a set of static factory methods to obtain the MXBeans for the Java platform to allow an application to access the MXBeans directly.

A platform MBeanServer can be accessed with the {@link java.lang.management.ManagementFactory#getPlatformMBeanServer getPlatformMBeanServer} method. On the first call to this method, -it creates the platform MBeanServer and registers all platform MXBeans -including platform MXBeans defined in other packages such as -{@link java.util.logging.LoggingMXBean}. -Each platform MXBean is registered with a unique name defined in the -{@link java.lang.management.ManagementFactory ManagementFactory} class -for constructing {@link javax.management.ObjectName ObjectName}. -This is a single MBeanServer that can be shared by different managed +it creates the platform MBeanServer and registers all platform MXBeans +including {@linkplain java.lang.management.PlatformManagedObject +platform MXBeans}. +Each platform MXBean is registered with a unique name defined in +the specification of the management interface. +This is a single MBeanServer that can be shared by different managed components running within the same Java virtual machine. - +

Interoperability

-A management application and a platform MBeanServer of a running -virtual machine can interoperate +

A management application and a platform MBeanServer of a running +virtual machine can interoperate without requiring classes used by the platform MXBean interfaces. The data types being transmitted between the JMX connector server and the connector client are JMX -{@link javax.management.openmbean.OpenType open types} and +{@linkplain javax.management.openmbean.OpenType open types} and this allows interoperation across versions. - -

A data type used by the MXBean interfaces are mapped to -an open type when being accessed via MBeanServer interface. -The data type mapping is specified in the -{@link java.lang.management.ManagementFactory ManagementFactory} class. +A data type used by the MXBean interfaces are mapped to an +open type when being accessed via MBeanServer interface. +See the +MXBean specification for details.

Ways to Access MXBeans

-There are three different ways to access the management interfaces. - +

An application can monitor the instrumentation of the +Java virtual machine and the runtime in the following ways:

-

    -
  1. Call the methods in the MXBean directly within the same - Java virtual machine. -
    +1. Direct access to an MXBean interface
    +

    +

      +
    • Get an MXBean instance locally in the running Java virtual machine:

      +

          RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
       
          // Get the standard attribute "VmVendor"
          String vendor = mxbean.getVmVendor();
      -
       
      -
    +

    Or by calling the + {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) + getPlatformMXBean} or + {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class) + getPlatformMXBeans} method: +

    +   RuntimeMXBean mxbean = ManagementFactory.getPlatformMXBean(RuntimeMXBean.class);
    +
    +   // Get the standard attribute "VmVendor"
    +   String vendor = mxbean.getVmVendor();
    +
    +

  2. +
  3. Construct an MXBean proxy instance that forwards the + method calls to a given MBeanServer:

    +

    +   MBeanServerConnection mbs;
     
    -
  4. Go through a MBeanServerConnection connecting - to the platform MBeanServer of a running virtual machine.
  5. -
    +   // Connect to a running JVM (or itself) and get MBeanServerConnection
    +   // that has the JVM MBeans registered in it
    +   ...
    +
    +   // Get a MBean proxy for RuntimeMXBean interface
    +   RuntimeMXBean proxy =
    +       {@link java.lang.management.ManagementFactory#getPlatformMXBean(MBeanServerConnection, Class)
    +       ManagementFactory.getPlatformMXBean}(mbs,
    +                                           RuntimeMXBean.class);
    +   // Get standard attribute "VmVendor"
    +   String vendor = proxy.getVmVendor();
    +
    +

    A proxy is typically used to access an MXBean + in a remote Java virtual machine. + An alternative way to create an MXBean proxy is: +

    +   RuntimeMXBean proxy =
    +       {@link java.lang.management.ManagementFactory#newPlatformMXBeanProxy
    +              ManagementFactory.newPlatformMXBeanProxy}(mbs,
    +                                                ManagementFactory.RUNTIME_MXBEAN_NAME,
    +                                                RuntimeMXBean.class);
    +
    +
  6. + +

    +2. Indirect access to an MXBean interface via MBeanServer

    +

      +
    • Go through the + {@link java.lang.management.ManagementFactory#getPlatformMBeanServer + platform MBeanServer} to access MXBeans locally or + a specific {@code MBeanServerConnection} to access + MXBeans remotely. + The attributes and operations of an MXBean use only + JMX open types which include basic data types, + {@link javax.management.openmbean.CompositeData CompositeData}, + and {@link javax.management.openmbean.TabularData TabularData} + defined in {@link javax.management.openmbean.OpenType OpenType}.

      +

          MBeanServerConnection mbs;
       
          // Connect to a running JVM (or itself) and get MBeanServerConnection
      @@ -190,7 +154,7 @@
          try {
              // Assuming the RuntimeMXBean has been registered in mbs
              ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
      -    
      +
              // Get standard attribute "VmVendor"
              String vendor = (String) mbs.getAttribute(oname, "VmVendor");
          } catch (....) {
      @@ -198,36 +162,19 @@
              // and MBeanServer.getAttribute method
              ...
          }
      -
      -
      - -
    • Use MXBean proxy.
    • -
      -   MBeanServerConnection mbs;
      -
      -   // Connect to a running JVM (or itself) and get MBeanServerConnection
      -   // that has the JVM MBeans registered in it
      -   ...
      -
      -   // Get a MBean proxy for RuntimeMXBean interface
      -   RuntimeMXBean proxy = 
      -       ManagementFactory.newPlatformMXBeanProxy(mbs,
      -                                                ManagementFactory.RUNTIME_MXBEAN_NAME,
      -                                                RuntimeMXBean.class);
      -   // Get standard attribute "VmVendor" 
      -   String vendor = proxy.getVmVendor();
      -
      -
+ + +

Platform Extension

-A Java virtual machine implementation may add its platform extension to +

A Java virtual machine implementation may add its platform extension to the management interface by defining platform-dependent interfaces that extend the standard management interfaces to include -platform-specific metrics and management operations. +platform-specific metrics and management operations. The static factory methods in the ManagementFactory class will -return the MBeans with the platform extension. +return the MXBeans with the platform extension.

It is recommended to name the platform-specific attributes with @@ -240,26 +187,30 @@ the applications accessing that vendor-specific attribute would have to be modified to cope with versioning and compatibility issues. -

Below is an example showing how to access a platform-specific -attribute from Sun's implementation of the RuntimeMXBean. +

Below is an example showing how to access an attribute +from the platform extension:

-1) Direct access to the Sun-specific MXBean interface -

-   com.sun.management.RuntimeMXBean mxbean = 
-       (com.sun.management.RuntimeMXBean) ManagementFactory.getRuntimeMXBean();
+1) Direct access to the Oracle-specific MXBean interface
+
+
+   List<com.sun.management.GarbageCollectorMXBean> mxbeans =
+       ManagementFactory.getPlatformMXBeans(com.sun.management.GarbageCollectorMXBean.class);
 
-   // Get the standard attribute "VmVendor"
-   String vendor = mxbean.getVmVendor();
+   for (com.sun.management.GarbageCollectorMXBean gc : mxbeans) {
+       // Get the standard attribute "CollectionCount"
+       String count = mxbean.getCollectionCount();
 
-   // Get the platform-specific attribute "Bar"
-   BarType bar = mxbean.getBar();
-
+       // Get the platform-specific attribute "LastGcInfo"
+       GcInfo gcinfo = gc.getLastGcInfo();
+       ...
+   }
 

-2) Access the Sun-specific MXBean interface via MBeanServer +2) Access the Oracle-specific MXBean interface via MBeanServer + through proxy

    MBeanServerConnection mbs;
@@ -268,24 +219,17 @@
    // that has the JVM MXBeans registered in it
    ...
 
-   try {
-       // Assuming the RuntimeMXBean has been registered in mbs
-       ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
-    
-       // Get standard attribute "VmVendor"
-       String vendor = (String) mbs.getAttribute(oname, "VmVendor");
+   List<com.sun.management.GarbageCollectorMXBean> mxbeans =
+       ManagementFactory.getPlatformMXBeans(mbs, com.sun.management.GarbageCollectorMXBean.class);
 
-       // Check if this MXBean contains Sun's extension
-       if (mbs.isInstanceOf(oname, "com.sun.management.RuntimeMXBean")) {
-           // Get platform-specific attribute "Bar"
-           BarType bar = (String) mbs.getAttribute(oname, "Bar");
-       }
-   } catch (....) {
-       // Catch the exceptions thrown by ObjectName constructor
-       // and MBeanServer methods
+   for (com.sun.management.GarbageCollectorMXBean gc : mxbeans) {
+       // Get the standard attribute "CollectionCount"
+       String count = mxbean.getCollectionCount();
+
+       // Get the platform-specific attribute "LastGcInfo"
+       GcInfo gcinfo = gc.getLastGcInfo();
        ...
    }
-
 

Unless otherwise noted, passing a null argument to a constructor diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/nio/BufferPoolMXBean.java --- a/jdk/src/share/classes/java/nio/BufferPoolMXBean.java Wed Mar 30 00:59:07 2011 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2007, 2008, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ - -package java.nio; - -import java.lang.management.PlatformManagedObject; - -/** - * The management interface for a buffer pool. - * - *

A class implementing this interface is an MXBean. A Java - * virtual machine has one or more implementations of this interface. The {@link - * java.lang.management.ManagementFactory#getPlatformMXBeans getPlatformMXBeans} - * method can be used to obtain the list of {@code BufferPoolMXBean} objects - * representing the management interfaces for pools of buffers as follows: - *

- *     List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
- * 
- * - *

The management interfaces are also registered with the platform {@link - * javax.management.MBeanServer MBeanServer}. The {@link - * javax.management.ObjectName ObjectName} that uniquely identifies the - * management interface within the {@code MBeanServer} takes the form: - *

- * java.nio:type=BufferPool,name=pool name - *
- * where pool name is the {@link #getName name} of the buffer pool. - * - * @since 1.7 - */ - -public interface BufferPoolMXBean extends PlatformManagedObject { - - /** - * Returns the name representing this buffer pool. - * - * @return The name of this buffer pool. - */ - String getName(); - - /** - * Returns an estimate of the number of buffers in the pool. - * - * @return An estimate of the number of buffers in this pool - */ - long getCount(); - - /** - * Returns an estimate of the total capacity of the buffers in this pool. - * A buffer's capacity is the number of elements it contains and the value - * returned by this method is an estimate of the total capacity of buffers - * in the pool in bytes. - * - * @return An estimate of the total capacity of the buffers in this pool - * in bytes - */ - long getTotalCapacity(); - - /** - * Returns an estimate of the memory that the Java virtual machine is using - * for this buffer pool. The value returned by this method may differ - * from the estimate of the total {@link #getTotalCapacity capacity} of - * the buffers in this pool. This difference is explained by alignment, - * memory allocator, and other implementation specific reasons. - * - * @return An estimate of the memory that the Java virtual machine is using - * for this buffer pool in bytes, or {@code -1L} if an estimate of - * the memory usage is not available - */ - long getMemoryUsed(); -} diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/util/logging/LogManager.java --- a/jdk/src/share/classes/java/util/logging/LogManager.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/util/logging/LogManager.java Wed Mar 30 01:00:23 2011 +0100 @@ -1166,7 +1166,12 @@ private static LoggingMXBean loggingMXBean = null; /** * String representation of the - * {@link javax.management.ObjectName} for {@link LoggingMXBean}. + * {@link javax.management.ObjectName} for the management interface + * for the logging facility. + * + * @see java.lang.management.PlatformLoggingMXBean + * @see java.util.logging.LoggingMXBean + * * @since 1.5 */ public final static String LOGGING_MXBEAN_NAME @@ -1174,20 +1179,20 @@ /** * Returns LoggingMXBean for managing loggers. - * An alternative way to manage loggers is using - * the {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class) - * ManagementFactory.getPlatformMXBeans} method as follows: + * An alternative way to manage loggers is through the + * {@link java.lang.management.PlatformLoggingMXBean} interface + * that can be obtained by calling: *
-     *     List<{@link PlatformLoggingMXBean}> result = ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class);
+     *     PlatformLoggingMXBean logging = {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class)
+     *         ManagementFactory.getPlatformMXBean}(PlatformLoggingMXBean.class);
      * 
* * @return a {@link LoggingMXBean} object. * - * @see PlatformLoggingMXBean - * @see java.lang.management.ManagementFactory + * @see java.lang.management.PlatformLoggingMXBean * @since 1.5 */ - public static synchronized LoggingMXBean getLoggingMXBean() { + public static synchronized LoggingMXBean getLoggingMXBean() { if (loggingMXBean == null) { loggingMXBean = new Logging(); } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/util/logging/LoggingMXBean.java --- a/jdk/src/share/classes/java/util/logging/LoggingMXBean.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/util/logging/LoggingMXBean.java Wed Mar 30 01:00:23 2011 +0100 @@ -27,36 +27,41 @@ /** - * The management interface for the logging facility. + * The management interface for the logging facility. It is recommended + * to use the {@link java.lang.management.PlatformLoggingMXBean} management + * interface that implements all attributes defined in this + * {@code LoggingMXBean}. The + * {@link java.lang.management.ManagementFactory#getPlatformMXBean(Class) + * ManagementFactory.getPlatformMXBean} method can be used to obtain + * the {@code PlatformLoggingMXBean} object representing the management + * interface for logging. * *

There is a single global instance of the LoggingMXBean. - * This instance is an - * MXBean - * can be obtained by calling - * the {@link LogManager#getLoggingMXBean} method or from the + * This instance is an {@link javax.management.MXBean MXBean} that + * can be obtained by calling the {@link LogManager#getLoggingMXBean} + * method or from the * {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer * platform MBeanServer}. - * - * The {@link javax.management.ObjectName ObjectName} for uniquely - * identifying the LoggingMXBean within an MBeanServer is: - *

- * {@link LogManager#LOGGING_MXBEAN_NAME - * java.util.logging:type=Logging} - *
- * - * The instance registered in the platform MBeanServer with - * this {@code ObjectName} is also a {@link PlatformLoggingMXBean}. + *

+ * The {@link javax.management.ObjectName ObjectName} that uniquely identifies + * the management interface for logging within the {@code MBeanServer} is: + *

+ *    {@link LogManager#LOGGING_MXBEAN_NAME java.util.logging:type=Logging}
+ * 
+ *

+ * The instance registered in the platform {@code MBeanServer} + * is also a {@link java.lang.management.PlatformLoggingMXBean}. * * @author Ron Mann * @author Mandy Chung * @since 1.5 * - * @see PlatformLoggingMXBean + * @see java.lang.management.PlatformLoggingMXBean */ public interface LoggingMXBean { /** - * Returns the list of currently registered loggers. This method + * Returns the list of currently registered logger names. This method * calls {@link LogManager#getLoggerNames} and returns a list * of the logger names. * @@ -89,7 +94,7 @@ * * @see Logger#getLevel */ - public String getLoggerLevel( String loggerName ); + public String getLoggerLevel(String loggerName); /** * Sets the specified logger to the specified new level. @@ -115,7 +120,7 @@ * * @see Logger#setLevel */ - public void setLoggerLevel( String loggerName, String levelName ); + public void setLoggerLevel(String loggerName, String levelName); /** * Returns the name of the parent for the specified logger. diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java --- a/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/util/logging/LoggingProxyImpl.java Wed Mar 30 01:00:23 2011 +0100 @@ -99,4 +99,9 @@ public String getLevelName(Object level) { return ((Level) level).getName(); } + + @Override + public String getProperty(String key) { + return LogManager.getLogManager().getProperty(key); + } } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/util/logging/PlatformLoggingMXBean.java --- a/jdk/src/share/classes/java/util/logging/PlatformLoggingMXBean.java Wed Mar 30 00:59:07 2011 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2009, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ - -package java.util.logging; - -import java.lang.management.PlatformManagedObject; - -/** - * The {@linkplain PlatformManagedObject platform managed object} for the - * logging facility. This interface simply unifies {@link LoggingMXBean} - * {@link PlatformManagedObject}; - * and it does not specify any new operations. - * - *

The {@link java.lang.management.ManagementFactory#getPlatformMXBeans(Class) - * ManagementFactory.getPlatformMXBeans} method can be used to obtain - * the {@code PlatformLoggingMXBean} object as follows: - *

- *     ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class);
- * 
- * or from the {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer - * platform MBeanServer}. - * - * The {@link javax.management.ObjectName ObjectName} for uniquely - * identifying the LoggingMXBean within an MBeanServer is: - *
- * java.util.logging:type=Logging - *
- * - * The {@link PlatformManagedObject#getObjectName} method - * can be used to obtain its {@code ObjectName}. - * - * @see java.lang.management.PlatformManagedObject - * - * @author Mandy Chung - * @since 1.7 - */ -public interface PlatformLoggingMXBean extends LoggingMXBean, PlatformManagedObject { -} diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/java/util/logging/SimpleFormatter.java --- a/jdk/src/share/classes/java/util/logging/SimpleFormatter.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/java/util/logging/SimpleFormatter.java Wed Mar 30 01:00:23 2011 +0100 @@ -29,31 +29,108 @@ import java.io.*; import java.text.*; import java.util.Date; +import sun.util.logging.LoggingSupport; /** - * Print a brief summary of the LogRecord in a human readable + * Print a brief summary of the {@code LogRecord} in a human readable * format. The summary will typically be 1 or 2 lines. * + *

+ * + * Configuration: + * The {@code SimpleFormatter} is initialized with the + * format string + * specified in the {@code java.util.logging.SimpleFormatter.format} + * property to {@linkplain #format format} the log messages. + * This property can be defined + * in the {@linkplain LogManager#getProperty logging properties} + * configuration file + * or as a system property. If this property is set in both + * the logging properties and system properties, + * the format string specified in the system property will be used. + * If this property is not defined or the given format string + * is {@linkplain java.util.IllegalFormatException illegal}, + * the default format is implementation-specific. + * * @since 1.4 + * @see java.util.Formatter */ public class SimpleFormatter extends Formatter { - Date dat = new Date(); - private final static String format = "{0,date} {0,time}"; - private MessageFormat formatter; - - private Object args[] = new Object[1]; - - // Line separator string. This is the value of the line.separator - // property at the moment that the SimpleFormatter was created. - private String lineSeparator = java.security.AccessController.doPrivileged( - new sun.security.action.GetPropertyAction("line.separator")); + // format string for printing the log record + private static final String format = LoggingSupport.getSimpleFormat(); + private final Date dat = new Date(); /** * Format the given LogRecord. *

- * This method can be overridden in a subclass. + * The formatting can be customized by specifying the + * format string + * in the + * {@code java.util.logging.SimpleFormatter.format} property. + * The given {@code LogRecord} will be formatted as if by calling: + *

+     *    {@link String#format String.format}(format, date, source, logger, level, message, thrown);
+     * 
+ * where the arguments are:
+ *
    + *
  1. {@code format} - the {@link java.util.Formatter + * java.util.Formatter} format string specified in the + * {@code java.util.logging.SimpleFormatter.format} property + * or the default format.
  2. + *
  3. {@code date} - a {@link Date} object representing + * {@linkplain LogRecord#getMillis event time} of the log record.
  4. + *
  5. {@code source} - a string representing the caller, if available; + * otherwise, the logger's name.
  6. + *
  7. {@code logger} - the logger's name.
  8. + *
  9. {@code level} - the {@linkplain Level#getLocalizedName + * log level}.
  10. + *
  11. {@code message} - the formatted log message + * returned from the {@link Formatter#formatMessage(LogRecord)} + * method. It uses {@link java.text.MessageFormat java.text} + * formatting and does not use the {@code java.util.Formatter + * format} argument.
  12. + *
  13. {@code thrown} - a string representing + * the {@linkplain LogRecord#getThrown throwable} + * associated with the log record and its backtrace + * beginning with a newline character, if any; + * otherwise, an empty string.
  14. + *
+ * + *

Some example formats:
+ *

    + *
  • {@code java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"} + *

    This prints 1 line with the log level ({@code 4$}), + * the log message ({@code 5$}) and the timestamp ({@code 1$}) in + * a square bracket. + *

    +     *     WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
    +     *     
  • + *
  • {@code java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"} + *

    This prints 2 lines where the first line includes + * the timestamp ({@code 1$}) and the source ({@code 2$}); + * the second line includes the log level ({@code 4$}) and + * the log message ({@code 5$}) followed with the throwable + * and its backtrace ({@code 6$}), if any: + *

    +     *     Tue Mar 22 13:11:31 PDT 2011 MyClass fatal
    +     *     SEVERE: several message with an exception
    +     *     java.lang.IllegalArgumentException: invalid argument
    +     *             at MyClass.mash(MyClass.java:9)
    +     *             at MyClass.crunch(MyClass.java:6)
    +     *             at MyClass.main(MyClass.java:3)
    +     *     
  • + *
  • {@code java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"} + *

    This prints 2 lines similar to the example above + * with a different date/time formatting and does not print + * the throwable and its backtrace: + *

    +     *     Mar 22, 2011 1:11:31 PM MyClass fatal
    +     *     SEVERE: several message with an exception
    +     *     
  • + *
+ *

This method can also be overridden in a subclass. * It is recommended to use the {@link Formatter#formatMessage} * convenience method to localize and format the message field. * @@ -61,42 +138,32 @@ * @return a formatted log record */ public synchronized String format(LogRecord record) { - StringBuffer sb = new StringBuffer(); - // Minimize memory allocations here. dat.setTime(record.getMillis()); - args[0] = dat; - StringBuffer text = new StringBuffer(); - if (formatter == null) { - formatter = new MessageFormat(format); - } - formatter.format(args, text, null); - sb.append(text); - sb.append(" "); + String source; if (record.getSourceClassName() != null) { - sb.append(record.getSourceClassName()); + source = record.getSourceClassName(); + if (record.getSourceMethodName() != null) { + source += " " + record.getSourceMethodName(); + } } else { - sb.append(record.getLoggerName()); + source = record.getLoggerName(); } - if (record.getSourceMethodName() != null) { - sb.append(" "); - sb.append(record.getSourceMethodName()); - } - sb.append(lineSeparator); String message = formatMessage(record); - sb.append(record.getLevel().getLocalizedName()); - sb.append(": "); - sb.append(message); - sb.append(lineSeparator); + String throwable = ""; if (record.getThrown() != null) { - try { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - record.getThrown().printStackTrace(pw); - pw.close(); - sb.append(sw.toString()); - } catch (Exception ex) { - } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.println(); + record.getThrown().printStackTrace(pw); + pw.close(); + throwable = sw.toString(); } - return sb.toString(); + return String.format(format, + dat, + source, + record.getLoggerName(), + record.getLevel().getLocalizedName(), + message, + throwable); } } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/management/ManagementFactoryHelper.java --- a/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/management/ManagementFactoryHelper.java Wed Mar 30 01:00:23 2011 +0100 @@ -27,20 +27,18 @@ import java.lang.management.*; -import javax.management.MBeanServer; -import javax.management.ObjectName; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; +import javax.management.MBeanServer; import javax.management.MBeanRegistrationException; import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; import javax.management.RuntimeOperationsException; -import java.nio.BufferPoolMXBean; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import sun.security.action.LoadLibraryAction; -import java.util.logging.PlatformLoggingMXBean; import sun.util.logging.LoggingSupport; import java.util.ArrayList; @@ -139,61 +137,80 @@ return result; } - public static List getLoggingMXBean() { + public static PlatformLoggingMXBean getPlatformLoggingMXBean() { if (LoggingSupport.isAvailable()) { - return Collections.singletonList(createPlatformLoggingMXBean()); + return PlatformLoggingImpl.instance; } else { - return Collections.emptyList(); + return null; } } - private final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging"; - private static PlatformLoggingMXBean createPlatformLoggingMXBean() { - return new PlatformLoggingMXBean() { - private volatile ObjectName objname; // created lazily - @Override - public ObjectName getObjectName() { - ObjectName result = objname; - if (result == null) { - synchronized (this) { - if (objname == null) { - result = Util.newObjectName(LOGGING_MXBEAN_NAME); - objname = result; - } + // 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 + extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean { + } + + static class PlatformLoggingImpl implements LoggingMXBean + { + final static PlatformLoggingMXBean instance = new PlatformLoggingImpl(); + final static String LOGGING_MXBEAN_NAME = "java.util.logging:type=Logging"; + + private volatile ObjectName objname; // created lazily + @Override + public ObjectName getObjectName() { + ObjectName result = objname; + if (result == null) { + synchronized (this) { + if (objname == null) { + result = Util.newObjectName(LOGGING_MXBEAN_NAME); + objname = result; } } - return result; } + return result; + } - @Override - public java.util.List getLoggerNames() { - return LoggingSupport.getLoggerNames(); - } + @Override + public java.util.List getLoggerNames() { + return LoggingSupport.getLoggerNames(); + } - @Override - public String getLoggerLevel(String loggerName) { - return LoggingSupport.getLoggerLevel(loggerName); - } + @Override + public String getLoggerLevel(String loggerName) { + return LoggingSupport.getLoggerLevel(loggerName); + } - @Override - public void setLoggerLevel(String loggerName, String levelName) { - LoggingSupport.setLoggerLevel(loggerName, levelName); - } + @Override + public void setLoggerLevel(String loggerName, String levelName) { + LoggingSupport.setLoggerLevel(loggerName, levelName); + } - @Override - public String getParentLoggerName(String loggerName) { - return LoggingSupport.getParentLoggerName(loggerName); - } - }; + @Override + public String getParentLoggerName(String loggerName) { + return LoggingSupport.getParentLoggerName(loggerName); + } } - public static List getBufferPoolMXBeans() { - List pools = new ArrayList(2); - pools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess() - .getDirectBufferPool())); - pools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl - .getMappedBufferPool())); - return pools; + private static List bufferPools = null; + public static synchronized List getBufferPoolMXBeans() { + if (bufferPools == null) { + bufferPools = new ArrayList<>(2); + bufferPools.add(createBufferPoolMXBean(sun.misc.SharedSecrets.getJavaNioAccess() + .getDirectBufferPool())); + bufferPools.add(createBufferPoolMXBean(sun.nio.ch.FileChannelImpl + .getMappedBufferPool())); + } + return bufferPools; } private final static String BUFFER_POOL_MXBEAN_NAME = "java.nio:type=BufferPool"; diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/security/tools/JarSigner.java --- a/jdk/src/share/classes/sun/security/tools/JarSigner.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/security/tools/JarSigner.java Wed Mar 30 01:00:23 2011 +0100 @@ -1238,8 +1238,6 @@ // Provide a helpful message when TSA is beyond a firewall error(rb.getString("unable.to.sign.jar.") + rb.getString("no.response.from.the.Timestamping.Authority.") + - rb.getString("When.connecting.from.behind.a.firewall.an.HTTP.or.HTTPS.proxy.may.need.to.be.specified.") + - rb.getString("Supply.the.following.options.to.jarsigner.") + "\n -J-Dhttp.proxyHost=" + "\n -J-Dhttp.proxyPort=\n" + rb.getString("or") + diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/security/tools/JarSignerResources.java --- a/jdk/src/share/classes/sun/security/tools/JarSignerResources.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/security/tools/JarSignerResources.java Wed Mar 30 01:00:23 2011 +0100 @@ -181,11 +181,9 @@ {"TSA.location.", "TSA location: "}, {"TSA.certificate.", "TSA certificate: "}, {"no.response.from.the.Timestamping.Authority.", - "no response from the Timestamping Authority. "}, - {"When.connecting.from.behind.a.firewall.an.HTTP.or.HTTPS.proxy.may.need.to.be.specified.", - "When connecting from behind a firewall an HTTP or HTTPS proxy may need to be specified. "}, - {"Supply.the.following.options.to.jarsigner.", - "Supply the following options to jarsigner: "}, + "no response from the Timestamping Authority. When connecting" + + " from behind a firewall an HTTP or HTTPS proxy may need to" + + " be specified. Supply the following options to jarsigner:"}, {"or", "or"}, {"Certificate.not.found.for.alias.alias.must.reference.a.valid.KeyStore.entry.containing.an.X.509.public.key.certificate.for.the", "Certificate not found for: {0}. {1} must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority."}, diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/security/tools/KeyTool.java --- a/jdk/src/share/classes/sun/security/tools/KeyTool.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/security/tools/KeyTool.java Wed Mar 30 01:00:23 2011 +0100 @@ -1740,16 +1740,19 @@ KeyStore.TrustedCertificateEntry.class)) { // We have a trusted certificate entry Certificate cert = keyStore.getCertificate(alias); + Object[] source = {"trustedCertEntry"}; + String mf = new MessageFormat( + rb.getString("Entry.type.type.")).format(source) + "\n"; if (verbose && (cert instanceof X509Certificate)) { - out.println(rb.getString("Entry.type.trustedCertEntry.")); + out.println(mf); printX509Cert((X509Certificate)cert, out); } else if (rfc) { - out.println(rb.getString("Entry.type.trustedCertEntry.")); + out.println(mf); dumpCert(cert, out); } else if (debug) { out.println(cert.toString()); } else { - out.println(rb.getString("trustedCertEntry.")); + out.println("trustedCertEntry, "); out.println(rb.getString("Certificate.fingerprint.SHA1.") + getCertFingerPrint("SHA1", cert)); } @@ -1837,10 +1840,6 @@ System.err.println(rb.getString (".The.integrity.of.the.information.stored.in.the.srckeystore.")); System.err.println(rb.getString - (".has.NOT.been.verified.In.order.to.verify.its.integrity.")); - System.err.println(rb.getString - (".you.must.provide.the.srckeystore.password.")); - System.err.println(rb.getString (".WARNING.WARNING.WARNING.")); System.err.println(); } @@ -3187,10 +3186,6 @@ System.err.println(rb.getString (".The.integrity.of.the.information.stored.in.your.keystore.")); System.err.println(rb.getString - (".has.NOT.been.verified.In.order.to.verify.its.integrity.")); - System.err.println(rb.getString - (".you.must.provide.your.keystore.password.")); - System.err.println(rb.getString (".WARNING.WARNING.WARNING.")); System.err.println(); } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/security/util/AuthResources.java --- a/jdk/src/share/classes/sun/security/util/AuthResources.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/security/util/AuthResources.java Wed Mar 30 01:00:23 2011 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2011, 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 @@ -111,17 +111,15 @@ // com.sun.security.auth.PolicyParser {"expected.keystore.type", "expected keystore type"}, - {"can.not.specify.Principal.with.a.", - "can not specify Principal with a "}, - {"wildcard.class.without.a.wildcard.name", - "wildcard class without a wildcard name"}, + {"can.not.specify.Principal.with.a.wildcard.class.without.a.wildcard.name", + "can not specify Principal with a wildcard class without a wildcard name"}, {"expected.codeBase.or.SignedBy", "expected codeBase or SignedBy"}, {"only.Principal.based.grant.entries.permitted", "only Principal-based grant entries permitted"}, {"expected.permission.entry", "expected permission entry"}, {"number.", "number "}, - {"expected.", "expected "}, - {".read.end.of.file", ", read end of file"}, + {"expected.expect.read.end.of.file.", + "expected {0}, read end of file"}, {"expected.read.end.of.file", "expected ';', read end of file"}, {"line.", "line "}, {".expected.", ": expected '"}, @@ -136,6 +134,9 @@ {"SolarisNumericUserPrincipal.", "SolarisNumericUserPrincipal: "}, {"SolarisPrincipal.", "SolarisPrincipal: "}, + // provided.null.name is the NullPointerException message when a + // developer incorrectly passes a null name to the constructor of + // subclasses of java.security.Principal {"provided.null.name", "provided null name"} }; diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/security/util/Resources.java --- a/jdk/src/share/classes/sun/security/util/Resources.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/security/util/Resources.java Wed Mar 30 01:00:23 2011 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2011, 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 @@ -304,8 +304,6 @@ {"Certificate.chain.length.", "Certificate chain length: "}, {"Certificate.i.1.", "Certificate[{0,number,integer}]:"}, {"Certificate.fingerprint.SHA1.", "Certificate fingerprint (SHA1): "}, - {"Entry.type.trustedCertEntry.", "Entry type: trustedCertEntry\n"}, - {"trustedCertEntry.", "trustedCertEntry,"}, {"Keystore.type.", "Keystore type: "}, {"Keystore.provider.", "Keystore provider: "}, {"Your.keystore.contains.keyStore.size.entry", @@ -378,21 +376,15 @@ {"No.certificate.from.the.SSL.server", "No certificate from the SSL server"}, - // Translators of the following 5 pairs, ATTENTION: - // the next 5 string pairs are meant to be combined into 2 paragraphs, - // 1+3+4 and 2+3+5. make sure your translation also does. {".The.integrity.of.the.information.stored.in.your.keystore.", - "* The integrity of the information stored in your keystore *"}, + "* The integrity of the information stored in your keystore *\n" + + "* has NOT been verified! In order to verify its integrity, *\n" + + "* you must provide your keystore password. *"}, {".The.integrity.of.the.information.stored.in.the.srckeystore.", - "* The integrity of the information stored in the srckeystore*"}, - {".has.NOT.been.verified.In.order.to.verify.its.integrity.", - "* has NOT been verified! In order to verify its integrity, *"}, - {".you.must.provide.your.keystore.password.", - "* you must provide your keystore password. *"}, - {".you.must.provide.the.srckeystore.password.", + "* The integrity of the information stored in the srckeystore*\n" + + "* has NOT been verified! In order to verify its integrity, *\n" + "* you must provide the srckeystore password. *"}, - {"Certificate.reply.does.not.contain.public.key.for.alias.", "Certificate reply does not contain public key for <{0}>"}, {"Incomplete.certificate.chain.in.reply", diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/util/logging/LoggingProxy.java --- a/jdk/src/share/classes/sun/util/logging/LoggingProxy.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/util/logging/LoggingProxy.java Wed Mar 30 01:00:23 2011 +0100 @@ -60,4 +60,7 @@ public Object parseLevel(String levelName); public String getLevelName(Object level); + + // return the logging property + public String getProperty(String key); } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/util/logging/LoggingSupport.java --- a/jdk/src/share/classes/sun/util/logging/LoggingSupport.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/util/logging/LoggingSupport.java Wed Mar 30 01:00:23 2011 +0100 @@ -29,6 +29,7 @@ import java.lang.reflect.Field; import java.security.AccessController; import java.security.PrivilegedAction; +import java.util.Date; /** * Internal API to support JRE implementation to detect if the java.util.logging @@ -138,4 +139,42 @@ ensureAvailable(); return proxy.getLevelName(level); } + + private static final String DEFAULT_FORMAT = + "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n"; + + private static final String FORMAT_PROP_KEY = "java.util.logging.SimpleFormatter.format"; + public static String getSimpleFormat() { + return getSimpleFormat(true); + } + + // useProxy if true will cause initialization of + // java.util.logging and read its configuration + static String getSimpleFormat(boolean useProxy) { + String format = + AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + return System.getProperty(FORMAT_PROP_KEY); + } + }); + + if (useProxy && proxy != null && format == null) { + format = proxy.getProperty(FORMAT_PROP_KEY); + } + + if (format != null) { + try { + // validate the user-defined format string + String.format(format, new Date(), "", "", "", "", ""); + } catch (IllegalArgumentException e) { + // illegal syntax; fall back to the default format + format = DEFAULT_FORMAT; + } + } else { + format = DEFAULT_FORMAT; + } + return format; + } + } diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/classes/sun/util/logging/PlatformLogger.java --- a/jdk/src/share/classes/sun/util/logging/PlatformLogger.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/classes/sun/util/logging/PlatformLogger.java Wed Mar 30 01:00:23 2011 +0100 @@ -316,12 +316,6 @@ */ static class LoggerProxy { private static final PrintStream defaultStream = System.err; - private static final String lineSeparator = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - return System.getProperty("line.separator"); - } - }); final String name; volatile int levelValue; @@ -353,14 +347,14 @@ if (level < levelValue || levelValue == OFF) { return; } - defaultStream.println(format(level, msg, null)); + defaultStream.print(format(level, msg, null)); } void doLog(int level, String msg, Throwable thrown) { if (level < levelValue || levelValue == OFF) { return; } - defaultStream.println(format(level, msg, thrown)); + defaultStream.print(format(level, msg, thrown)); } void doLog(int level, String msg, Object... params) { @@ -368,7 +362,7 @@ return; } String newMsg = formatMessage(msg, params); - defaultStream.println(format(level, newMsg, null)); + defaultStream.print(format(level, newMsg, null)); } public boolean isLoggable(int level) { @@ -378,12 +372,6 @@ return true; } - private static final String format = "{0,date} {0,time}"; - - private Object args[] = new Object[1]; - private MessageFormat formatter; - private Date dat; - // Copied from java.util.logging.Formatter.formatMessage private String formatMessage(String format, Object... parameters) { // Do the formatting. @@ -408,37 +396,30 @@ } } + private static final String formatString = + LoggingSupport.getSimpleFormat(false); // don't check logging.properties + + // minimize memory allocation + private Date date = new Date(); private synchronized String format(int level, String msg, Throwable thrown) { - StringBuffer sb = new StringBuffer(); - // Minimize memory allocations here. - if (dat == null) { - dat = new Date(); - formatter = new MessageFormat(format); - } - dat.setTime(System.currentTimeMillis()); - args[0] = dat; - StringBuffer text = new StringBuffer(); - formatter.format(args, text, null); - sb.append(text); - sb.append(" "); - sb.append(getCallerInfo()); - sb.append(lineSeparator); - sb.append(PlatformLogger.getLevelName(level)); - sb.append(": "); - sb.append(msg); + date.setTime(System.currentTimeMillis()); + String throwable = ""; if (thrown != null) { - try { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - thrown.printStackTrace(pw); - pw.close(); - sb.append(sw.toString()); - } catch (Exception ex) { - throw new AssertionError(ex); - } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.println(); + thrown.printStackTrace(pw); + pw.close(); + throwable = sw.toString(); } - return sb.toString(); + return String.format(formatString, + date, + getCallerInfo(), + name, + PlatformLogger.getLevelName(level), + msg, + throwable); } // Returns the caller's class and method's name; best effort diff -r 6679e1339581 -r 799504d1fdcc jdk/src/share/lib/logging.properties --- a/jdk/src/share/lib/logging.properties Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/src/share/lib/logging.properties Wed Mar 30 01:00:23 2011 +0100 @@ -43,6 +43,11 @@ java.util.logging.ConsoleHandler.level = INFO java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +# Example to customize the SimpleFormatter output format +# to print one-line log message like this: +# : [] +# +# java.util.logging.SimpleFormatter.format=%4$s: %5$s [%1$tc]%n ############################################################ # Facility specific properties. diff -r 6679e1339581 -r 799504d1fdcc jdk/test/Makefile --- a/jdk/test/Makefile Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/test/Makefile Wed Mar 30 01:00:23 2011 +0100 @@ -504,7 +504,7 @@ # Stable samevm testruns (minus items from PROBLEM_LIST) JDK_ALL_TARGETS += jdk_nio2 jdk_nio2: $(call TestDirs, java/nio/Buffer java/nio/ByteOrder \ - java/nio/channels java/nio/BufferPoolMXBean java/nio/MappedByteBuffer) + java/nio/channels java/nio/MappedByteBuffer) $(call SharedLibraryPermissions,java/nio/channels) $(call RunSamevmBatch) @@ -687,7 +687,7 @@ ################################################################ -# perftest to collect statistics +# perftest to collect statistics # Expect JPRT to set JPRT_PACKTEST_HOME. PERFTEST_HOME = $(TEST_ROOT)/perf diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/lang/management/BufferPoolMXBean/Basic.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/management/BufferPoolMXBean/Basic.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2007, 2010, 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 6606598 7024172 + * @summary Unit test for java.lang.management.BufferPoolMXBean + * @run main/othervm Basic + */ + +import java.nio.ByteBuffer; +import java.nio.MappedByteBuffer; +import java.nio.file.Path; +import java.nio.file.Files; +import static java.nio.file.StandardOpenOption.*; +import java.nio.channels.FileChannel; +import java.lang.management.BufferPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.lang.ref.WeakReference; +import java.util.*; + +public class Basic { + + // static fields to ensure buffers aren't GC'ed + static List buffers; + static MappedByteBuffer mbb; + + // check counters + static void check(List pools, + int minBufferCount, + long minTotalCapacity) + { + int bufferCount = 0; + long totalCap = 0; + long totalMem = 0; + for (BufferPoolMXBean pool: pools) { + bufferCount += pool.getCount(); + totalCap += pool.getTotalCapacity(); + totalMem += pool.getMemoryUsed(); + } + if (bufferCount < minBufferCount) + throw new RuntimeException("Count less than expected"); + if (totalMem < minTotalCapacity) + throw new RuntimeException("Memory usage less than expected"); + if (totalCap < minTotalCapacity) + throw new RuntimeException("Total capacity less than expected"); + } + + public static void main(String[] args) throws Exception { + Random rand = new Random(); + + // allocate a few direct buffers + int bufferCount = 5 + rand.nextInt(20); + buffers = new ArrayList(bufferCount); + long totalCapacity = 0L; + for (int i=0; i pools = + ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); + check(pools, bufferCount, totalCapacity); + + // use MBeanServer + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + Set mbeans = server.queryNames( + new ObjectName("java.nio:type=BufferPool,*"), null); + pools = new ArrayList(); + for (ObjectName name: mbeans) { + BufferPoolMXBean pool = ManagementFactory + .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class); + pools.add(pool); + } + check(pools, bufferCount, totalCapacity); + + // attempt to unmap mapped buffer + WeakReference ref = new WeakReference<>(mbb); + mbb = null; + do { + System.gc(); + Thread.sleep(250); + } while (ref.get() != null); + } +} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/lang/management/ManagementFactory/GetPlatformMXBeans.java --- a/jdk/test/java/lang/management/ManagementFactory/GetPlatformMXBeans.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/test/java/lang/management/ManagementFactory/GetPlatformMXBeans.java Wed Mar 30 01:00:23 2011 +0100 @@ -23,23 +23,26 @@ /* * @test - * @bug 6610094 - * @summary Basic unit test of ManagementFactory.getPlatformMXBeans() - * and also PlatformManagedObject.getObjectName() + * @bug 6610094 7024172 + * @summary Basic unit test of ManagementFactory.getPlatformMXBean(s) + * methods and PlatformManagedObject.getObjectName() * @author Mandy Chung * * @run main GetPlatformMXBeans */ import java.lang.management.*; -import static java.lang.management.ManagementFactory.*; +import java.io.IOException; import java.util.*; import javax.management.*; +import static java.lang.management.ManagementFactory.*; + public class GetPlatformMXBeans { private static MBeanServer platformMBeanServer = getPlatformMBeanServer(); public static void main(String[] argv) throws Exception { + // singleton platform MXBean checkPlatformMXBean(getClassLoadingMXBean(), ClassLoadingMXBean.class, CLASS_LOADING_MXBEAN_NAME); @@ -58,17 +61,28 @@ checkPlatformMXBean(getThreadMXBean(), ThreadMXBean.class, THREAD_MXBEAN_NAME); + + // the following MXBean can have more than one instances checkGarbageCollectorMXBeans(getGarbageCollectorMXBeans()); checkMemoryManagerMXBeans(getMemoryManagerMXBeans()); checkMemoryPoolMXBeans(getMemoryPoolMXBeans()); + + // check invalid platform MXBean + checkInvalidPlatformMXBean(); } private static - void checkPlatformMXBean(T obj, Class mxbeanInterface, - String mxbeanName) throws Exception + void checkPlatformMXBean(T obj, Class mxbeanInterface, + String mxbeanName) + throws Exception { - int numElements = (obj != null ? 1 : 0); - // verify local list of platform MXBeans + // getPlatformMXBean may return null if the mxbean is not implemented + PlatformManagedObject mxbean = getPlatformMXBean(mxbeanInterface); + if (obj != mxbean) { + throw new RuntimeException("Singleton MXBean returned not matched"); + } + + int numElements = obj == null ? 0 : 1; List mxbeans = getPlatformMXBeans(mxbeanInterface); if (mxbeans.size() != numElements) { @@ -77,24 +91,46 @@ } if (obj != null) { - PlatformManagedObject pmo = mxbeans.get(0); - if (obj != pmo) { + if (obj != mxbeans.get(0)) { throw new RuntimeException("The list returned by getPlatformMXBeans" + " not matched"); } ObjectName on = new ObjectName(mxbeanName); - if (!on.equals(pmo.getObjectName())) { + if (!on.equals(mxbean.getObjectName())) { throw new RuntimeException("Unmatched ObjectName " + - pmo.getObjectName() + " Expected = " + on); + mxbean.getObjectName() + " Expected = " + on); } + checkRemotePlatformMXBean(obj, platformMBeanServer, + mxbeanInterface, mxbeanName); + } + } + + // verify platform MXBeans in the platform MBeanServer + private static + void checkRemotePlatformMXBean(T obj, + MBeanServerConnection mbs, + Class mxbeanInterface, + String mxbeanName) + throws Exception + { + PlatformManagedObject mxbean = getPlatformMXBean(mbs, mxbeanInterface); + if ((obj == null && mxbean != null) || (obj != null && mxbean == null)) { + throw new RuntimeException("Singleton MXBean returned not matched"); } - // verify platform MXBeans in the platform MBeanServer - mxbeans = getPlatformMXBeans(platformMBeanServer, mxbeanInterface); + int numElements = obj == null ? 0 : 1; + List mxbeans = + getPlatformMXBeans(mbs, mxbeanInterface); if (mxbeans.size() != numElements) { throw new RuntimeException("Unmatched number of platform MXBeans " + mxbeans.size() + ". Expected = " + numElements); } + + ObjectName on = new ObjectName(mxbeanName); + if (!on.equals(mxbean.getObjectName())) { + throw new RuntimeException("Unmatched ObjectName " + + mxbean.getObjectName() + " Expected = " + on); + } } private static void checkMemoryManagerMXBeans(List objs) @@ -148,6 +184,14 @@ void checkPlatformMXBeans(List objs, Class mxbeanInterface) throws Exception { + try { + getPlatformMXBean(mxbeanInterface); + // mxbeanInterface is not a singleton + throw new RuntimeException(mxbeanInterface + ": not a singleton MXBean"); + } catch (IllegalArgumentException e) { + // expect IAE + } + // verify local list of platform MXBeans List mxbeans = getPlatformMXBeans(mxbeanInterface); @@ -177,4 +221,40 @@ + mxbeans.size() + ". Expected = " + objs.size()); } } + + interface FakeMXBean extends PlatformManagedObject {}; + + private static void checkInvalidPlatformMXBean() throws IOException { + try { + getPlatformMXBean(FakeMXBean.class); + // mxbeanInterface is not a singleton + throw new RuntimeException("Expect IllegalArgumentException but not thrown"); + } catch (IllegalArgumentException e) { + // expect IAE + } + + try { + getPlatformMXBeans(FakeMXBean.class); + // mxbeanInterface is not a singleton + throw new RuntimeException("Expect IllegalArgumentException but not thrown"); + } catch (IllegalArgumentException e) { + // expect IAE + } + + try { + getPlatformMXBean(platformMBeanServer, FakeMXBean.class); + // mxbeanInterface is not a singleton + throw new RuntimeException("Expect IllegalArgumentException but not thrown"); + } catch (IllegalArgumentException e) { + // expect IAE + } + + try { + getPlatformMXBeans(platformMBeanServer, FakeMXBean.class); + // mxbeanInterface is not a singleton + throw new RuntimeException("Expect IllegalArgumentException but not thrown"); + } catch (IllegalArgumentException e) { + // expect IAE + } + } } diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/management/PlatformLoggingMXBean/LoggingMXBeanTest.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2011, 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 7024172 + * @summary Test if proxy for PlatformLoggingMXBean is equivalent + * to proxy for LoggingMXBean + * + * @build LoggingMXBeanTest + * @run main LoggingMXBeanTest + */ + +import java.lang.management.*; +import javax.management.MBeanServer; +import java.util.logging.*; +import java.util.ArrayList; +import java.util.List; + +public class LoggingMXBeanTest +{ + static String LOGGER_NAME_1 = "com.sun.management.Logger"; + static String LOGGER_NAME_2 = "com.sun.management.Logger.Logger2"; + static String UNKNOWN_LOGGER_NAME = "com.sun.management.Unknown"; + + public static void main(String[] argv) throws Exception { + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + LoggingMXBean proxy = + ManagementFactory.newPlatformMXBeanProxy(mbs, + LogManager.LOGGING_MXBEAN_NAME, + LoggingMXBean.class); + + // test LoggingMXBean proxy + LoggingMXBeanTest p = new LoggingMXBeanTest(proxy); + + // check if the attributes implemented by PlatformLoggingMXBean + // and LoggingMXBean return the same value + PlatformLoggingMXBean mxbean = + ManagementFactory.getPlatformMXBean(mbs, PlatformLoggingMXBean.class); + + checkAttributes(proxy, mxbean); + } + + // same verification as in java/util/logging/LoggingMXBeanTest2 + public LoggingMXBeanTest(LoggingMXBean mbean) throws Exception { + + Logger logger1 = Logger.getLogger( LOGGER_NAME_1 ); + logger1.setLevel(Level.FINE); + Logger logger2 = Logger.getLogger( LOGGER_NAME_2 ); + logger2.setLevel(null); + + /* + * Check for the existence of our new Loggers + */ + System.out.println("Test Logger Name retrieval (getLoggerNames)"); + boolean log1 = false, log2 = false; + List loggers = mbean.getLoggerNames(); + if (loggers == null || loggers.size() < 2) { + throw new RuntimeException( + "Could not Detect the presense of the new Loggers"); + } + + for (String logger : loggers) { + if (logger.equals(LOGGER_NAME_1)) { + log1 = true; + System.out.println(" : Found new Logger : " + logger); + } + if (logger.equals(LOGGER_NAME_2)) { + log2 = true; + System.out.println(" : Found new Logger : " + logger); + } + } + if ( log1 && log2 ) + System.out.println(" : PASSED." ); + else { + System.out.println(" : FAILED. Could not Detect the new Loggers." ); + throw new RuntimeException( + "Could not Detect the presense of the new Loggers"); + } + + System.out.println("Test getLoggerLevel"); + String l1 = mbean.getLoggerLevel(LOGGER_NAME_1); + System.out.println(" : Level for Logger " + LOGGER_NAME_1 + " : " + l1); + if (!l1.equals(Level.FINE.getName())) { + throw new RuntimeException( + "Expected level for " + LOGGER_NAME_1 + " = " + + Level.FINE.getName() + " but got " + l1); + } + String l2 = mbean.getLoggerLevel(LOGGER_NAME_2); + System.out.println(" : Level for Logger " + LOGGER_NAME_2 + " : " + l2); + if (!l2.equals("")) { + throw new RuntimeException( + "Expected level for " + LOGGER_NAME_2 + " = \"\"" + + " but got " + l2); + } + String l3 = mbean.getLoggerLevel(UNKNOWN_LOGGER_NAME); + System.out.println(" : Level for unknown logger : " + l3); + if (l3 != null) { + throw new RuntimeException( + "Expected level for " + UNKNOWN_LOGGER_NAME + " = null" + + " but got " + l3); + } + + System.out.println("Test setLoggerLevel"); + mbean.setLoggerLevel(LOGGER_NAME_1, "INFO"); + System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: INFO"); + Level l = logger1.getLevel(); + if (l != Level.INFO) { + throw new RuntimeException( + "Expected level for " + LOGGER_NAME_1 + " = " + + Level.INFO + " but got " + l); + } + + mbean.setLoggerLevel(LOGGER_NAME_2, "SEVERE"); + System.out.println(" : Set Level for Logger " + LOGGER_NAME_2 + " to: SERVER"); + l = logger2.getLevel(); + if (l != Level.SEVERE) { + throw new RuntimeException( + "Expected level for " + LOGGER_NAME_2 + " = " + + Level.SEVERE+ " but got " + l); + } + + mbean.setLoggerLevel(LOGGER_NAME_1, null); + System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: null"); + l = logger1.getLevel(); + if (l != null) { + throw new RuntimeException( + "Expected level for " + LOGGER_NAME_1 + " = null " + + " but got " + l); + } + + boolean iaeCaught = false; + System.out.println(" : Set Level for unknown Logger to: FINE"); + try { + mbean.setLoggerLevel(UNKNOWN_LOGGER_NAME, "FINE"); + } catch (IllegalArgumentException e) { + // expected + iaeCaught = true; + System.out.println(" : IllegalArgumentException caught as expected"); + } + if (!iaeCaught) { + throw new RuntimeException( + "Expected IllegalArgumentException for setting level for " + + UNKNOWN_LOGGER_NAME + " not thrown"); + } + iaeCaught = false; + System.out.println(" : Set Level for Logger " + LOGGER_NAME_1 + " to: DUMMY"); + try { + mbean.setLoggerLevel(LOGGER_NAME_1, "DUMMY"); + } catch (IllegalArgumentException e) { + // expected + iaeCaught = true; + System.out.println(" : IllegalArgumentException caught as expected"); + } + if (!iaeCaught) { + throw new RuntimeException( + "Expected IllegalArgumentException for invalid level."); + } + + + System.out.println("Test getParentLoggerName"); + String p1 = mbean.getParentLoggerName(LOGGER_NAME_2); + System.out.println(" : Parent Logger for " + LOGGER_NAME_2 + " : " + p1); + if (!p1.equals(LOGGER_NAME_1)) { + throw new RuntimeException( + "Expected parent for " + LOGGER_NAME_2 + " = " + + LOGGER_NAME_1 + " but got " + p1); + } + String p2 = mbean.getParentLoggerName(""); + System.out.println(" : Parent Logger for \"\" : " + p2); + if (!p2.equals("")) { + throw new RuntimeException( + "Expected parent for root logger \"\" = \"\"" + + " but got " + p2); + } + String p3 = mbean.getParentLoggerName(UNKNOWN_LOGGER_NAME); + System.out.println(" : Parent Logger for unknown logger : " + p3); + if (p3 != null) { + throw new RuntimeException( + "Expected level for " + UNKNOWN_LOGGER_NAME + " = null" + + " but got " + p3); + } + } + + private static void checkAttributes(LoggingMXBean mxbean1, + PlatformLoggingMXBean mxbean2) { + // verify logger names + List loggers1 = mxbean1.getLoggerNames(); + List loggers2 = mxbean2.getLoggerNames(); + if (loggers1.size() != loggers2.size()) + throw new RuntimeException("LoggerNames: unmatched number of entries"); + List loggers3 = new ArrayList<>(loggers1); + loggers3.removeAll(loggers2); + if (loggers3.size() != 0) + throw new RuntimeException("LoggerNames: unmatched loggers"); + + // verify logger's level and parent + for (String logger : loggers1) { + if (!mxbean1.getLoggerLevel(logger) + .equals(mxbean2.getLoggerLevel(logger))) + throw new RuntimeException( + "LoggerLevel: unmatched level for " + logger); + if (!mxbean1.getParentLoggerName(logger) + .equals(mxbean2.getParentLoggerName(logger))) + throw new RuntimeException( + "ParentLoggerName: unmatched parent logger's name for " + logger); + } + } +} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/lang/management/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/management/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6876135 7024172 + * + * @summary Test PlatformLoggingMXBean + * This test performs similar testing as + * java/util/logging/LoggingMXBeanTest. + * + * @build PlatformLoggingMXBeanTest + * @run main PlatformLoggingMXBeanTest + */ + +import javax.management.*; +import java.lang.management.ManagementFactory; +import java.lang.management.PlatformLoggingMXBean; +import java.util.logging.*; +import java.util.List; + +public class PlatformLoggingMXBeanTest +{ + + ObjectName objectName = null; + static String LOGGER_NAME_1 = "com.sun.management.Logger1"; + static String LOGGER_NAME_2 = "com.sun.management.Logger2"; + + public PlatformLoggingMXBeanTest() throws Exception { + } + + private void runTest(PlatformLoggingMXBean mBean) throws Exception { + + /* + * Create the MBeanServeri, register the PlatformLoggingMXBean + */ + System.out.println( "***************************************************" ); + System.out.println( "********** PlatformLoggingMXBean Unit Test **********" ); + System.out.println( "***************************************************" ); + System.out.println( "" ); + System.out.println( "*******************************" ); + System.out.println( "*********** Phase 1 ***********" ); + System.out.println( "*******************************" ); + System.out.println( " Creating MBeanServer " ); + System.out.print( " Register PlatformLoggingMXBean: " ); + MBeanServer mbs = MBeanServerFactory.createMBeanServer(); + String[] list = new String[0]; + + try { + objectName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME); + mbs.registerMBean( mBean, objectName ); + } + catch ( Exception e ) { + System.out.println( "FAILED" ); + throw e; + } + System.out.println( "PASSED" ); + System.out.println(""); + + /* + * Access our MBean to get the current list of Loggers + */ + System.out.println( "*******************************" ); + System.out.println( "*********** Phase 2 ***********" ); + System.out.println( "*******************************" ); + System.out.println( " Test Logger Name retrieval (getLoggerNames) " ); + // check that Level object are returned properly + try { + list = (String[]) mbs.getAttribute( objectName, "LoggerNames" ); + } + catch ( Exception e ) { + System.out.println(" : FAILED" ); + throw e; + } + + /* + * Dump the list of Loggers already present, if any + */ + Object[] params = new Object[1]; + String[] signature = new String[1]; + Level l; + + if ( list == null ) { + System.out.println(" : PASSED. No Standard Loggers Present" ); + System.out.println(""); + } + else { + System.out.println(" : PASSED. There are " + list.length + " Loggers Present" ); + System.out.println(""); + System.out.println( "*******************************" ); + System.out.println( "*********** Phase 2B **********" ); + System.out.println( "*******************************" ); + System.out.println( " Examine Existing Loggers" ); + for ( int i = 0; i < list.length; i++ ) { + try { + params[0] = list[i]; + signature[0] = "java.lang.String"; + String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); + System.out.println(" : Logger #" + i + " = " + list[i] ); + System.out.println(" : Level = " + levelName ); + } + catch ( Exception e ) { + System.out.println(" : FAILED" ); + throw e; + } + } + System.out.println(" : PASSED" ); + } + + /* + * Create two new loggers to the list of Loggers already present + */ + System.out.println(""); + System.out.println( "*******************************" ); + System.out.println( "*********** Phase 3 ***********" ); + System.out.println( "*******************************" ); + System.out.println( " Create and test new Loggers" ); + Logger logger1 = Logger.getLogger( LOGGER_NAME_1 ); + Logger logger2 = Logger.getLogger( LOGGER_NAME_2 ); + + // check that Level object are returned properly + try { + list = (String[]) mbs.getAttribute( objectName, "LoggerNames" ); + } + catch ( Exception e ) { + System.out.println(" : FAILED" ); + throw e; + } + + /* + * Check for the existence of our new Loggers + */ + boolean log1 = false, log2 = false; + + if ( list == null || list.length < 2 ) { + System.out.println(" : FAILED. Could not Detect the presense of the new Loggers" ); + throw new RuntimeException( + "Could not Detect the presense of the new Loggers"); + } + else { + for ( int i = 0; i < list.length; i++ ) { + if ( list[i].equals( LOGGER_NAME_1 ) ) { + log1 = true; + System.out.println( " : Found new Logger : " + list[i] ); + } + if ( list[i].equals( LOGGER_NAME_2 ) ) { + log2 = true; + System.out.println( " : Found new Logger : " + list[i] ); + } + } + if ( log1 && log2 ) + System.out.println( " : PASSED." ); + else { + System.out.println( " : FAILED. Could not Detect the new Loggers." ); + throw new RuntimeException( + "Could not Detect the presense of the new Loggers"); + } + } + + /* + * Set a new Logging levels and check that it succeeded + */ + System.out.println(""); + System.out.println( "*******************************" ); + System.out.println( "*********** Phase 4 ***********" ); + System.out.println( "*******************************" ); + System.out.println( " Set and Check the Logger Level" ); + log1 = false; + log2 = false; + try { + // Set the level of logger1 to ALL + params = new Object[2]; + signature = new String[2]; + params[0] = LOGGER_NAME_1; + params[1] = Level.ALL.getName(); + signature[0] = "java.lang.String"; + signature[1] = "java.lang.String"; + mbs.invoke( objectName, "setLoggerLevel", params, signature ); + + // Set the level of logger2 to FINER + params[0] = LOGGER_NAME_2; + params[1] = Level.FINER.getName(); + mbs.invoke( objectName, "setLoggerLevel", params, signature ); + + // Okay read back the Level from Logger1. Should be ALL + params = new Object[1]; + signature = new String[1]; + params[0] = LOGGER_NAME_1; + signature[0] = "java.lang.String"; + String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); + l = Level.parse(levelName); + System.out.print(" Logger1: " ); + if ( l.equals( l.ALL ) ) { + System.out.println("Level Set to ALL: PASSED" ); + log1 = true; + } + else { + System.out.println("Level Set to ALL: FAILED" ); + throw new RuntimeException( + "Level Set to ALL but returned " + l.toString()); + } + + // Okay read back the Level from Logger2. Should be FINER + params = new Object[1]; + signature = new String[1]; + params[0] = LOGGER_NAME_2; + signature[0] = "java.lang.String"; + levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); + l = Level.parse(levelName); + System.out.print(" Logger2: " ); + if ( l.equals( l.FINER ) ) { + System.out.println("Level Set to FINER: PASSED" ); + log2 = true; + } + else { + System.out.println("Level Set to FINER: FAILED" ); + throw new RuntimeException( + "Level Set to FINER but returned " + l.toString()); + } + } + catch ( Exception e ) { + throw e; + } + + System.out.println( "" ); + System.out.println( "***************************************************" ); + System.out.println( "***************** All Tests Passed ****************" ); + System.out.println( "***************************************************" ); + } + + public static void main(String[] argv) throws Exception { + PlatformLoggingMXBean mbean = + ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class); + ObjectName objname = mbean.getObjectName(); + if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) { + throw new RuntimeException("Invalid ObjectName " + objname); + } + + // check if the PlatformLoggingMXBean is registered in the platform MBeanServer + MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer(); + ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME); + + // We could call mbs.isRegistered(objName) here. + // Calling getMBeanInfo will throw exception if not found. + platformMBS.getMBeanInfo(objName); + + if (!platformMBS.isInstanceOf(objName, "java.lang.management.PlatformLoggingMXBean") || + !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) { + throw new RuntimeException(objName + " is of unexpected type"); + } + + // test if PlatformLoggingMXBean works properly in a MBeanServer + PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest(); + test.runTest(mbean); + } +} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/nio/BufferPoolMXBean/Basic.java --- a/jdk/test/java/nio/BufferPoolMXBean/Basic.java Wed Mar 30 00:59:07 2011 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2007, 2010, 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 6606598 - * @summary Unit test for java.nio.BufferPoolMXBean - * @run main/othervm Basic - */ - -import java.nio.ByteBuffer; -import java.nio.MappedByteBuffer; -import java.nio.BufferPoolMXBean; -import java.nio.channels.FileChannel; -import java.io.File; -import java.io.RandomAccessFile; -import java.lang.management.ManagementFactory; -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.util.*; - -public class Basic { - - // static fields to ensure buffers aren't GC'ed - static List buffers; - static MappedByteBuffer mbb; - - // check counters - static void check(List pools, - int minBufferCount, - long minTotalCapacity) - { - int bufferCount = 0; - long totalCap = 0; - long totalMem = 0; - for (BufferPoolMXBean pool: pools) { - bufferCount += pool.getCount(); - totalCap += pool.getTotalCapacity(); - totalMem += pool.getMemoryUsed(); - } - if (bufferCount < minBufferCount) - throw new RuntimeException("Count less than expected"); - if (totalMem < minTotalCapacity) - throw new RuntimeException("Memory usage less than expected"); - if (totalCap < minTotalCapacity) - throw new RuntimeException("Total capacity less than expected"); - } - - public static void main(String[] args) throws Exception { - Random rand = new Random(); - - // allocate a few direct buffers - int bufferCount = 5 + rand.nextInt(20); - buffers = new ArrayList(bufferCount); - long totalCapacity = 0L; - for (int i=0; i pools = - ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class); - check(pools, bufferCount, totalCapacity); - - // using MBeanServer - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - Set mbeans = server.queryNames( - new ObjectName("java.nio:type=BufferPool,*"), null); - pools = new ArrayList(); - for (ObjectName name: mbeans) { - BufferPoolMXBean pool = ManagementFactory - .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class); - pools.add(pool); - } - check(pools, bufferCount, totalCapacity); - } -} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java --- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Leaky.java Wed Mar 30 01:00:23 2011 +0100 @@ -28,12 +28,12 @@ */ import java.nio.ByteBuffer; -import java.nio.BufferPoolMXBean; import java.nio.channels.*; import java.net.*; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; +import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; /** diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/util/logging/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java --- a/jdk/test/java/util/logging/PlatformLoggingMXBean/PlatformLoggingMXBeanTest.java Wed Mar 30 00:59:07 2011 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 6876135 - * - * @summary Test PlatformLoggingMXBean - * This test performs similar testing as LoggingMXBeanTest. - * - * @build PlatformLoggingMXBeanTest - * @run main PlatformLoggingMXBeanTest - */ - -import javax.management.*; -import java.lang.management.ManagementFactory; -import java.util.logging.*; -import java.util.List; - -public class PlatformLoggingMXBeanTest -{ - - ObjectName objectName = null; - static String LOGGER_NAME_1 = "com.sun.management.Logger1"; - static String LOGGER_NAME_2 = "com.sun.management.Logger2"; - - public PlatformLoggingMXBeanTest() throws Exception { - } - - private void runTest(PlatformLoggingMXBean mBean) throws Exception { - - /* - * Create the MBeanServeri, register the PlatformLoggingMXBean - */ - System.out.println( "***************************************************" ); - System.out.println( "********** PlatformLoggingMXBean Unit Test **********" ); - System.out.println( "***************************************************" ); - System.out.println( "" ); - System.out.println( "*******************************" ); - System.out.println( "*********** Phase 1 ***********" ); - System.out.println( "*******************************" ); - System.out.println( " Creating MBeanServer " ); - System.out.print( " Register PlatformLoggingMXBean: " ); - MBeanServer mbs = MBeanServerFactory.createMBeanServer(); - String[] list = new String[0]; - - try { - objectName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME); - mbs.registerMBean( mBean, objectName ); - } - catch ( Exception e ) { - System.out.println( "FAILED" ); - throw e; - } - System.out.println( "PASSED" ); - System.out.println(""); - - /* - * Access our MBean to get the current list of Loggers - */ - System.out.println( "*******************************" ); - System.out.println( "*********** Phase 2 ***********" ); - System.out.println( "*******************************" ); - System.out.println( " Test Logger Name retrieval (getLoggerNames) " ); - // check that Level object are returned properly - try { - list = (String[]) mbs.getAttribute( objectName, "LoggerNames" ); - } - catch ( Exception e ) { - System.out.println(" : FAILED" ); - throw e; - } - - /* - * Dump the list of Loggers already present, if any - */ - Object[] params = new Object[1]; - String[] signature = new String[1]; - Level l; - - if ( list == null ) { - System.out.println(" : PASSED. No Standard Loggers Present" ); - System.out.println(""); - } - else { - System.out.println(" : PASSED. There are " + list.length + " Loggers Present" ); - System.out.println(""); - System.out.println( "*******************************" ); - System.out.println( "*********** Phase 2B **********" ); - System.out.println( "*******************************" ); - System.out.println( " Examine Existing Loggers" ); - for ( int i = 0; i < list.length; i++ ) { - try { - params[0] = list[i]; - signature[0] = "java.lang.String"; - String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); - System.out.println(" : Logger #" + i + " = " + list[i] ); - System.out.println(" : Level = " + levelName ); - } - catch ( Exception e ) { - System.out.println(" : FAILED" ); - throw e; - } - } - System.out.println(" : PASSED" ); - } - - /* - * Create two new loggers to the list of Loggers already present - */ - System.out.println(""); - System.out.println( "*******************************" ); - System.out.println( "*********** Phase 3 ***********" ); - System.out.println( "*******************************" ); - System.out.println( " Create and test new Loggers" ); - Logger logger1 = Logger.getLogger( LOGGER_NAME_1 ); - Logger logger2 = Logger.getLogger( LOGGER_NAME_2 ); - - // check that Level object are returned properly - try { - list = (String[]) mbs.getAttribute( objectName, "LoggerNames" ); - } - catch ( Exception e ) { - System.out.println(" : FAILED" ); - throw e; - } - - /* - * Check for the existence of our new Loggers - */ - boolean log1 = false, log2 = false; - - if ( list == null || list.length < 2 ) { - System.out.println(" : FAILED. Could not Detect the presense of the new Loggers" ); - throw new RuntimeException( - "Could not Detect the presense of the new Loggers"); - } - else { - for ( int i = 0; i < list.length; i++ ) { - if ( list[i].equals( LOGGER_NAME_1 ) ) { - log1 = true; - System.out.println( " : Found new Logger : " + list[i] ); - } - if ( list[i].equals( LOGGER_NAME_2 ) ) { - log2 = true; - System.out.println( " : Found new Logger : " + list[i] ); - } - } - if ( log1 && log2 ) - System.out.println( " : PASSED." ); - else { - System.out.println( " : FAILED. Could not Detect the new Loggers." ); - throw new RuntimeException( - "Could not Detect the presense of the new Loggers"); - } - } - - /* - * Set a new Logging levels and check that it succeeded - */ - System.out.println(""); - System.out.println( "*******************************" ); - System.out.println( "*********** Phase 4 ***********" ); - System.out.println( "*******************************" ); - System.out.println( " Set and Check the Logger Level" ); - log1 = false; - log2 = false; - try { - // Set the level of logger1 to ALL - params = new Object[2]; - signature = new String[2]; - params[0] = LOGGER_NAME_1; - params[1] = Level.ALL.getName(); - signature[0] = "java.lang.String"; - signature[1] = "java.lang.String"; - mbs.invoke( objectName, "setLoggerLevel", params, signature ); - - // Set the level of logger2 to FINER - params[0] = LOGGER_NAME_2; - params[1] = Level.FINER.getName(); - mbs.invoke( objectName, "setLoggerLevel", params, signature ); - - // Okay read back the Level from Logger1. Should be ALL - params = new Object[1]; - signature = new String[1]; - params[0] = LOGGER_NAME_1; - signature[0] = "java.lang.String"; - String levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); - l = Level.parse(levelName); - System.out.print(" Logger1: " ); - if ( l.equals( l.ALL ) ) { - System.out.println("Level Set to ALL: PASSED" ); - log1 = true; - } - else { - System.out.println("Level Set to ALL: FAILED" ); - throw new RuntimeException( - "Level Set to ALL but returned " + l.toString()); - } - - // Okay read back the Level from Logger2. Should be FINER - params = new Object[1]; - signature = new String[1]; - params[0] = LOGGER_NAME_2; - signature[0] = "java.lang.String"; - levelName = (String) mbs.invoke( objectName, "getLoggerLevel", params, signature ); - l = Level.parse(levelName); - System.out.print(" Logger2: " ); - if ( l.equals( l.FINER ) ) { - System.out.println("Level Set to FINER: PASSED" ); - log2 = true; - } - else { - System.out.println("Level Set to FINER: FAILED" ); - throw new RuntimeException( - "Level Set to FINER but returned " + l.toString()); - } - } - catch ( Exception e ) { - throw e; - } - - System.out.println( "" ); - System.out.println( "***************************************************" ); - System.out.println( "***************** All Tests Passed ****************" ); - System.out.println( "***************************************************" ); - } - - public static void main(String[] argv) throws Exception { - List result = - ManagementFactory.getPlatformMXBeans(PlatformLoggingMXBean.class); - if (result.size() != 1) { - throw new RuntimeException("Unexpected number of PlatformLoggingMXBean instances: " + - result.size()); - } - - PlatformLoggingMXBean mbean = result.get(0); - ObjectName objname = mbean.getObjectName(); - if (!objname.equals(new ObjectName(LogManager.LOGGING_MXBEAN_NAME))) { - throw new RuntimeException("Invalid ObjectName " + objname); - } - - // check if the PlatformLoggingMXBean is registered in the platform MBeanServer - MBeanServer platformMBS = ManagementFactory.getPlatformMBeanServer(); - ObjectName objName = new ObjectName(LogManager.LOGGING_MXBEAN_NAME); - // We could call mbs.isRegistered(objName) here. - // Calling getMBeanInfo will throw exception if not found. - platformMBS.getMBeanInfo(objName); - - if (!platformMBS.isInstanceOf(objName, "java.util.logging.PlatformLoggingMXBean") || - !platformMBS.isInstanceOf(objName, "java.util.logging.LoggingMXBean")) { - throw new RuntimeException(objName + " is of unexpected type"); - } - - // test if PlatformLoggingMXBean works properly in a MBeanServer - PlatformLoggingMXBeanTest test = new PlatformLoggingMXBeanTest(); - test.runTest(mbean); - } -} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/java/util/logging/SimpleFormatterFormat.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/util/logging/SimpleFormatterFormat.java Wed Mar 30 01:00:23 2011 +0100 @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2011, 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 6381464 + * @summary Test the custom simple formatter output + * + * @run main/othervm SimpleFormatterFormat + */ + +import java.io.*; +import java.util.logging.*; +import java.util.regex.*; + +public class SimpleFormatterFormat { + private static final String key = "java.util.logging.SimpleFormatter.format"; + private static final String origFormat = System.getProperty(key); + private static final PrintStream err = System.err; + public static void main(String[] args) throws Exception { + try { + File dir = new File(System.getProperty("user.dir", ".")); + File log = new File(dir, "simpleformat.txt"); + java.nio.file.Files.deleteIfExists(log.toPath()); + PrintStream logps = new PrintStream(log); + System.setProperty(key, "%3$s:%4$s: %5$s [%1$tc] source: %2$s%6$s%n"); + writeLogRecords(logps); + checkLogRecords(log); + } finally { + if (origFormat == null) { + System.clearProperty(key); + } else { + System.setProperty(key, origFormat); + } + System.setErr(err); + } + } + + private static String[] loggers = new String[] { + "test.foo", + "test.foo", + "test.bar", + "test.bar" + }; + private static String[] messages = new String[] { + "severe hello world", + "warning lost connection", + "info welcome", + "warning exception thrown", + }; + private static void writeLogRecords(PrintStream logps) throws Exception { + try { + System.setErr(logps); + + Logger foo = Logger.getLogger("test.foo"); + foo.log(Level.SEVERE, "{0} {1} {2}", new Object[] {"severe", "hello", "world"}); + foo.warning(messages[1]); + + Logger bar = Logger.getLogger("test.bar"); + bar.finest("Dummy message"); + bar.info(messages[2]); + bar.log(Level.WARNING, messages[3], new IllegalArgumentException()); + + } finally { + logps.flush(); + logps.close(); + System.setErr(err); + } + } + + private static void checkLogRecords(File log) throws Exception { + System.out.println("Checking log records in file: " + log); + Pattern p = Pattern.compile("([\\.a-zA-Z:]+) (.*) \\[.*\\] source: (.*)"); + + try (FileInputStream in = new FileInputStream(log)) { + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + String line; + int i = 0; + while (i < messages.length && + (line = reader.readLine()) != null) { + String expectedLogger = loggers[i]; + String expectedMsg = messages[i]; + i++; + + line = line.trim(); + System.out.println(line); + + Matcher m = p.matcher(line); + if (!m.matches()) { + throw new RuntimeException("Unexpected output format"); + } + if (m.groupCount() != 3) { + throw new RuntimeException("Unexpected group count = " + + m.groupCount()); + } + // verify logger name and level + String[] ss = m.group(1).split(":"); + int len = ss.length; + if (len != 2) { + throw new RuntimeException("Unexpected logger name and level" + + m.group(1)); + } + + verify(expectedLogger, expectedMsg, ss[0], ss[1], m.group(2), m.group(3)); + } + + // expect IllegalArgumentException following it + line = reader.readLine().trim(); + if (!line.equals("java.lang.IllegalArgumentException")) { + throw new RuntimeException("Invalid line: " + line); + } + } + } + + private static void verify(String expectedLogger, String expectedMsg, + String logger, String level, + String msg, String source) { + if (!logger.equals(expectedLogger)) { + throw new RuntimeException("Unexpected logger: " + logger); + } + if (!msg.equals(expectedMsg)) { + throw new RuntimeException("Unexpected message: " + msg); + } + + String[] ss = expectedMsg.split("\\s+"); + String expectedLevel = ss[0].toUpperCase(); + if (!level.equals(expectedLevel)) { + throw new RuntimeException("Unexpected level: " + level); + } + + ss = source.split("\\s+"); + int len = ss.length; + if (!(len == 2 && + ss[0].equals("SimpleFormatterFormat") && + ss[1].equals("writeLogRecords"))) { + throw new RuntimeException("Unexpected source: " + source); + } + } +} diff -r 6679e1339581 -r 799504d1fdcc jdk/test/sun/util/logging/PlatformLoggerTest.java --- a/jdk/test/sun/util/logging/PlatformLoggerTest.java Wed Mar 30 00:59:07 2011 +0100 +++ b/jdk/test/sun/util/logging/PlatformLoggerTest.java Wed Mar 30 01:00:23 2011 +0100 @@ -26,10 +26,11 @@ * @bug 6882376 6985460 * @summary Test if java.util.logging.Logger is created before and after * logging is enabled. Also validate some basic PlatformLogger - * operations. + * operations. othervm mode to make sure java.util.logging + * is not initialized. * * @compile -XDignore.symbol.file PlatformLoggerTest.java - * @run main PlatformLoggerTest + * @run main/othervm PlatformLoggerTest */ import java.util.logging.*;