diff --git a/nucleus/common/amx-core/src/main/java/fish/payara/admin/amx/AMXBootService.java b/nucleus/common/amx-core/src/main/java/fish/payara/admin/amx/AMXBootService.java index 2ec41018018..178fac07277 100644 --- a/nucleus/common/amx-core/src/main/java/fish/payara/admin/amx/AMXBootService.java +++ b/nucleus/common/amx-core/src/main/java/fish/payara/admin/amx/AMXBootService.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright (c) [2018] Payara Foundation and/or its affiliates. All rights reserved. + * Copyright (c) [2018-2019] Payara Foundation and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development @@ -45,7 +45,6 @@ import fish.payara.admin.amx.config.AMXConfiguration; import java.beans.PropertyChangeEvent; -import java.util.Collections; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.glassfish.admin.mbeanserver.BootAMX; @@ -58,8 +57,8 @@ import org.jvnet.hk2.config.UnprocessedChangeEvents; /** - * - * @author jonathan + * Service to boot AMX if it is enabled + * @author jonathan coustick * @since 4.1.2.172 */ @Service(name="amx-boot-service") @@ -73,7 +72,6 @@ public class AMXBootService implements ConfigListener { ServiceLocator habitat; private boolean enabled; - private BootAMX bootAMX; @PostConstruct public void postConstruct(){ @@ -85,7 +83,7 @@ public void postConstruct(){ } private void startup(){ - bootAMX = habitat.getService(BootAMX.class); + BootAMX bootAMX = habitat.getService(BootAMX.class); bootAMX.bootAMX(); } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ChildGetter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ChildGetter.java index bafddc7e48a..4b79e73af6e 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ChildGetter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ChildGetter.java @@ -84,10 +84,3 @@ where the interface FooBar is a sub-interface of {@link org.glassfish.admin.amx. /** child type, derived automatically by default for the normal naming pattern */ String type() default ""; } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Description.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Description.java index f69344d172d..f141e67dea4 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Description.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Description.java @@ -58,10 +58,3 @@ public @interface Description { public String value() default ""; } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedAttribute.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedAttribute.java index 09df1aa7364..efc156888c8 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedAttribute.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedAttribute.java @@ -59,10 +59,3 @@ @Taxonomy(stability = Stability.NOT_AN_INTERFACE) public @interface ManagedAttribute { } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedOperation.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedOperation.java index 5a2a23563ee..d666d539947 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedOperation.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/ManagedOperation.java @@ -60,9 +60,4 @@ @Taxonomy(stability = Stability.NOT_AN_INTERFACE) public @interface ManagedOperation { public int impact() default MBeanOperationInfo.UNKNOWN; -} - - - - - +} \ No newline at end of file diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Param.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Param.java index 3b1e6d2eb5d..312d77812a6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Param.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/Param.java @@ -63,10 +63,3 @@ /** true if null may be passed */ public boolean optional() default false; } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/package-info.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/package-info.java index e0368acb4a6..b04f79df3fa 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/package-info.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/annotation/package-info.java @@ -42,7 +42,4 @@ package org.glassfish.admin.amx.annotation; import org.glassfish.external.arc.Taxonomy; -import org.glassfish.external.arc.Stability; - - - +import org.glassfish.external.arc.Stability; \ No newline at end of file diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/BulkAccess.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/BulkAccess.java index 31014d65715..a6ca6ad48ea 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/BulkAccess.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/BulkAccess.java @@ -174,5 +174,3 @@ public Object[] bulkInvoke(final ObjectName[] objectNames, final Object[] args, final String[] types); } - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/DomainRoot.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/DomainRoot.java index ba622b70c9b..ac1f119363e 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/DomainRoot.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/DomainRoot.java @@ -273,17 +273,3 @@ to DomainConfig using getDomain().as(DomainConfig.class). @Description("Return a Map of all non-compliant MBeans (MBeans might no longer be registered). The List<String> contains all issues with that MBean") public Map> getComplianceFailures(); } - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Ext.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Ext.java index 3e684757960..5278d7ca146 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Ext.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Ext.java @@ -59,20 +59,3 @@ public interface Ext extends AMXProxy, Singleton, Utility public Realms getRealms(); } - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTracker.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTracker.java index 9961413bb24..9e62a2baf64 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTracker.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTracker.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.base; import java.util.Collections; @@ -44,7 +46,10 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.management.*; +import org.glassfish.admin.amx.util.AMXLoggerInfo; import org.glassfish.admin.amx.core.AMXMBeanMetadata; import org.glassfish.admin.amx.core.Util; import org.glassfish.admin.amx.util.jmx.JMXUtil; @@ -53,17 +58,16 @@ import org.glassfish.external.arc.Taxonomy; /** - * Tracks the entire MBean parent/child hierarachy so that individual MBeans + * Tracks the entire MBean parent/child hierarchy so that individual MBeans * need not do so. Can supply parents and children of any MBean, used by all AMX * implementations. */ @Taxonomy(stability = Stability.NOT_AN_INTERFACE) @AMXMBeanMetadata(singleton = true, globalSingleton = true, leaf = true) public final class MBeanTracker implements NotificationListener, MBeanRegistration, MBeanTrackerMBean { + + private static final Logger LOGGER = AMXLoggerInfo.getLogger(); - private static void debug(final Object o) { - System.out.println("" + o); - } /** * maps a parent ObjectName to a Set of children */ @@ -112,12 +116,12 @@ public void handleNotification(final Notification notifIn, final Object handback // first and there's nothing we could do about it. if (type.equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) { if (mEmitMBeanStatus) { - System.out.println("AMX MBean registered: " + objectName); + LOGGER.log(Level.INFO, "AMX MBean registered: {0}", objectName); } addChild(objectName); } else if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) { if (mEmitMBeanStatus) { - System.out.println("AMX MBean UNregistered: " + objectName); + LOGGER.log(Level.INFO, "AMX MBean UNregistered: {0}", objectName); } removeChild(objectName); } @@ -140,18 +144,16 @@ public final void postRegister(final Boolean registrationSucceeded) { if (mServer == null) { return; } - if (registrationSucceeded.booleanValue()) { + if (registrationSucceeded) { try { mServer.addNotificationListener(JMXUtil.getMBeanServerDelegateObjectName(), this, null, null); } catch (Exception e) { throw new RuntimeException("Could not register with MBeanServerDelegate", e); } - //debug( "MBeanTracker: registered as " + mObjectName ); } // populate our list final ObjectName pattern = Util.newObjectNamePattern(mDomain, ""); final Set names = JMXUtil.queryNames(mServer, pattern, null); - //debug( "MBeanTracker: found MBeans: " + names.size() ); for (final ObjectName o : names) { addChild(o); } @@ -166,6 +168,7 @@ public final void preDeregister() throws Exception { @Override public final void postDeregister() { + //nothing needed here, see preDeregister } private boolean isRelevantMBean(final ObjectName child) { @@ -181,7 +184,7 @@ private void addChild(final ObjectName child) { parent = (ObjectName) mServer.getAttribute(child, AMX.ATTR_PARENT); } catch (final Exception e) { // nothing to be done, MBean gone missing, badly implemented, etc. - //System.out.println( "No Parent for: " + child ); + LOGGER.log(Level.FINE, "No Parent for: {0}", child); } if (parent != null) { @@ -193,7 +196,6 @@ private void addChild(final ObjectName child) { mParentChildren.put(parent, children); } children.add(child); - //debug( "MBeanTracker: ADDED " + child + " with parent " + parent ); } } } @@ -209,7 +211,6 @@ private synchronized ObjectName removeChild(final ObjectName child) { children.remove(child); if (children.isEmpty()) { mParentChildren.remove(parent); - //debug( "MBeanTracker: REMOVED " + child + " from parent " + parent ); } } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTrackerMBean.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTrackerMBean.java index b63594e2a90..ff15e308d53 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTrackerMBean.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/MBeanTrackerMBean.java @@ -74,14 +74,3 @@ public interface MBeanTrackerMBean @ManagedAttribute public void setEmitMBeanStatus(boolean emit); } - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Pathnames.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Pathnames.java index 2291d2d7269..29be8d5d8b1 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Pathnames.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Pathnames.java @@ -104,10 +104,3 @@ Resolves the path to an ObjectName, then calls ancestors(objectName). @ManagedOperation(impact=MBeanOperationInfo.INFO) public String[] dump( final String path ); } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Query.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Query.java index 1cedab3d225..795e187322d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Query.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Query.java @@ -144,9 +144,3 @@ have a different Parent (uniqueness invariant within any parent). @ManagedOperation(impact = MBeanOperationInfo.INFO) public AMXProxy[] queryDescendants( @Param(name="parentObjectName") ObjectName parentObjectName); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Realms.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Realms.java index ea300a0ed88..68ed11a8c73 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Realms.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Realms.java @@ -95,13 +95,3 @@ public interface Realms extends AMXProxy, Utility, Singleton @ManagedAttribute public String getAnonymousUser(); } - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/RuntimeRoot.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/RuntimeRoot.java index a8872bb09d9..d6a0432173d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/RuntimeRoot.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/RuntimeRoot.java @@ -156,13 +156,3 @@ public String getContextRoot( @Description("Whether the server was started with --debug") public boolean isStartedInDebugMode(); } - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Sample.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Sample.java index 17678cc0071..6f28bd4658b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Sample.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Sample.java @@ -113,13 +113,3 @@ The type of Notification emitted by emitNotification(). @ManagedAttribute public Object[] getAllSortsOfStuff(); } - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Singleton.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Singleton.java index b3e61915ac2..30d93a3af1a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Singleton.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Singleton.java @@ -51,5 +51,3 @@ public interface Singleton extends AMXProxy { } - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java index 7a1a8631acd..2190894fb7b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java @@ -128,5 +128,3 @@ high availability feature (HADB) is available. public Map getPerformanceMillis(); } - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Tools.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Tools.java index 277fb09dfef..a303d9ac7d7 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Tools.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/Tools.java @@ -129,19 +129,3 @@ public String validate( public String getHierarchy(); } - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/UnprocessedConfigChange.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/UnprocessedConfigChange.java index 9b5bba6512c..27d6581ec69 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/UnprocessedConfigChange.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/UnprocessedConfigChange.java @@ -185,30 +185,3 @@ public int hashCode() } } - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/package-info.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/package-info.java index 30473a3f68d..f518d80cb07 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/package-info.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/package-info.java @@ -43,6 +43,3 @@ import org.glassfish.external.arc.Taxonomy; import org.glassfish.external.arc.Stability; - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigConstants.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigConstants.java index 52b9d7a7324..85a470f5dcc 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigConstants.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigConstants.java @@ -126,11 +126,3 @@ private AMXConfigConstants() public static final String AMX_CONFIG_READY_FEATURE = "AMXConfigReady"; } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigProxy.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigProxy.java index 2a4a6af38be..592baf085af 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigProxy.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AMXConfigProxy.java @@ -169,10 +169,3 @@ public AttributeList setAttributesTransactionally( @Param(name = "attrs") Attrib throws Exception; } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java index c9e42059cf1..05f05f57ab5 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java @@ -110,10 +110,3 @@ Calls getAttributes(), then returns all resolved values. If the attributes public AttributeList resolveAttributes(@Param(name = "attributeNames") String[] attributeNames); } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/package-info.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/package-info.java index 67f6e92f5ae..3091256e0c7 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/package-info.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/package-info.java @@ -46,7 +46,4 @@ package org.glassfish.admin.amx.config; import org.glassfish.external.arc.Taxonomy; -import org.glassfish.external.arc.Stability; - - - +import org.glassfish.external.arc.Stability; \ No newline at end of file diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXProxy.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXProxy.java index e1848f6055c..f1963f770f2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXProxy.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXProxy.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.core; @@ -49,7 +50,7 @@ import java.util.Set; /** -@deprecated An AMXProxy offers generic access to any AMX-compliant MBean, including the ability to navigate +An AMXProxy offers generic access to any AMX-compliant MBean, including the ability to navigate upwards to the Parent MBean, find all children or those of a particular type or name, to get all metadata, atttributes, or to invoke any method.

@@ -60,7 +61,7 @@ children of a particular type, creating new children (eg configuration), attribu its sub-interfaces.

-Implementing handler— an AMXProxy is implemented by {@link AMXProxyHandler}, but the handler should be considered +Implementing handler — an AMXProxy is implemented by {@link AMXProxyHandler}, but the handler should be considered private: do not use it as it is subject to change.

@@ -71,7 +72,7 @@ children of a particular type, creating new children (eg configuration), attribu interface demands the use of AMXProxy and sub-types, whereas the MBean must return ObjectName.

-Method name convention— a convention followed in AMXProxy is that convenience "getter" methods +Method name convention — a convention followed in AMXProxy is that convenience "getter" methods (non-remote methods implemented directly by the proxy itself) do not use the get prefix, in order to distinguish them from the usual getter pattern for real MBean attributes. For example, {@link #parent} returns an AMXProxy, but {@link #getParent} returns the value of the @@ -79,7 +80,7 @@ interface demands the use of AMXProxy and sub-types, whereas the MBean must retu The same convention is followed for {@link #childrenSet}, etc / {@link #getChildren}.

-Not authoritative— proxy interfaces should not be considered authoritative, meaning that an underlying MBean +Not authoritative — proxy interfaces should not be considered authoritative, meaning that an underlying MBean implementation determines what the MBean actually provides, possibly ignoring the proxy interface (this is the case with config MBeans, which derive their metadata from the ConfigBean @Configured interface). @@ -97,7 +98,7 @@ implementation changes over time (eg addition or removal of attributes), obtain all available attributes, and of course {@link MetaGetters#mbeanInfo} provides extensive metadata.

-Auto-mapping of ObjectName— An AMXProxy automatically maps various ObjectName constructs +Auto-mapping of ObjectName — An AMXProxy automatically maps various ObjectName constructs to the equivalent AMXProxy(ies).

For example, an MBean providing an Attribute named Item should declare it as an ObjectName, or for a plurality Items, declaring an ObjectName[]. Any of the following proxy methods (declared in a sub-interface of AMXProxy) will automatically convert the resulting @@ -119,7 +120,6 @@ Any of the following proxy methods (declared in a sub-interface of AMXProxy) wil @see org.glassfish.admin.amx.config.AMXConfigProxy */ @Taxonomy(stability = Stability.UNCOMMITTED) -@Deprecated public interface AMXProxy extends AMX_SPI { /** MBean MUST return an ObjectName. May be null for DomainRoot only. */ diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXValidator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXValidator.java index ce1c68fb0ce..b3e7503d858 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXValidator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/AMXValidator.java @@ -37,10 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.core; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -68,240 +70,217 @@ import org.glassfish.external.arc.Taxonomy; /** -Validation of key behavioral requirements of AMX MBeans. -These tests do not validate any MBean-specific semantics, only general requirements for all AMX MBeans. -

-Note that all tests have to account for the possibility that an MBean can be unregistered while -the validation is in progress— that is not a test failure, since it is perfectly legal. + * Validation of key behavioral requirements of AMX MBeans. + * These tests do not validate any MBean-specific semantics, only general requirements for all AMX MBeans. + *

+ * Note that all tests have to account for the possibility that an MBean can be unregistered while + * the validation is in progress— that is not a test failure, since it is perfectly legal. */ @Taxonomy(stability = Stability.UNCOMMITTED) -public final class AMXValidator -{ - /** we can run in the client or server, so use a fixed-name Logger */ - private static final Logger sLogger = Logger.getLogger( AMXValidator.class.getName() ); +public final class AMXValidator { + + /** + * we can run in the client or server, so use a fixed-name Logger + */ + private static final Logger sLogger = Logger.getLogger(AMXValidator.class.getName()); + private static void log( - final Level level, - final String msg, - final Throwable t) - { + final Level level, + final String msg, + final Throwable t) { sLogger.log(level, msg, t); } + private static void logWarning( - final String msg, - final Throwable t) - { + final String msg, + final Throwable t) { log(Level.WARNING, msg, t); } + private static void logInfo( - final String msg, - final Throwable t) - { + final String msg, + final Throwable t) { log(Level.INFO, msg, t); } + private static void progress( - final Object... args) - { - if ( sLogger.isLoggable(Level.FINE) ) - { + final Object... args) { + if (sLogger.isLoggable(Level.FINE)) { log(Level.FINE, toString(args), null); } } - - private static String toString(final Object... args) - { + + private static String toString(final Object... args) { final StringBuilder buf = new StringBuilder(); - for( final Object o : args ) - { - buf.append("").append( o); + for (final Object o : args) { + buf.append("").append(o); } return buf.toString(); } - + private static final Level LEVEL_DEBUG = Level.FINE; - private static void debug(final Object... args) - { - if ( sLogger.isLoggable(LEVEL_DEBUG) ) - { - log( LEVEL_DEBUG, toString(args), null ); + + private static void debug(final Object... args) { + if (sLogger.isLoggable(LEVEL_DEBUG)) { + log(LEVEL_DEBUG, toString(args), null); } } - - private static final String NL = StringUtil.NEWLINE(); + private static final String NL = StringUtil.LS; private final MBeanServerConnection mMBeanServer; private final ProxyFactory mProxyFactory; private final DomainRoot mDomainRoot; - + // created if needed - private MBeanTrackerMBean mMBeanTracker; + private MBeanTrackerMBean mMBeanTracker; + + private volatile boolean mUnregisterNonCompliant; + private volatile boolean mLogInaccessibleAttributes; - private volatile boolean mUnregisterNonCompliant; - private volatile boolean mLogInaccessibleAttributes; - private volatile String mValidationLevel; - public AMXValidator( - final MBeanServerConnection conn, - final String validationLevel, - final boolean unregisterNonCompliant, - final boolean logInaccessibleAttributes ) - { + final MBeanServerConnection conn, + final String validationLevel, + final boolean unregisterNonCompliant, + final boolean logInaccessibleAttributes) { mMBeanServer = conn; mProxyFactory = ProxyFactory.getInstance(conn); mDomainRoot = mProxyFactory.getDomainRootProxy(false); - - mValidationLevel = validationLevel; + mUnregisterNonCompliant = unregisterNonCompliant; mLogInaccessibleAttributes = logInaccessibleAttributes; } - + /** - Return a Set containing ObjectNames that appear to be AMX-compliant MBeans + * Return a Set containing ObjectNames that appear to be AMX-compliant MBeans */ - public Set filterAMX(final Set candidates) - { + public Set filterAMX(final Set candidates) { final Set amxSet = new HashSet(); - for( final ObjectName cand : candidates ) - { - if ( cand.getKeyProperty(TYPE_KEY) == null ) continue; - + for (final ObjectName cand : candidates) { + if (cand.getKeyProperty(TYPE_KEY) == null) { + continue; + } + // for now, require matching jmx domain "amx" - if ( cand.getDomain().equals( AMXGlassfish.DEFAULT_JMX_DOMAIN) ) - { + if (cand.getDomain().equals(AMXGlassfish.DEFAULT_JMX_DOMAIN)) { amxSet.add(cand); } - + } return amxSet; } - + /** - Find all MBeans that appear to be AMX MBeans + * Find all MBeans that appear to be AMX MBeans */ - public Set findAllAMXCompliant() - { + public Set findAllAMXCompliant() { // query for all MBeans in all domains // for now, any MBean with Parent/Name and metadata we'll guess is AMX final ObjectName pattern = Util.newObjectNamePattern("*", "*"); Set theWorld = null; - try - { + try { theWorld = mMBeanServer.queryNames(pattern, null); + } catch (final IOException e) { + throw new UncheckedIOException(e); } - catch( final IOException e ) - { - throw new RuntimeException(e); - } - + return filterAMX(theWorld); } - private static final class IllegalClassException extends Exception - { + private static final class IllegalClassException extends Exception { + private final Class mClass; - public IllegalClassException(final Class clazz) - { + public IllegalClassException(final Class clazz) { super("Class " + clazz.getName() + " not allowed for AMX MBeans"); mClass = clazz; } - public Class clazz() - { + public Class clazz() { return mClass; } @Override - public String toString() - { + public String toString() { return super.getMessage(); } } - private static final class ValidationFailureException extends Exception - { + private static final class ValidationFailureException extends Exception { + private final ObjectName mObjectName; - public ValidationFailureException(final ObjectName objectName, final String msg) - { + public ValidationFailureException(String message) { + super(message); + mObjectName = null; + } + + public ValidationFailureException(final ObjectName objectName, final String msg) { super(msg); mObjectName = objectName; } - public ValidationFailureException(final AMXProxy amx, final String msg) - { + public ValidationFailureException(final AMXProxy amx, final String msg) { this(amx.objectName(), msg); } - public ObjectName objectName() - { + public ObjectName objectName() { return mObjectName; } @Override - public String toString() - { + public String toString() { return getMessage() + ", " + mObjectName; } } - - /** keeps track of all validation failures */ - private static final class Failures - { + + /** + * keeps track of all validation failures + */ + private static final class Failures { + private final ConcurrentMap mFailures = new ConcurrentHashMap(); private AtomicInteger mNumTested = new AtomicInteger(); - public Failures() - { - } - - public int getNumTested() - { + public int getNumTested() { return mNumTested.get(); } - public int getNumFailures() - { + public int getNumFailures() { return mFailures.keySet().size(); } - public Map getFailures() - { + public Map getFailures() { return mFailures; } - void result( final ProblemList problems) - { + void result(final ProblemList problems) { mNumTested.incrementAndGet(); - if ( problems.hasProblems() ) - { - if ( problems.instanceNotFound() ) - { + if (problems.hasProblems()) { + if (problems.instanceNotFound()) { return; } - - mFailures.put( problems.getObjectName(), problems); + + mFailures.put(problems.getObjectName(), problems); } } @Override - public String toString() - { + public String toString() { final StringBuilder builder = new StringBuilder(); - for (final ObjectName badBoy : mFailures.keySet()) - { + for (final ObjectName badBoy : mFailures.keySet()) { final ProblemList problems = mFailures.get(badBoy); builder.append(badBoy).append(NL); - builder.append(CollectionUtil.toString( problems.getProblems(), NL)); + builder.append(CollectionUtil.toString(problems.getProblems(), NL)); builder.append(NL); builder.append(NL); } @@ -310,424 +289,327 @@ public String toString() return builder.toString() + NL + mNumTested + " MBeans tested."; } } - - public static final class ProblemList - { - final ObjectName mObjectName; + + public static final class ProblemList { + + final ObjectName mObjectName; final List mProblems; - boolean mInstanceNotFound; - - public ProblemList( final ObjectName objectName ) - { + boolean mInstanceNotFound; + + public ProblemList(final ObjectName objectName) { mObjectName = objectName; mProblems = new ArrayList(); mInstanceNotFound = false; } - - public List getProblems() { return mProblems; } - public ObjectName getObjectName() { return mObjectName; } - - public boolean hasProblems() { return !mProblems.isEmpty(); } - - - public boolean instanceNotFound() - { + + public List getProblems() { + return mProblems; + } + + public ObjectName getObjectName() { + return mObjectName; + } + + public boolean hasProblems() { + return !mProblems.isEmpty(); + } + + public boolean instanceNotFound() { return mInstanceNotFound; } - - private void add( final String msg ) - { - try - { - add( msg, null); - } - catch( final InstanceNotFoundException e ) - { + + private void add(final String msg) { + try { + add(msg, null); + } catch (final InstanceNotFoundException e) { // can't happen } } - - private void add( final Throwable t) throws InstanceNotFoundException { add( "", t); } - private void add( final String msg, final Throwable t ) - throws InstanceNotFoundException - { - if ( t == null ) - { - mProblems.add( msg ); - } - else - { + private void add(final Throwable t) throws InstanceNotFoundException { + add("", t); + } + + private void add(final String msg, final Throwable t) + throws InstanceNotFoundException { + if (t == null) { + mProblems.add(msg); + } else { // it's not an issue if the MBean went missing final Throwable rootCause = ExceptionUtil.getRootCause(t); - if ( AMXValidator.instanceNotFound(rootCause) ) - { + if (AMXValidator.instanceNotFound(rootCause)) { mInstanceNotFound = true; // abort validation by throwing InstanceNotFoundException - throw new InstanceNotFoundException( "" + mObjectName ); - } - else - { - mProblems.add( msg + "\n" + ExceptionUtil.toString(rootCause) ); + throw new InstanceNotFoundException("" + mObjectName); + } else { + mProblems.add(msg + "\n" + ExceptionUtil.toString(rootCause)); } } } - + @Override - public String toString() - { - if ( mInstanceNotFound ) - { + public String toString() { + if (mInstanceNotFound) { return "MBean " + mObjectName + " unregistered while being validated"; } - - return "MBean " + mObjectName + " problems: " + NL + CollectionUtil.toString( mProblems, NL); + + return "MBean " + mObjectName + " problems: " + NL + CollectionUtil.toString(mProblems, NL); } } - /** types that are not open types, but that we deem acceptable for a remote API */ - private static Set EXTRA_ALLOWED_TYPES = SetUtil.newTypedSet( - // any special-case exceptions go here - ); - - private static boolean isAcceptableRemoteType(final Class c) - { - if (c.isPrimitive() || - EXTRA_ALLOWED_TYPES.contains(c) || - OpenType.ALLOWED_CLASSNAMES_LIST.contains(c.getName()) || - c.getName().startsWith("javax.management.") ) - { + /** + * types that are not open types, but that we deem acceptable for a remote API + */ + private static final Set EXTRA_ALLOWED_TYPES = SetUtil.newTypedSet( // any special-case exceptions go here + ); + + private static boolean isAcceptableRemoteType(final Class c) { + if (c.isPrimitive() + || EXTRA_ALLOWED_TYPES.contains(c) + || OpenType.ALLOWED_CLASSNAMES_LIST.contains(c.getName()) + || c.getName().startsWith("javax.management.")) { return true; } // quick checks for other common cases - if (c.isArray() && isAcceptableRemoteType(c.getComponentType())) - { - return true; - } - - return false; + return c.isArray() && isAcceptableRemoteType(c.getComponentType()); } /** - "best effort"

- Attributes that cannot be sent to generic clients are not allowed. - More than OpenTypes are allowed eg messy stuff like JSR 77 Stats and Statistics. + * "best effort" + *

+ * Attributes that cannot be sent to generic clients are not allowed. More than OpenTypes are allowed eg messy stuff like JSR 77 Stats and Statistics. */ - private static void checkLegalForRemote(final Object value) throws IllegalClassException - { - if (value == null) - { + private static void checkLegalForRemote(final Object value) throws IllegalClassException { + if (value == null) { return; } final Class clazz = value.getClass(); - if (isAcceptableRemoteType(clazz)) - { + if (isAcceptableRemoteType(clazz)) { return; } // would these always be disallowed? - if (clazz.isSynthetic() || clazz.isLocalClass() || clazz.isAnonymousClass() || clazz.isMemberClass()) - { + if (clazz.isSynthetic() || clazz.isLocalClass() || clazz.isAnonymousClass() || clazz.isMemberClass()) { throw new IllegalClassException(clazz); } - if (clazz.isArray()) - { - if (!isAcceptableRemoteType(clazz.getComponentType())) - { + if (clazz.isArray()) { + if (!isAcceptableRemoteType(clazz.getComponentType())) { final Object[] a = (Object[]) value; - for (final Object o : a) - { + for (final Object o : a) { checkLegalForRemote(o); } } - } - else if (Collection.class.isAssignableFrom(clazz)) - { + } else if (Collection.class.isAssignableFrom(clazz)) { final Collection items = (Collection) value; - for (final Object o : items) - { + for (final Object o : items) { checkLegalForRemote(o); } - } - else if (Map.class.isAssignableFrom(clazz)) - { + } else if (Map.class.isAssignableFrom(clazz)) { final Map items = (Map) value; - for (final Map.Entry me : items.entrySet()) - { + for (final Map.Entry me : items.entrySet()) { checkLegalForRemote(me.getKey()); checkLegalForRemote(me.getValue()); } - } - else - { + } else { throw new IllegalClassException(clazz); } } - static boolean instanceNotFound(final Throwable t ) - { + static boolean instanceNotFound(final Throwable t) { return ExceptionUtil.getRootCause(t) instanceof InstanceNotFoundException; } - - - private void _validate(final AMXProxy proxy, final ProblemList problems) throws InstanceNotFoundException - { - progress( "Validate: ", proxy.objectName() ); - try - { + private void _validate(final AMXProxy proxy, final ProblemList problems) throws InstanceNotFoundException { + progress("Validate: ", proxy.objectName()); + + try { validateObjectName(proxy); - } - catch (final Exception t) - { - problems.add( t); + } catch (final Exception t) { + problems.add(t); } - try - { + try { validateMetadata(proxy, problems); - } - catch (final Exception t) - { + } catch (final Exception t) { problems.add(t); } - try - { + try { validateRequiredAttributes(proxy); - } - catch (final Exception t) - { + } catch (final Exception t) { problems.add(t); } - // test required attributes - try - { - final String name = proxy.getName(); - } - catch (final Exception t) - { - problems.add( "Proxy access to 'Name' failed: ", t); + try { + proxy.getName(); + } catch (final Exception t) { + problems.add("Proxy access to 'Name' failed: ", t); } - try - { - final ObjectName parent = proxy.getParent(); + try { + proxy.getParent(); + } catch (final Exception t) { + problems.add("Proxy access to 'Parent' failed: ", t); } - catch (final Exception t) - { - problems.add( "Proxy access to 'Parent' failed: ", t); - } - try - { - final ObjectName[] children = proxy.getChildren(); - } - catch (final Exception t) - { - problems.add( "Proxy access to 'Children' failed: ", t); + try { + proxy.getChildren(); + } catch (final Exception t) { + problems.add("Proxy access to 'Children' failed: ", t); } - // test path resolution final Pathnames paths = mDomainRoot.getPathnames(); - if ( paths == null ) - { + if (paths == null) { throw new IllegalStateException("Pathnames MBean does not exist"); } - - try - { + + try { final String path = proxy.path(); final ObjectName actualObjectName = proxy.objectName(); final ObjectName o = paths.resolvePath(path); - if (o == null) - { - if ( proxy.valid() ) // could have been unregistered + if (o == null) { + if (proxy.valid()) // could have been unregistered { problems.add("Path " + path + " does not resolve to any ObjectName, should resolve to: " + actualObjectName); } - } - else if (!actualObjectName.equals(o)) - { + } else if (!actualObjectName.equals(o)) { problems.add("Path " + path + " does not resolve to ObjectName: " + actualObjectName); } - } - catch (final Exception t) - { + } catch (final Exception t) { problems.add(t); } // test attributes final Set attributeNames = proxy.extra().attributeNames(); - for (final String attrName : attributeNames) - { - try - { + for (final String attrName : attributeNames) { + try { final Object result = proxy.extra().getAttribute(attrName); checkLegalForRemote(result); - } - catch (final Exception t) - { - if ( attrName.equals(ATTR_NAME) || attrName.equals(ATTR_PARENT) || attrName.equals(ATTR_CHILDREN) ) - { - problems.add( "Attribute failed: '" + attrName + "': ", t); - } - else // too stringer to consider the MBean non-compliant because of a general attribute failure. + } catch (final Exception t) { + if (attrName.equals(ATTR_NAME) || attrName.equals(ATTR_PARENT) || attrName.equals(ATTR_CHILDREN)) { + problems.add("Attribute failed: '" + attrName + "': ", t); + } else // too stringer to consider the MBean non-compliant because of a general attribute failure. { // this code can run in a client; a logger is not advisable - logWarning( "Attribute '" + attrName + "' failed for " + proxy.objectName(), ExceptionUtil.getRootCause(t)); + logWarning("Attribute '" + attrName + "' failed for " + proxy.objectName(), ExceptionUtil.getRootCause(t)); } } } - try - { + try { validateChildren(proxy); - } - catch (final Exception t) - { + } catch (final Exception t) { problems.add(t); } // test proxy methods - try - { + try { final AMXProxy parent = proxy.parent(); - if (parent == null && !proxy.type().equals(Util.deduceType(DomainRoot.class))) - { + if (parent == null && !proxy.type().equals(Util.deduceType(DomainRoot.class))) { final ObjectName parentObjectName = proxy.getParent(); - final boolean exists = mMBeanServer.isRegistered( proxy.objectName() ); - problems.add("Null parent for " + proxy.objectName() + - ", isRegistered(self) = " + exists + ", parent = " + parentObjectName); + final boolean exists = mMBeanServer.isRegistered(proxy.objectName()); + problems.add("Null parent for " + proxy.objectName() + + ", isRegistered(self) = " + exists + ", parent = " + parentObjectName); } final Set childrenSet = proxy.childrenSet(); final Map> childrenMaps = proxy.childrenMaps(); final Map attributesMap = proxy.attributesMap(); final Set attrNames = proxy.attributeNames(); - if (!attrNames.equals(attributesMap.keySet())) - { - final Set keys = new HashSet(attributesMap.keySet()); + if (!attrNames.equals(attributesMap.keySet())) { + final Set keys = new HashSet(attributesMap.keySet()); keys.removeAll(attrNames); - if ( !keys.isEmpty() ) - { - throw new Exception("Attributes Map contains attributes not found in the MBeanInfo: " + keys); + if (!keys.isEmpty()) { + throw new ValidationFailureException("Attributes Map contains attributes not found in the MBeanInfo: " + keys); } - - if ( mLogInaccessibleAttributes ) - { + + if (mLogInaccessibleAttributes) { final Set missing = new HashSet(attrNames); missing.removeAll(attributesMap.keySet()); - + logInfo("Inaccessible attributes: " + missing + " in " + proxy.objectName(), null); } } - for (final AMXProxy child : childrenSet) - { - if (child.extra().singleton()) - { + for (final AMXProxy child : childrenSet) { + if (child.extra().singleton()) { final String childType = child.type(); - if (!child.objectName().equals(proxy.child(childType).objectName())) - { - throw new Exception("Child type " + childType + " cannot be found via child(type)"); + if (!child.objectName().equals(proxy.child(childType).objectName())) { + throw new ValidationFailureException("Child type " + childType + " cannot be found via child(type)"); } } } - for (final String type : childrenMaps.keySet()) - { + for (final String type : childrenMaps.keySet()) { final Map m = proxy.childrenMap(type); - if (m.keySet().isEmpty()) - { - throw new Exception("Child type " + type + " has nothing in Map"); + if (m.keySet().isEmpty()) { + throw new ValidationFailureException("Child type " + type + " has nothing in Map"); } } + } catch (final Exception t) { + problems.add("General test failure: ", t); } - catch (final Exception t) - { - problems.add( "General test failure: ", t); - } - - try - { + try { validateAMXConfig(proxy, problems); - } - catch (final Exception t) - { - if ( proxy.valid() ) - { - problems.add( "General test failure in validateAMXConfig: ", t); + } catch (final Exception t) { + if (proxy.valid()) { + problems.add("General test failure in validateAMXConfig: ", t); } } } - - + private void fail(final ObjectName objectName, final String msg) - throws ValidationFailureException - { + throws ValidationFailureException { throw new ValidationFailureException(objectName, msg); } private void fail(final AMXProxy amx, final String msg) - throws ValidationFailureException - { + throws ValidationFailureException { throw new ValidationFailureException(amx, msg); } - private void validateAMXConfig(final AMXProxy proxy, final ProblemList problems) throws InstanceNotFoundException - { - if (!AMXConfigProxy.class.isAssignableFrom(proxy.extra().genericInterface())) - { + private void validateAMXConfig(final AMXProxy proxy, final ProblemList problems) throws InstanceNotFoundException { + if (!AMXConfigProxy.class.isAssignableFrom(proxy.extra().genericInterface())) { return; } final AMXConfigProxy config = proxy.as(AMXConfigProxy.class); // All AMXConfig must be descendants of Domain - if ( ! config.type().equals( "domain" ) ) // hard-coded type, we can't import Domain.class here + if (!config.type().equals("domain")) // hard-coded type, we can't import Domain.class here { // verify that all its ancestors are also AMXConfig // Do a quick check, ultimately if all AMXConfig have an AMXConfig as a parent, // then they all have DomainConfig as a parent. - if ( ! AMXConfigProxy.class.isAssignableFrom(config.parent().extra().genericInterface() ) ) - { - problems.add("AMXConfig MBean is not a descendant of Domain: " + config.objectName() + ", it has parent " + config.getParent() ); + if (!AMXConfigProxy.class.isAssignableFrom(config.parent().extra().genericInterface())) { + problems.add("AMXConfig MBean is not a descendant of Domain: " + config.objectName() + ", it has parent " + config.getParent()); } } - + // check default values support final Map defaultValues = config.getDefaultValues(false); final Map defaultValuesAMX = config.getDefaultValues(true); - if (defaultValues.keySet().size() != defaultValuesAMX.keySet().size()) - { + if (defaultValues.keySet().size() != defaultValuesAMX.keySet().size()) { problems.add("Default values for AMX names differ in number from XML names: " + defaultValues.keySet().size() + " != " + defaultValuesAMX.keySet().size()); } - for (final Map.Entry me : defaultValues.entrySet()) - { + for (final Map.Entry me : defaultValues.entrySet()) { final Object value = me.getValue(); - if (value == null) - { + if (value == null) { problems.add("Default value of null for: " + me.getKey()); - } - else if (!(value instanceof String)) - { + } else if (!(value instanceof String)) { problems.add("Default value is not a String for: " + me.getKey()); } } final String[] subTypes = config.extra().subTypes(); - if (subTypes != null) - { - for (final String subType : subTypes) - { + if (subTypes != null) { + for (final String subType : subTypes) { config.getDefaultValues(subType, false); } } @@ -738,300 +620,228 @@ else if (!(value instanceof String)) private static final Pattern NAME_PATTERN = Pattern.compile(LEGAL_NAME_PATTERN); private void validateObjectName(final AMXProxy proxy) - throws ValidationFailureException - { + throws ValidationFailureException { final ObjectName objectName = proxy.objectName(); final String type = objectName.getKeyProperty("type"); - if (type == null || type.length() == 0) - { + if (type == null || type.length() == 0) { fail(objectName, "type property required in ObjectName"); } - if (!TYPE_PATTERN.matcher(type).matches()) - { + if (!TYPE_PATTERN.matcher(type).matches()) { fail(objectName, "Illegal type \"" + type + "\", does not match " + TYPE_PATTERN.pattern()); } final String nameProp = objectName.getKeyProperty("name"); - if (nameProp != null) - { - if (nameProp.length() == 0) - { + if (nameProp != null) { + if (nameProp.length() == 0) { fail(objectName, "name property of ObjectName may not be empty"); } - if (!NAME_PATTERN.matcher(nameProp).matches()) - { + if (!NAME_PATTERN.matcher(nameProp).matches()) { fail(objectName, "Illegal name \"" + nameProp + "\", does not match " + NAME_PATTERN.pattern()); } - } - else - { + } else { // no name property, it's by definition a singleton - if (!proxy.extra().singleton()) - { + if (!proxy.extra().singleton()) { fail(objectName, "Metadata claims named (non-singleton), but no name property present in ObjectName"); } } - if (proxy.parent() != null) - { - if (!proxy.parentPath().equals(proxy.parent().path())) - { + if (proxy.parent() != null) { + if (!proxy.parentPath().equals(proxy.parent().path())) { fail(objectName, "Parent path of " + proxy.parentPath() + " does not match parent's path for parent " + proxy.parent().objectName()); } } } - /** verify that the children/parent relationship exists */ + /** + * verify that the children/parent relationship exists + */ private void validateChildren(final AMXProxy proxy) - throws ValidationFailureException - { + throws ValidationFailureException { final Set attrNames = proxy.attributeNames(); - if (!attrNames.contains(ATTR_CHILDREN)) - { + if (!attrNames.contains(ATTR_CHILDREN)) { // must NOT supply Children - try - { + try { fail(proxy, "MBean has no Children attribute in its MBeanInfo, but supplies the attribute"); - } - catch (Exception e) - { + } catch (Exception e) { // good, the Attribute must not exist } - } - else - { + } else { // must supply Children - try - { + try { final ObjectName[] children = proxy.getChildren(); - if (children == null) - { + if (children == null) { fail(proxy, "Children attribute must be non-null"); } final Set childrenSet = SetUtil.newSet(children); - if ( childrenSet.size() != children.length ) - { + if (childrenSet.size() != children.length) { fail(proxy, "Children contains duplicates"); } - if ( childrenSet.contains(null) ) - { + if (childrenSet.contains(null)) { fail(proxy, "Children contains null"); } // verify that each child is non-null and references its parent - for (final ObjectName childObjectName : children) - { - if (childObjectName == null) - { + for (final ObjectName childObjectName : children) { + if (childObjectName == null) { fail(proxy, "Child in Children array is null"); } final AMXProxy child = mProxyFactory.getProxy(childObjectName); - if (!proxy.objectName().equals(child.parent().objectName())) - { - fail(proxy, "Child’s Parent of " + child.parent().objectName() + - " does not match the actual parent of " + proxy.objectName()); + if (!proxy.objectName().equals(child.parent().objectName())) { + fail(proxy, "Child’s Parent of " + child.parent().objectName() + + " does not match the actual parent of " + proxy.objectName()); } } // verify that the children types do not differ only by case-sensitivity final Set caseSensitiveTypes = new HashSet(); final Set caseInsensitiveTypes = new HashSet(); - for (final ObjectName o : children) - { + for (final ObjectName o : children) { caseSensitiveTypes.add(Util.getTypeProp(o)); caseInsensitiveTypes.add(Util.getTypeProp(o).toLowerCase(Locale.ENGLISH)); } - if (caseSensitiveTypes.size() != caseInsensitiveTypes.size()) - { + if (caseSensitiveTypes.size() != caseInsensitiveTypes.size()) { fail(proxy, "Children types must be case-insensitive"); } - + // verify that the MBeanTracker agrees with the parent MBean - final Set tracked = getMBeanTracker().getChildrenOf(proxy.objectName()); - if ( childrenSet.size() != children.length ) - { + final Set tracked = getMBeanTracker().getChildrenOf(proxy.objectName()); + if (childrenSet.size() != children.length) { // try again, in case it's a timing issue - final Set childrenSetNow = SetUtil.newSet( proxy.getChildren() ); - if ( ! tracked.equals( childrenSetNow ) ) - { - fail(proxy, "MBeanTracker has different MBeans than the MBean: {" + - CollectionUtil.toString(tracked, ", ") + "} vs MBean having {" + - CollectionUtil.toString(childrenSetNow, ", ") + "}"); + final Set childrenSetNow = SetUtil.newSet(proxy.getChildren()); + if (!tracked.equals(childrenSetNow)) { + fail(proxy, "MBeanTracker has different MBeans than the MBean: {" + + CollectionUtil.toString(tracked, ", ") + "} vs MBean having {" + + CollectionUtil.toString(childrenSetNow, ", ") + "}"); } } - } - catch (final Exception e) - { - if ( ! instanceNotFound(e) ) - { + } catch (final Exception e) { + if (!instanceNotFound(e)) { fail(proxy, "MBean failed to supply Children attribute"); } } // children of the same type must have the same MBeanInfo - try - { + try { final Map> maps = proxy.childrenMaps(); - for (final Map.Entry> me : maps.entrySet()) - { + for (final Map.Entry> me : maps.entrySet()) { final Map siblings = me.getValue(); - if (siblings.keySet().size() > 1) - { + if (siblings.keySet().size() > 1) { final Iterator iter = siblings.values().iterator(); final MBeanInfo mbeanInfo = iter.next().extra().mbeanInfo(); - while (iter.hasNext()) - { + while (iter.hasNext()) { final AMXProxy next = iter.next(); - if (!mbeanInfo.equals(next.extra().mbeanInfo())) - { - fail(proxy, "Children of type=" + me.getKey() + " must have the same MBeanInfo: " + siblings.values() ); + if (!mbeanInfo.equals(next.extra().mbeanInfo())) { + fail(proxy, "Children of type=" + me.getKey() + " must have the same MBeanInfo: " + siblings.values()); } } } } - } - catch (final Exception e) - { - if ( ! instanceNotFound(e) ) - { - logWarning( "MBean failed validating the MBeanInfo of children", e ); - fail(proxy, "MBean failed validating the MBeanInfo of children with Exception: " + e.getMessage() ); + } catch (final Exception e) { + if (!instanceNotFound(e)) { + logWarning("MBean failed validating the MBeanInfo of children", e); + fail(proxy, "MBean failed validating the MBeanInfo of children with Exception: " + e.getMessage()); } } } } - + private MBeanTrackerMBean getMBeanTracker() { - if ( mMBeanTracker == null ) - { + if (mMBeanTracker == null) { mMBeanTracker = MBeanServerInvocationHandler.newProxyInstance( - mMBeanServer, MBeanTrackerMBean.MBEAN_TRACKER_OBJECT_NAME, MBeanTrackerMBean.class, false); + mMBeanServer, MBeanTrackerMBean.MBEAN_TRACKER_OBJECT_NAME, MBeanTrackerMBean.class, false); } return mMBeanTracker; - } - - private static final class MetadataValidator - { + } + + private static final class MetadataValidator { + private final Descriptor mDescriptor; private final Set mFieldNames; private final ProblemList mProblems; - public MetadataValidator(final Descriptor d, final ProblemList problems) throws InstanceNotFoundException - { + public MetadataValidator(final Descriptor d, final ProblemList problems) throws InstanceNotFoundException { mDescriptor = d; mFieldNames = SetUtil.newSet(d.getFieldNames()); mProblems = problems; validateRemote(); } - + // Descriptor fields must be remotable - void validateRemote() throws InstanceNotFoundException - { - for (final String fieldName : mFieldNames) - { - try - { + void validateRemote() throws InstanceNotFoundException { + for (final String fieldName : mFieldNames) { + try { checkLegalForRemote(mDescriptor.getFieldValue(fieldName)); - } - catch (final IllegalClassException e) - { + } catch (final IllegalClassException e) { mProblems.add("Descriptor field " + fieldName + " uses a remote-unfriendly class: " + e.clazz().getName()); } } } - void validateMetadataBoolean(final String fieldName) throws InstanceNotFoundException - { - if (mFieldNames.contains(fieldName)) - { + void validateMetadataBoolean(final String fieldName) throws InstanceNotFoundException { + if (mFieldNames.contains(fieldName)) { final Object value = mDescriptor.getFieldValue(fieldName); - if (value == null) - { + if (value == null) { mProblems.add("Descriptor field " + fieldName + " must not be null"); - } - else if (!((value instanceof Boolean) || value.equals("true") || value.equals("false"))) - { + } else if (!((value instanceof Boolean) || value.equals("true") || value.equals("false"))) { mProblems.add("Descriptor field " + fieldName + " must be set to 'true' or 'false', value is " + value); } } } - void validateMetadataString(final String fieldName) throws InstanceNotFoundException - { - if (mFieldNames.contains(fieldName)) - { + void validateMetadataString(final String fieldName) throws InstanceNotFoundException { + if (mFieldNames.contains(fieldName)) { final Object value = mDescriptor.getFieldValue(fieldName); - if ( value != null ) - { - if ( ! (value instanceof String) ) - { - mProblems.add("Descriptor field " + fieldName + " must be a String!" ); + if (value != null) { + if (!(value instanceof String)) { + mProblems.add("Descriptor field " + fieldName + " must be a String!"); } } } } - void validate(final String fieldName, final Class clazz) throws InstanceNotFoundException - { - if (mFieldNames.contains(fieldName)) - { + void validate(final String fieldName, final Class clazz) throws InstanceNotFoundException { + if (mFieldNames.contains(fieldName)) { final Object value = mDescriptor.getFieldValue(fieldName); - if (value == null || (!(clazz.isAssignableFrom(value.getClass())))) - { + if (value == null || (!(clazz.isAssignableFrom(value.getClass())))) { mProblems.add("Descriptor field " + fieldName + " must be of class " + clazz.getSimpleName()); } } } } - - private static boolean - isLegalClassname( final String s ) - { - if ( s.length()== 0 || s.indexOf(' ') >= 0 ) - { - return false; // detect totally bogus name - } - - return true; + + private static boolean + isLegalClassname(final String s) { + // detect totally bogus name + return !(s.length() == 0 || s.indexOf(' ') >= 0); } - - private void checkLegalAttributeType(final String clazz, final String attrName, final ProblemList problems ) - throws InstanceNotFoundException - { - if ( ! isLegalClassname(clazz) ) - { - problems.add( "Illegal classname for attribute " + StringUtil.quote(attrName) + ": " + StringUtil.quote(clazz) ); + private void checkLegalAttributeType(final String clazz, final String attrName, final ProblemList problems) { + if (!isLegalClassname(clazz)) { + problems.add("Illegal classname for attribute " + StringUtil.quote(attrName) + ": " + StringUtil.quote(clazz)); } } - - private void checkLegalReturnType(final String clazz, final String operation, final ProblemList problems ) - throws InstanceNotFoundException - { - if ( ! isLegalClassname(clazz) ) - { - problems.add( "Illegal return type for " + operation + "(): " + StringUtil.quote(clazz) ); + + private void checkLegalReturnType(final String clazz, final String operation, final ProblemList problems) { + if (!isLegalClassname(clazz)) { + problems.add("Illegal return type for " + operation + "(): " + StringUtil.quote(clazz)); } } private void validateMetadata(final AMXProxy proxy, final ProblemList problems) - throws InstanceNotFoundException - { + throws InstanceNotFoundException { final MBeanInfo mbeanInfo = proxy.extra().mbeanInfo(); final Descriptor d = mbeanInfo.getDescriptor(); // verify that no extraneous field exist final Set LEGAL_AMX_DESCRIPTORS = SetUtil.newStringSet( DESC_GENERIC_INTERFACE_NAME, DESC_IS_SINGLETON, DESC_IS_GLOBAL_SINGLETON, DESC_GROUP, DESC_SUPPORTS_ADOPTION, DESC_SUB_TYPES); - for (final String fieldName : d.getFieldNames()) - { - if (fieldName.startsWith(DESC_PREFIX) && !LEGAL_AMX_DESCRIPTORS.contains(fieldName)) - { + for (final String fieldName : d.getFieldNames()) { + if (fieldName.startsWith(DESC_PREFIX) && !LEGAL_AMX_DESCRIPTORS.contains(fieldName)) { problems.add("Illegal/unknown AMX metadata field: " + fieldName + " = " + d.getFieldValue(fieldName)); } } @@ -1048,286 +858,193 @@ private void validateMetadata(final AMXProxy proxy, final ProblemList problems) val.validate(DESC_SUB_TYPES, String[].class); - for (final MBeanAttributeInfo attrInfo : mbeanInfo.getAttributes()) - { - checkLegalAttributeType( attrInfo.getType(), attrInfo.getName(), problems ); + for (final MBeanAttributeInfo attrInfo : mbeanInfo.getAttributes()) { + checkLegalAttributeType(attrInfo.getType(), attrInfo.getName(), problems); new MetadataValidator(attrInfo.getDescriptor(), problems); } - for (final MBeanOperationInfo opInfo : mbeanInfo.getOperations()) - { - checkLegalReturnType( opInfo.getReturnType(), opInfo.getName(), problems ); - + for (final MBeanOperationInfo opInfo : mbeanInfo.getOperations()) { + checkLegalReturnType(opInfo.getReturnType(), opInfo.getName(), problems); + new MetadataValidator(opInfo.getDescriptor(), problems); } - for (final MBeanConstructorInfo cosntructorInfo : mbeanInfo.getConstructors()) - { + for (final MBeanConstructorInfo cosntructorInfo : mbeanInfo.getConstructors()) { new MetadataValidator(cosntructorInfo.getDescriptor(), problems); } - for (final MBeanNotificationInfo notifInfo : mbeanInfo.getNotifications()) - { + for (final MBeanNotificationInfo notifInfo : mbeanInfo.getNotifications()) { new MetadataValidator(notifInfo.getDescriptor(), problems); } - if ( proxy.extra().globalSingleton() ) - { + if (proxy.extra().globalSingleton()) { final ObjectName objectName = proxy.objectName(); - //debug( "Global singleton type = " + Util.getTypeProp(objectName) ); // don't use Query MBean, it might not exist - final ObjectName pattern = Util.newObjectNamePattern( objectName.getDomain(), Util.makeTypeProp(Util.getTypeProp(objectName)) ); - try - { - final Set instances = mMBeanServer.queryNames( pattern, null); - - if ( instances.size() > 1 ) - { - problems.add( "Global singleton " + objectName + - " conflicts with other MBeans of the same type: " + - CollectionUtil.toString(instances, ", ")); + final ObjectName pattern = Util.newObjectNamePattern(objectName.getDomain(), Util.makeTypeProp(Util.getTypeProp(objectName))); + try { + final Set instances = mMBeanServer.queryNames(pattern, null); + + if (instances.size() > 1) { + problems.add("Global singleton " + objectName + + " conflicts with other MBeans of the same type: " + + CollectionUtil.toString(instances, ", ")); } - } - catch( final Exception e ) - { + } catch (final Exception e) { throw new RuntimeException(e); } } } private void validateRequiredAttributes(final AMXProxy proxy) - throws ValidationFailureException - { + throws ValidationFailureException { final ObjectName objectName = proxy.objectName(); // verify that the required attributes are present final Map infos = JMXUtil.attributeInfosToMap(proxy.extra().mbeanInfo().getAttributes()); final Set attrNames = infos.keySet(); - if (!attrNames.contains("Name")) - { + if (!attrNames.contains("Name")) { fail(objectName, "MBeanInfo does not contain Name attribute"); } - if (!attrNames.contains("Parent")) - { + if (!attrNames.contains("Parent")) { fail(objectName, "MBeanInfo does not contain Parent attribute"); } - if (attrNames.contains("Children")) - { + if (attrNames.contains("Children")) { // must contain a non-null list of children - try - { - if (proxy.getChildren() == null) - { + try { + if (proxy.getChildren() == null) { fail(objectName, "value of Children attribute must not be null"); } - } - catch (final AMXException e) - { + } catch (final AMXException e) { throw e; - } - catch (final Exception e) - { - if ( ! instanceNotFound(e) ) - { + } catch (final Exception e) { + if (!instanceNotFound(e)) { fail(objectName, "does not supply children correctly"); } } - } - else - { + } else { // must NOT contain children, we expect an exception - try - { + try { proxy.getChildren(); fail(objectName, "Children attribute is present, but not listed in MBeanInfo"); - } - catch (final Exception e) - { + } catch (final Exception e) { // good, this is expected } } } - public static final class ValidationResult - { + public static final class ValidationResult { + private final String mDetails; private final int mNumTested; private final int mNumFailures; - + private final Map mProblems; - private ValidationResult( final Failures failures ) - { + private ValidationResult(final Failures failures) { mNumTested = failures.getNumTested(); mNumFailures = failures.getNumFailures(); mDetails = failures.toString(); mProblems = failures.getFailures(); } - public String details() - { + public String details() { return mDetails; } - public Map failures() - { + public Map failures() { return mProblems; } - public int numTested() - { + public int numTested() { return mNumTested; } - public int numFailures() - { + public int numFailures() { return mNumFailures; } @Override - public String toString() - { + public String toString() { return details(); } } - - private void unregisterNonCompliantMBean( final ObjectName objectName) - { - if ( mUnregisterNonCompliant ) - { + + private void unregisterNonCompliantMBean(final ObjectName objectName) { + if (mUnregisterNonCompliant) { try { mMBeanServer.unregisterMBean(objectName); - logWarning( "Unregistered non-compliant MBean " + objectName, null); - } - catch( final Exception ignore ) { - logWarning( "Unable to unregister non-compliant MBean " + objectName, null); + logWarning("Unregistered non-compliant MBean " + objectName, null); + } catch (final Exception ignore) { + logWarning("Unable to unregister non-compliant MBean " + objectName, null); } } } - - public ValidationResult validate(final Collection c) - { - final ObjectName[] targets = CollectionUtil.toArray( c, ObjectName.class ); - return validate( targets ); + + public ValidationResult validate(final Collection c) { + final ObjectName[] targets = CollectionUtil.toArray(c, ObjectName.class); + return validate(targets); } - - public ValidationResult validate(final ObjectName[] targets) - { + + public ValidationResult validate(final ObjectName[] targets) { final Failures failures = new Failures(); // list them in order - for (final ObjectName objectName : targets) - { - progress( "AMXValidator.validate(), begin: " + objectName ); + for (final ObjectName objectName : targets) { + progress("AMXValidator.validate(), begin: " + objectName); final ProblemList problems = new ProblemList(objectName); - AMXProxy amx = null; - - try - { + AMXProxy amx = null; + + try { // certain failures prevent even the proxy from being created, a fatal error amx = mProxyFactory.getProxy(objectName); - if ( amx == null ) - { + if (amx == null) { continue; // not found } - //debug( "VALIDATING: got proxy for: " + objectName ); - } - catch( final Exception e ) - { - if ( instanceNotFound(e) ) - { - progress( "AMXValidator.validate(), InstanceNotFound: " + objectName ); + } catch (final Exception e) { + if (instanceNotFound(e)) { + progress("AMXValidator.validate(), InstanceNotFound: " + objectName); continue; } - + final String msg = "Cannot create AMXProxy for MBean \"" + objectName; - progress( msg ); + progress(msg); problems.add(msg); } - - if ( amx != null ) - { - try - { + + if (amx != null) { + try { _validate(amx, problems); - } - catch( final InstanceNotFoundException e ) - { + } catch (final InstanceNotFoundException e) { continue; // can't be tested, it's gone - } - catch( final Exception e ) - { - logWarning( "AMXValidator.validate(): got exception from _validate for " + objectName, e); - problems.add( "Validation failure for MBean " + objectName + e); + } catch (final Exception e) { + logWarning("AMXValidator.validate(): got exception from _validate for " + objectName, e); + problems.add("Validation failure for MBean " + objectName + e); } } - if ( problems.hasProblems() && ! problems.instanceNotFound() ) - { - debug( "AMXValidator.validate(): got problems from _validate for " + objectName + " : " + problems ); - - //debug( "Calling unregisterNonCompliantMBean(): " + objectName + " for problems: " + problems ); + if (problems.hasProblems() && !problems.instanceNotFound()) { + debug("AMXValidator.validate(): got problems from _validate for " + objectName + " : " + problems); + unregisterNonCompliantMBean(objectName); failures.result(problems); } - progress( "AMXValidator.validate(): validated: " + objectName ); + progress("AMXValidator.validate(): validated: " + objectName); } - final ValidationResult result = new ValidationResult( failures ); - return result; + return new ValidationResult(failures); } - public ValidationResult validate(final ObjectName objectName) - { - return validate( new ObjectName[] { objectName } ); + public ValidationResult validate(final ObjectName objectName) { + return validate(new ObjectName[]{objectName}); } - public ValidationResult validate() - { - final List all = Util.toObjectNameList( mDomainRoot.getQueryMgr().queryAll() ); + public ValidationResult validate() { + final List all = Util.toObjectNameList(mDomainRoot.getQueryMgr().queryAll()); return validate(CollectionUtil.toArray(all, ObjectName.class)); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameConstants.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameConstants.java index 5d413d1246f..3802ee19edb 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameConstants.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameConstants.java @@ -37,11 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ package org.glassfish.admin.amx.core; import org.glassfish.external.arc.Stability; @@ -49,81 +46,70 @@ import org.glassfish.admin.amx.base.Pathnames; /** - Constants and regex related to pathnames. -

- Wildcarding is basic: a '*" means "0 or more characters" (a '*' is converted to - '.*' for regex purposes). + * Constants and regex related to pathnames. + *

+ * Wildcarding is basic: a '*" means "0 or more characters" (a '*' is converted to '.*' for regex purposes). + * * @see Pathnames * @see PathnameParser */ @Taxonomy(stability = Stability.UNCOMMITTED) -public final class PathnameConstants -{ - private PathnameConstants() {} - - /** delimiter between parts of a path */ +public final class PathnameConstants { + + private PathnameConstants() { + } + + /** + * delimiter between parts of a path + */ public static final char SEPARATOR = '/'; - + /** - Wildcard charcter, the '*' (not a regex expression). - Usage is similar to usage in a shell, the '*' means "zero or more - */ - public static final String MATCH_ZERO_OR_MORE = "*"; + * Wildcard charcter, the '*' (not a regex expression). Usage is similar to usage in a shell, + * the '*' means "zero or more + */ + public static final char MATCH_ZERO_OR_MORE = '*'; - /** subscript left character, subscripts must be a character pair for grammar reasons */ + /** + * subscript left character, subscripts must be a character pair for grammar reasons + */ public static final char SUBSCRIPT_LEFT = '['; - /** subscript right character, subscripts must be a character pair for grammar reasons */ + /** + * subscript right character, subscripts must be a character pair for grammar reasons + */ public static final char SUBSCRIPT_RIGHT = ']'; - + /** - The characters legal to use as the type portion of a pathname, - expressed as regex compatible string, but without enclosing square brackets. - */ + * The characters legal to use as the type portion of a pathname, expressed as regex compatible string, + * but without enclosing square brackets. + */ public static final String LEGAL_CHAR_FOR_TYPE = "$a-zA-Z0-9._-"; - - /** Regex pattern for one legal character (in square braces). */ + + /** + * Regex pattern for one legal character (in square braces). + */ public static final String LEGAL_CHAR_FOR_TYPE_PATTERN = "[**" + LEGAL_CHAR_FOR_TYPE + "]"; - - /** Regex pattern for one legal character (in square braces), wildcard allowed */ - // public static final String LEGAL_CHAR_FOR_TYPE_WILD_PATTERN = "[" + LEGAL_CHAR_FOR_TYPE + "*]"; - - /** regex pattern denoting a legal type, grouping () surrounding it */ + + /** + * regex pattern denoting a legal type, grouping () surrounding it + */ public static final String LEGAL_TYPE_PATTERN = "(" + LEGAL_CHAR_FOR_TYPE_PATTERN + LEGAL_CHAR_FOR_TYPE_PATTERN + "*)"; - - /** regex pattern denoting a legal type, with wildcards, grouping () surrounding it */ - // public static String LEGAL_TYPE_WILD_PATTERN = "(" + LEGAL_CHAR_FOR_TYPE_WILD_PATTERN + "*)"; /** - The characters legal to use as a name. A name may be zero length, and it may include - the {@link #SEPARATOR} character. However, it may not include the right square brace, because - that character terminates a subscript. - JMX ObjectNames might have additional restrictions. - */ + * The characters legal to use as a name. A name may be zero length, and it may include the {@link #SEPARATOR} character. + * However, it may not include the right square brace, because that character terminates a subscript. + * JMX ObjectNames might have additional restrictions. + */ public static final String LEGAL_CHAR_FOR_NAME = "^" + SUBSCRIPT_RIGHT; - /** Regex pattern for one legal name character (in square braces). */ + /** + * Regex pattern for one legal name character (in square braces). + */ public static final String LEGAL_CHAR_FOR_NAME_PATTERN = "[" + LEGAL_CHAR_FOR_NAME + "]"; - /** Regex pattern for one legal name character (in square braces). */ - // public static final String LEGAL_CHAR_FOR_NAME_WILD_PATTERN = "[" + LEGAL_CHAR_FOR_NAME + "*]"; - - /** regex pattern denoting a legal name */ + /** + * Regex pattern denoting a legal name + */ public static final String LEGAL_NAME_PATTERN = LEGAL_CHAR_FOR_NAME_PATTERN + "*"; - /** regex pattern denoting a legal name, with wildcards */ - // public static final String LEGAL_NAME_WILD_PATTERN = LEGAL_CHAR_FOR_NAME_WILD_PATTERN + "*"; - } - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameParser.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameParser.java index e14b37295de..111ab993e56 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameParser.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/PathnameParser.java @@ -37,12 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation] -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ package org.glassfish.admin.amx.core; import java.util.ArrayList; @@ -55,6 +51,7 @@ import static org.glassfish.external.amx.AMX.*; import org.glassfish.external.arc.Stability; import org.glassfish.external.arc.Taxonomy; + /** Parses a pathname into parts.

@@ -62,12 +59,7 @@ The root part (leading "/") is not included in the parts list returned by {@link #parts}. */ @Taxonomy(stability = Stability.UNCOMMITTED) -public final class PathnameParser -{ - private static void debug(final Object o) - { - System.out.println("" + o); - } +public final class PathnameParser { private final char mDelim; @@ -83,7 +75,8 @@ private static void debug(final Object o) public static final class PathPart { - private final String mType, mName; + private final String mType; + private final String mName; public PathPart(final String type, final String name) { @@ -228,11 +221,6 @@ public String parentPath() */ private static final Pattern TYPE_SEARCH_PATTERN = Pattern.compile(LEGAL_TYPE_PATTERN + ".*"); - /** - This pattern finds a name up to the terminating SUBSCRIPT_RIGHT. - */ - private static final Pattern NAME_SEARCH_PATTERN = Pattern.compile("(" + LEGAL_NAME_PATTERN + ")" + SUBSCRIPT_RIGHT + ".*"); - /* a legal type, by itself */ private static final Pattern LEGAL_TYPE_PATTERN_COMPILED = Pattern.compile( LEGAL_TYPE_PATTERN ); @@ -252,11 +240,8 @@ private static boolean isValidName(final String type) /** */ - private void parse(final String path, final List parts) - { - //debug( "PathnameParser: parsing: " + path ); - if (path == null || path.length() == 0) - { + private void parse(final String path, final List parts) { + if (path == null || path.length() == 0) { throw new IllegalArgumentException(path); } String remaining = path; @@ -280,7 +265,6 @@ private void parse(final String path, final List parts) } final String type = matcher.group(1); - //debug( "PathnameParser, matched type: \"" + type + "\"" ); char matchChar; if (type.length() < remaining.length()) @@ -294,8 +278,6 @@ private void parse(final String path, final List parts) parts.add(part); break; } - //debug( "PathnameParser, match char: \"" + matchChar + "\"" ); - //debug( "PathnameParser, remaining: \"" + remaining + "\"" ); String name = null; if (matchChar == mNameLeft) @@ -318,16 +300,8 @@ private void parse(final String path, final List parts) final PathPart part = new PathPart(type, name); parts.add(part); - //debug( "PathnameParser, matched part: \"" + part + "\"" ); } - - /* - String s = ""; - for( final PathPart part : parts ){ - s = s + "{" + part + "}"; - } - debug( "FINAL PARSE for : " + path + " = " + s); - */ + } private List parse() @@ -371,8 +345,7 @@ public static String pathPart(final String type, final String name) final String namePart = (name == null) ? "" : SUBSCRIPT_LEFT + name + SUBSCRIPT_RIGHT; - final String part = pathPart(type) + namePart; - return part; + return pathPart(type) + namePart; } public static String pathPart(final String type) diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/Util.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/Util.java index cc53e9c601d..0e45eb3f782 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/Util.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/Util.java @@ -37,14 +37,14 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.core; import java.util.regex.Pattern; import org.glassfish.admin.amx.util.jmx.JMXUtil; -import org.glassfish.admin.amx.util.SetUtil; import org.glassfish.admin.amx.util.ClassUtil; -import org.glassfish.admin.amx.core.AMXMBeanMetadata; import static org.glassfish.external.amx.AMX.*; @@ -64,10 +64,6 @@ public final class Util { private static final String QUOTE_CHAR = "\""; - private static void debug(final String s) { - System.out.println(s); - } - public static String quoteIfNeeded(String name) { if(name.indexOf(':') > 1) { return ObjectName.quote(name); @@ -364,13 +360,6 @@ public static T getAMXNotificationValue( return theClass.cast(value); } - public static void sleep(final long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } - /** A safe way to cast to AMX. */ diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/AMXProxyHandler.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/AMXProxyHandler.java index 06480995a12..56fab57be92 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/AMXProxyHandler.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/AMXProxyHandler.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.core.proxy; import org.glassfish.admin.amx.annotation.ChildGetter; @@ -61,126 +61,93 @@ import static org.glassfish.external.amx.AMX.*; /** -@deprecated Extends MBeanProxyHandler by also supporting the functionality required of an AMX. + * @deprecated Extends MBeanProxyHandler by also supporting the functionality required of an AMX. */ @Deprecated @Taxonomy(stability = Stability.PRIVATE) -public final class AMXProxyHandler extends MBeanProxyHandler - implements AMXProxy, Extra -{ +public final class AMXProxyHandler extends MBeanProxyHandler implements AMXProxy, Extra { - private static void sdebug(final String s) - { - System.out.println(s); - } private final ObjectName mParentObjectName; private final String mName; - /** convert to specified class. */ - public T as(final Class intf) - { - if (this.getClass().isAssignableFrom(intf)) - { + /** + * convert to specified class. + */ + @Override + public T as(final Class intf) { + if (this.getClass().isAssignableFrom(intf)) { return intf.cast(this); } final T result = proxyFactory().getProxy(getObjectName(), getMBeanInfo(), intf); - if ( result == null ) - { - throw new IllegalStateException( "Proxy no longer valid for: " + objectName() ); + if (result == null) { + throw new IllegalStateException("Proxy no longer valid for: " + objectName()); } - - return result; - //throw new IllegalArgumentException( "Cannot convert " + getObjectName() + - // " to interface " + intf.getName() + ", interfaceName from Descriptor = " + interfaceName()); + return result; } - public Extra extra() - { + @Override + public Extra extra() { return this; } - public static AMXProxyHandler unwrap(final AMXProxy proxy) - { + public static AMXProxyHandler unwrap(final AMXProxy proxy) { return (AMXProxyHandler) Proxy.getInvocationHandler(proxy); } /** - Create a new AMX proxy. + * Create a new AMX proxy. */ - protected AMXProxyHandler( - final MBeanServerConnection conn, - final ObjectName objectName, - final MBeanInfo mbeanInfo) - throws IOException - { + protected AMXProxyHandler(final MBeanServerConnection conn, final ObjectName objectName, final MBeanInfo mbeanInfo) throws IOException { super(conn, objectName, mbeanInfo); - try - { + try { // one call, so one trip to the server - final AttributeList attrs = conn.getAttributes(objectName, new String[] - { - ATTR_NAME, ATTR_PARENT - }); + final AttributeList attrs = conn.getAttributes(objectName, new String[]{ + ATTR_NAME, ATTR_PARENT + }); final Map m = JMXUtil.attributeListToValueMap(attrs); mParentObjectName = (ObjectName) m.get(ATTR_PARENT); mName = (String) m.get(ATTR_NAME); - } - catch (final Exception e) - { + } catch (final Exception e) { throw new RuntimeException("Can't get Name and/or Parent attributes from " + objectName, e); } } private static final String GET = "get"; - public final static String ADD_NOTIFICATION_LISTENER = "addNotificationListener"; - public final static String REMOVE_NOTIFICATION_LISTENER = "removeNotificationListener"; - private final static String QUERY = "query"; + public static final String ADD_NOTIFICATION_LISTENER = "addNotificationListener"; + public static final String REMOVE_NOTIFICATION_LISTENER = "removeNotificationListener"; + private static final String QUERY = "query"; - - public final DomainRoot domainRootProxy() - { + public final DomainRoot domainRootProxy() { return proxyFactory().getDomainRootProxy(); } - + private static final String STRING = String.class.getName(); - private static final String[] EMPTY_SIG = new String[0]; - private static final String[] STRING_SIG = new String[] - { + private static final String[] STRING_SIG = new String[]{ STRING }; - protected T getProxy(final ObjectName objectName, final Class intf) - { + protected T getProxy(final ObjectName objectName, final Class intf) { return (proxyFactory().getProxy(objectName, intf)); } - protected AMXProxy getProxy(final ObjectName objectName) - { + protected AMXProxy getProxy(final ObjectName objectName) { return getProxy(objectName, AMXProxy.class); } - private Object invokeTarget( - final String methodName, - final Object[] args, - final String[] sig) - throws IOException, ReflectionException, InstanceNotFoundException, MBeanException, - AttributeNotFoundException - { + private Object invokeTarget(final String methodName, final Object[] args, final String[] sig) + throws IOException, ReflectionException, InstanceNotFoundException, MBeanException, AttributeNotFoundException { final int numArgs = args == null ? 0 : args.length; Object result = null; - if (numArgs == 0 && - methodName.startsWith(GET)) - { + if (numArgs == 0 + && methodName.startsWith(GET)) { final String attributeName = StringUtil.stripPrefix(methodName, GET); result = getMBeanServerConnection().getAttribute(getObjectName(), attributeName); - } - else - { + } else { result = getMBeanServerConnection().invoke(getObjectName(), methodName, args, sig); } @@ -188,17 +155,14 @@ private Object invokeTarget( } /** - Return true if the method is one that is requesting a single AMX object. - Such methods are client-side methods and do not operate on the target MBean. + * Return true if the method is one that is requesting a single AMX object. Such methods are client-side methods and do not operate on the target MBean. */ - protected static boolean isSingleProxyGetter(final Method method, final int argCount) - { + protected static boolean isSingleProxyGetter(final Method method, final int argCount) { boolean isProxyGetter = false; final String name = method.getName(); - if ((name.startsWith(GET) || name.startsWith(QUERY)) && - AMXProxy.class.isAssignableFrom(method.getReturnType())) - { + if ((name.startsWith(GET) || name.startsWith(QUERY)) + && AMXProxy.class.isAssignableFrom(method.getReturnType())) { isProxyGetter = true; } @@ -206,58 +170,41 @@ protected static boolean isSingleProxyGetter(final Method method, final int argC } /** - The method is one that requests a Proxy. The method could retrieve a real attribute, - but if there is no real Attribute, attempt to find a child of the matching type. + * The method is one that requests a Proxy. The method could retrieve a real attribute, but if there is no real Attribute, attempt to find a child of the + * matching type. */ - AMXProxy invokeSingleProxyGetter( - final Object myProxy, - final Method method, - final Object[] args) - throws IOException, ReflectionException, InstanceNotFoundException, MBeanException, - AttributeNotFoundException - { + AMXProxy invokeSingleProxyGetter(final Object myProxy, final Method method, final Object[] args) + throws IOException, ReflectionException, InstanceNotFoundException, MBeanException, AttributeNotFoundException { final String methodName = method.getName(); final int numArgs = (args == null) ? 0 : args.length; final Class returnClass = method.getReturnType().asSubclass(AMXProxy.class); ObjectName objectName = null; - if (numArgs == 0) - { - //System.out.println( "invokeSingleProxyGetter: intf = " + returnClass.getName() ); + if (numArgs == 0) { // If a real Attribute exists with this name then it takes priority final String attrName = JMXUtil.getAttributeName(method); - if (getAttributeInfo(attrName) != null) - { + if (getAttributeInfo(attrName) != null) { objectName = (ObjectName) invokeTarget(methodName, null, null); - } - else - { + } else { final String type = Util.deduceType(returnClass); - //System.out.println( "invokeSingleProxyGetter: type = " + type ); - final AMXProxy childProxy = child(type); objectName = childProxy == null ? null : childProxy.extra().objectName(); } - } - else - { + } else { objectName = (ObjectName) invokeTarget(methodName, args, STRING_SIG); } return objectName == null ? null : getProxy(objectName, returnClass); } - private static String toString(Object o) - { - //String result = o == null ? "null" : SmartStringifier.toString( o ); + private static String toString(Object o) { String result = "" + o; final int MAX_LENGTH = 256; - if (result.length() > MAX_LENGTH) - { + if (result.length() > MAX_LENGTH) { result = result.substring(0, MAX_LENGTH - 1) + "..."; } @@ -265,54 +212,77 @@ private static String toString(Object o) } private static final Map EMPTY_String_AMX = Collections.emptyMap(); - private final static Class[] NOTIFICATION_LISTENER_SIG1 = new Class[] - { + private static final Class[] NOTIFICATION_LISTENER_SIG1 = new Class[]{ NotificationListener.class }; - private final static Class[] NOTIFICATION_LISTENER_SIG2 = new Class[] - { + private static final Class[] NOTIFICATION_LISTENER_SIG2 = new Class[]{ NotificationListener.class, NotificationFilter.class, Object.class }; - /** Cached forever, parent ObjectName */ + /** + * Cached forever, parent ObjectName + */ private static final String GET_PARENT = GET + ATTR_PARENT; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_NAME_PROP = "nameProp"; private static final String METHOD_TYPE = "type"; private static final String METHOD_PARENT_PATH = "parentPath"; - /** proxy method */ - private static final String METHOD_CHILDREN = "children"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_CHILDREN_MAP = "childrenMap"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_CHILDREN_MAPS = "childrenMaps"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_CHILDREN_SET = "childrenSet"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_CHILD = "child"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_PARENT = "parent"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_OBJECTNAME = "objectName"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_EXTRA = "extra"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_AS = "as"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_VALID = "valid"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_ATTRIBUTES_MAP = "attributesMap"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_ATTRIBUTE_NAMES = "attributeNames"; - /** proxy method */ + /** + * proxy method + */ private static final String METHOD_PATHNAME = "path"; - + private static final String INVOKE_OPERATION = "invokeOp"; /** - These Attributes are handled specially. For example, J2EE_TYPE and - J2EE_NAME are part of the ObjectName. + * These Attributes are handled specially. For example, J2EE_TYPE and J2EE_NAME are part of the ObjectName. */ private static final Set SPECIAL_METHOD_NAMES = SetUtil.newUnmodifiableStringSet( GET_PARENT, @@ -335,541 +305,390 @@ private static String toString(Object o) REMOVE_NOTIFICATION_LISTENER); /** - Handle a "special" method; one that requires special handling and/or can - be dealt with on the client side and/or can be handled most efficiently - by special-casing it. + * Handle a "special" method; one that requires special handling and/or can be dealt with on the client side and/or can be handled most efficiently by + * special-casing it. */ private Object handleSpecialMethod( final Object myProxy, final Method method, final Object[] args) - throws ClassNotFoundException, JMException, IOException - { + throws ClassNotFoundException, JMException, IOException { final String methodName = method.getName(); final int numArgs = args == null ? 0 : args.length; Object result = null; boolean handled = false; - if (numArgs == 0) - { - handled = true; - if (methodName.equals(METHOD_PARENT)) - { - result = parent(); - } - else if (methodName.equals(GET_PARENT)) - { - result = parent() == null ? null : parent().extra().objectName(); - } - else if (methodName.equals(METHOD_CHILDREN_SET)) - { - result = childrenSet(); - } - else if (methodName.equals(METHOD_CHILDREN_MAPS)) - { - result = childrenMaps(); - } - else if (methodName.equals(METHOD_EXTRA)) - { - result = this; - } - else if (methodName.equals(METHOD_OBJECTNAME)) - { - result = getObjectName(); - } - else if (methodName.equals(METHOD_NAME_PROP)) - { - result = getObjectName().getKeyProperty(NAME_KEY); - } - else if (methodName.equals(METHOD_TYPE)) - { - result = type(); - } - else if (methodName.equals(METHOD_PARENT_PATH)) - { - result = parentPath(); - } - else if (methodName.equals(METHOD_ATTRIBUTES_MAP)) - { - result = attributesMap(); - } - else if (methodName.equals(METHOD_ATTRIBUTE_NAMES)) - { - result = attributeNames(); - } - else if (methodName.equals(METHOD_VALID)) - { - result = valid(); - } - else if (methodName.equals(METHOD_PATHNAME)) - { - result = path(); - } - else - { - handled = false; - } - } - else if (numArgs == 1) - { - handled = true; - final Object arg = args[0]; - - if (methodName.equals("equals")) - { - result = equals(arg); - } - else if (methodName.equals(METHOD_ATTRIBUTES_MAP)) - { - result = attributesMap( TypeCast.checkedStringSet( Set.class.cast(arg) ) ); - } - else if (methodName.equals(METHOD_CHILDREN_MAP)) - { - if (arg instanceof String) - { - result = childrenMap((String) arg); - } - else if (arg instanceof Class) - { - result = childrenMap((Class) arg); - } - else - { + switch (numArgs) { + case 0: + handled = true; + result = objectFromMethodName(methodName); + break; + case 1: + handled = true; + final Object arg = args[0]; + if (methodName.equals("equals")) { + result = equals(arg); + } else if (methodName.equals(METHOD_ATTRIBUTES_MAP)) { + result = attributesMap(TypeCast.checkedStringSet(Set.class.cast(arg))); + } else if (methodName.equals(METHOD_CHILDREN_MAP)) { + if (arg instanceof String) { + result = childrenMap((String) arg); + } else if (arg instanceof Class) { + result = childrenMap((Class) arg); + } else { + handled = false; + } + } else if (methodName.equals(METHOD_CHILD)) { + if (arg instanceof String) { + result = child((String) arg); + } else if (arg instanceof Class) { + result = child((Class) arg); + } else { + handled = false; + } + } else if (methodName.equals(METHOD_AS) && (arg instanceof Class)) { + result = as((Class) arg); + } else { handled = false; } - } - else if (methodName.equals(METHOD_CHILD)) - { - if (arg instanceof String) - { - result = child((String) arg); - } - else if (arg instanceof Class) - { - result = child((Class) arg); - } - else - { + break; + default: + handled = true; + final Class[] signature = method.getParameterTypes(); + if (methodName.equals(ADD_NOTIFICATION_LISTENER) + && (ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG1, signature) + || ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG2, signature))) { + addNotificationListener(args); + } else if (methodName.equals(REMOVE_NOTIFICATION_LISTENER) + && (ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG1, signature) + || ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG2, signature))) { + removeNotificationListener(args); + } else { handled = false; } - } - else if (methodName.equals(METHOD_AS) && (arg instanceof Class)) - { - result = as((Class) arg); - } - else - { - handled = false; - } - } - else - { - handled = true; - final Class[] signature = method.getParameterTypes(); - - if (methodName.equals(ADD_NOTIFICATION_LISTENER) && - (ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG1, signature) || - ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG2, signature))) - { - addNotificationListener(args); - } - else if (methodName.equals(REMOVE_NOTIFICATION_LISTENER) && - (ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG1, signature) || - ClassUtil.sigsEqual(NOTIFICATION_LISTENER_SIG2, signature))) - { - removeNotificationListener(args); - } - else - { - handled = false; - } + break; } - if (!handled) - { + if (!handled) { assert (false); throw new RuntimeException("unknown method: " + method); } return (result); } - - public final Object invoke( - final Object myProxy, - final Method method, - final Object[] args) - throws java.lang.Throwable - { - try - { - //System.out.println( "invoking: " + method.getName() ); + + private Object objectFromMethodName(String methodName) { + switch (methodName) { + case METHOD_PARENT: + return parent(); + case GET_PARENT: + return parent() == null ? null : parent().extra().objectName(); + case METHOD_CHILDREN_SET: + return childrenSet(); + case METHOD_CHILDREN_MAPS: + return childrenMaps(); + case METHOD_EXTRA: + return this; + case METHOD_OBJECTNAME: + return getObjectName(); + case METHOD_NAME_PROP: + return getObjectName().getKeyProperty(NAME_KEY); + case METHOD_TYPE: + return type(); + case METHOD_PARENT_PATH: + return parentPath(); + case METHOD_ATTRIBUTES_MAP: + return attributesMap(); + case METHOD_ATTRIBUTE_NAMES: + return attributeNames(); + case METHOD_VALID: + return valid(); + case METHOD_PATHNAME: + return path(); + default: + throw new UnknownMethodException(methodName); + } + } + + @Override + public final Object invoke(final Object myProxy, final Method method, final Object[] args) throws Throwable { + try { final Object result = _invoke(myProxy, method, args); - // System.out.println( "invoke: " + method.getName() + ", result = " + result ); - - assert (result == null || - ClassUtil.isPrimitiveClass(method.getReturnType()) || - method.getReturnType().isAssignableFrom(result.getClass())) : - method.getName() + ": result of type " + result.getClass().getName() + - " not assignable to " + method.getReturnType().getName() + ", " + - "interfaces: " + toString(result.getClass().getInterfaces()) + - ", ObjectName = " + getObjectName(); + assert (result == null + || ClassUtil.isPrimitiveClass(method.getReturnType()) + || method.getReturnType().isAssignableFrom(result.getClass())) : + method.getName() + ": result of type " + result.getClass().getName() + + " not assignable to " + method.getReturnType().getName() + ", " + + "interfaces: " + toString(result.getClass().getInterfaces()) + + ", ObjectName = " + getObjectName(); - //System.out.println( "invoke: " + method.getName() + ", return result = " + result ); return result; - } - catch (IOException e) - { + } catch (IOException e) { proxyFactory().checkConnection(); throw e; - } - catch (InstanceNotFoundException e) - { + } catch (InstanceNotFoundException e) { isValid(); throw e; } } - - public Object invokeOp( final String operationName) - { - try - { + + @Override + public Object invokeOp(final String operationName) { + try { return getMBeanServerConnection().invoke(getObjectName(), operationName, null, null); - } - catch( final Exception e ) - { - throw new RuntimeException( "Exception invoking " + operationName, e ); + } catch (final Exception e) { + throw new RuntimeException("Exception invoking " + operationName, e); } } - - public Object invokeOp( final String operationName, final Object[] args, final String[] signature ) - { - try - { + + @Override + public Object invokeOp(final String operationName, final Object[] args, final String[] signature) { + try { return getMBeanServerConnection().invoke(getObjectName(), operationName, args, signature); - } - catch( final Exception e ) - { - throw new RuntimeException( "Exception invoking " + operationName, e ); + } catch (final Exception e) { + throw new RuntimeException("Exception invoking " + operationName, e); } } - - private boolean isChildGetter( final Method m, final Object[] args) - { + + private boolean isChildGetter(final Method m, final Object[] args) { boolean isChildGetter = false; - if ( args == null || args.length == 0 ) - { + if (args == null || args.length == 0) { final ChildGetter getter = m.getAnnotation(ChildGetter.class); isChildGetter = getter != null; } return isChildGetter; } - - private String deduceChildType( final Method m ) - { + + private String deduceChildType(final Method m) { String type = null; final ChildGetter getter = m.getAnnotation(ChildGetter.class); - if ( getter != null ) - { + if (getter != null) { type = getter.type(); } - - if ( type == null || type.length() == 0 ) - { + + if (type == null || type.length() == 0) { String temp = m.getName(); final String GET = "get"; - if ( temp.startsWith(GET) ) - { - temp = temp.substring( GET.length() ); + if (temp.startsWith(GET)) { + temp = temp.substring(GET.length()); } type = Util.typeFromName(temp); } - + return type; } - + private ObjectName[] handleChildGetter( - final Method method, - final Object[] args) - { + final Method method, + final Object[] args) { final String type = deduceChildType(method); - + final List childrenList = childrenOfType(type); - - final ObjectName[] children = new ObjectName[ childrenList.size() ]; - childrenList.toArray( children ); - + + final ObjectName[] children = new ObjectName[childrenList.size()]; + childrenList.toArray(children); + return children; } - + /** - Convert an ObjectName[] to the proxy-based Map/Set/List/[] result type + * Convert an ObjectName[] to the proxy-based Map/Set/List/[] result type */ - Object - autoConvert(final Method method, final ObjectName[] items ) - { - //debug( "_invoke: trying to make ObjectName[] into proxies for " + method.getName() ); - final Class returnType = method.getReturnType(); + Object autoConvert(final Method method, final ObjectName[] items) { + final Class returnType = method.getReturnType(); Class proxyClass = AMXProxy.class; - + Object result = items; // fallback is to return the original ObjectName[] - - if ( returnType.isArray() ) - { + + if (returnType.isArray()) { final Class componentType = returnType.getComponentType(); - if ( AMXProxy.class.isAssignableFrom(componentType) ) - { + if (AMXProxy.class.isAssignableFrom(componentType)) { proxyClass = componentType.asSubclass(AMXProxy.class); final List proxyList = proxyFactory().toProxyList(items, proxyClass); - final AMXProxy[] proxies = (AMXProxy[])Array.newInstance( proxyClass, proxyList.size() ); + final AMXProxy[] proxies = (AMXProxy[]) Array.newInstance(proxyClass, proxyList.size()); proxyList.toArray(proxies); result = proxies; } - } - else - { - if (method.getGenericReturnType() instanceof ParameterizedType) - { + } else { + if (method.getGenericReturnType() instanceof ParameterizedType) { proxyClass = getProxyClass((ParameterizedType) method.getGenericReturnType()); } - + // Note that specialized sub-types of Set/List/Map, are *not* supported; // the method must be declared with Set/List/Map. This is intentional // to discourage use of HashMap, LinkedList, ArrayList, TreeMap, etc. - if (Set.class.isAssignableFrom(returnType)) - { + if (Set.class.isAssignableFrom(returnType)) { result = proxyFactory().toProxySet(items, proxyClass); - } - else if (List.class.isAssignableFrom(returnType)) - { + } else if (List.class.isAssignableFrom(returnType)) { result = proxyFactory().toProxyList(items, proxyClass); - } - else if (Map.class.isAssignableFrom(returnType)) - { + } else if (Map.class.isAssignableFrom(returnType)) { result = proxyFactory().toProxyMap(items, proxyClass); } } - + return result; } - - private List - tentativeObjectNameList(final Collection items) - { + + private List tentativeObjectNameList(final Collection items) { final List objectNames = new ArrayList(); // verify that all items are of type ObjectName // do NOT throw an exception, we just want to check, not require it. - for( final Object item : items ) - { - if ( ! (item instanceof ObjectName) ) - { + for (final Object item : items) { + if (!(item instanceof ObjectName)) { return null; } - objectNames.add((ObjectName)item); + objectNames.add((ObjectName) item); } return objectNames; } - + /** - Convert an Map/Set/List to the proxy-based Map/Set/List/[] result type + * Convert an Map/Set/List to the proxy-based Map/Set/List/[] result type */ - Object - autoConvertCollection(final Method method, final Object itemsIn) - { + Object autoConvertCollection(final Method method, final Object itemsIn) { Object result = itemsIn; // fallback is to return the original result - - //System.out.println( "autoConvertCollection() for " + method.getName() ); + final Class returnType = method.getReturnType(); Class proxyClass = AMXProxy.class; - if (method.getGenericReturnType() instanceof ParameterizedType) - { + if (method.getGenericReturnType() instanceof ParameterizedType) { proxyClass = getProxyClass((ParameterizedType) method.getGenericReturnType()); } - + // definitely do not want to auto convert to proxy if it's List (for example) - if ( proxyClass == null || ! AMXProxy.class.isAssignableFrom(proxyClass) ) - { + if (proxyClass == null || !AMXProxy.class.isAssignableFrom(proxyClass)) { return itemsIn; } - - if ( Collection.class.isAssignableFrom(returnType) && (itemsIn instanceof Collection) ) - { - final List objectNames = tentativeObjectNameList((Collection)itemsIn); - if ( objectNames != null ) - { + + if (Collection.class.isAssignableFrom(returnType) && (itemsIn instanceof Collection)) { + final List objectNames = tentativeObjectNameList((Collection) itemsIn); + if (objectNames != null) { final ObjectName[] objectNamesA = new ObjectName[objectNames.size()]; objectNames.toArray(objectNamesA); - if (Set.class.isAssignableFrom(returnType)) - { + if (Set.class.isAssignableFrom(returnType)) { result = proxyFactory().toProxySet(objectNamesA, proxyClass); - } - else if (List.class.isAssignableFrom(returnType)) - { + } else if (List.class.isAssignableFrom(returnType)) { result = proxyFactory().toProxyList(objectNamesA, proxyClass); } } - } - else if ( Map.class.isAssignableFrom(returnType) && (itemsIn instanceof Map) ) - { - final Map m = (Map)itemsIn; - final Map proxies = new HashMap(); + } else if (Map.class.isAssignableFrom(returnType) && (itemsIn instanceof Map)) { + final Map m = (Map) itemsIn; + final Map proxies = new HashMap(); boolean ok = true; - for( final Object meo : m.entrySet() ) - { - Map.Entry me = (Map.Entry)meo; - if ( ! (me.getKey() instanceof String) ) - { + for (final Object meo : m.entrySet()) { + Map.Entry me = (Map.Entry) meo; + if (!(me.getKey() instanceof String)) { ok = false; break; } final Object value = me.getValue(); - if ( ! (value instanceof ObjectName) ) - { + if (!(value instanceof ObjectName)) { ok = false; break; } - proxies.put( (String)me.getKey(), proxyFactory().getProxy((ObjectName)value, proxyClass )); + proxies.put((String) me.getKey(), proxyFactory().getProxy((ObjectName) value, proxyClass)); } - - if ( ok ) - { + + if (ok) { result = proxies; } } - + return result; } - - protected Object _invoke( - final Object myProxy, - final Method method, - final Object[] argsIn) - throws java.lang.Throwable - { + protected Object _invoke(final Object myProxy, final Method method, final Object[] argsIn) throws Throwable { final int numArgs = argsIn == null ? 0 : argsIn.length; - + // auto-convert any AMXProxy to ObjectName (Lists, Maps, etc thereof are caller's design headache) - final Object[] args = argsIn == null ? new Object[0] : new Object[ argsIn.length ]; - for( int i = 0; i < numArgs; ++i ) - { + final Object[] args = argsIn == null ? new Object[0] : new Object[argsIn.length]; + for (int i = 0; i < numArgs; ++i) { args[i] = argsIn[i]; // leave alone by default - if ( args[i] instanceof AMXProxy ) - { - args[i] = ((AMXProxy)argsIn[i]).objectName(); + if (args[i] instanceof AMXProxy) { + args[i] = ((AMXProxy) argsIn[i]).objectName(); } } - + debugMethod(method.getName(), args); Object result = null; final String methodName = method.getName(); - //System.out.println( "_invoke: " + methodName + " on " + objectName() ); - if (SPECIAL_METHOD_NAMES.contains(methodName)) - { + if (SPECIAL_METHOD_NAMES.contains(methodName)) { result = handleSpecialMethod(myProxy, method, args); - } - else if ( isChildGetter(method, args) ) - { - result = handleChildGetter(method,args); - } - else if ( INVOKE_OPERATION.equals(methodName) ) - { - if ( args.length == 1 ) - { - result = invokeOp( (String)args[0] ); - } - else if ( args.length == 3 ) - { - result = invokeOp( (String)args[0], (Object[])args[1], (String[])args[2] ); - } - else - { - throw new IllegalArgumentException(); + } else if (isChildGetter(method, args)) { + result = handleChildGetter(method, args); + } else if (INVOKE_OPERATION.equals(methodName)) { + switch (args.length) { + case 1: + result = invokeOp((String) args[0]); + break; + case 3: + result = invokeOp((String) args[0], (Object[]) args[1], (String[]) args[2]); + break; + default: + throw new IllegalArgumentException(); } - } - else - { - //System.out.println( "_invoke: (not handled): " + methodName + " on " + objectName() ); - if (isSingleProxyGetter(method, numArgs)) - { + } else { + if (isSingleProxyGetter(method, numArgs)) { result = invokeSingleProxyGetter(myProxy, method, args); - } - else - { + } else { result = super.invoke(myProxy, method, args); } } // AUTO-CONVERT certain return types to proxy from ObjectName, ObjectName[] - final Class returnType = method.getReturnType(); - if ((result instanceof ObjectName) && - AMXProxy.class.isAssignableFrom(returnType)) - { + if ((result instanceof ObjectName) + && AMXProxy.class.isAssignableFrom(returnType)) { result = getProxy((ObjectName) result, returnType.asSubclass(AMXProxy.class)); - } - else if (result != null && - result instanceof ObjectName[]) - { - result = autoConvert( method, (ObjectName[]) result ); - } - else if ( result != null && ( (result instanceof Collection) || (result instanceof Map) ) ) - { - result = autoConvertCollection( method, result ); + } else if (result != null + && result instanceof ObjectName[]) { + result = autoConvert(method, (ObjectName[]) result); + } else if (result != null && ((result instanceof Collection) || (result instanceof Map))) { + result = autoConvertCollection(method, result); } - //System.out.println( "_invoke: done: result class is " + result.getClass().getName() ); return (result); } - private Class getProxyClass(final ParameterizedType pt) - { + private Class getProxyClass(final ParameterizedType pt) { Class intf = null; final Type[] argTypes = pt.getActualTypeArguments(); - if (argTypes.length >= 1) - { + if (argTypes.length >= 1) { final Type argType = argTypes[argTypes.length - 1]; - if ((argType instanceof Class) && AMXProxy.class.isAssignableFrom((Class) argType)) - { + if ((argType instanceof Class) && AMXProxy.class.isAssignableFrom((Class) argType)) { intf = ((Class) argType).asSubclass(AMXProxy.class); } } - if (intf == null) - { + if (intf == null) { intf = AMXProxy.class; } return intf; } protected void addNotificationListener(final Object[] args) - throws IOException, InstanceNotFoundException - { - final NotificationListener listener = (NotificationListener) args[ 0]; - final NotificationFilter filter = (NotificationFilter) (args.length <= 1 ? null : args[ 1]); - final Object handback = args.length <= 1 ? null : args[ 2]; + throws IOException, InstanceNotFoundException { + final NotificationListener listener = (NotificationListener) args[0]; + final NotificationFilter filter = (NotificationFilter) (args.length <= 1 ? null : args[1]); + final Object handback = args.length <= 1 ? null : args[2]; getMBeanServerConnection().addNotificationListener( getObjectName(), listener, filter, handback); } protected void removeNotificationListener(final Object[] args) - throws IOException, InstanceNotFoundException, ListenerNotFoundException - { - final NotificationListener listener = (NotificationListener) args[ 0]; + throws IOException, InstanceNotFoundException, ListenerNotFoundException { + final NotificationListener listener = (NotificationListener) args[0]; // important: // this form removes the same listener registered with different filters and/or handbacks - if (args.length == 1) - { + if (args.length == 1) { getMBeanServerConnection().removeNotificationListener(getObjectName(), listener); - } - else - { - final NotificationFilter filter = (NotificationFilter) args[ 1]; - final Object handback = args[ 2]; + } else { + final NotificationFilter filter = (NotificationFilter) args[1]; + final Object handback = args[2]; getMBeanServerConnection().removeNotificationListener( getObjectName(), listener, filter, handback); @@ -877,100 +696,95 @@ protected void removeNotificationListener(final Object[] args) } //----------------------------------- - public static String interfaceName(final MBeanInfo info) - { + public static String interfaceName(final MBeanInfo info) { final Object value = info.getDescriptor().getFieldValue(DESC_STD_INTERFACE_NAME); return (String) value; } @Override - public String interfaceName() - { + public String interfaceName() { String name = super.interfaceName(); - if (name == null) - { + if (name == null) { name = AMXProxy.class.getName(); } return name; } - public static String genericInterfaceName(final MBeanInfo info) - { + public static String genericInterfaceName(final MBeanInfo info) { final Object value = info.getDescriptor().getFieldValue(DESC_GENERIC_INTERFACE_NAME); return (String) value; } - public String genericInterfaceName() - { + + public String genericInterfaceName() { return genericInterfaceName(mbeanInfo()); } - public Class genericInterface() - { + @Override + public Class genericInterface() { return ProxyFactory.genericInterface(mbeanInfo()); } - public boolean valid() - { + @Override + public boolean valid() { return isValid(); } - public ProxyFactory proxyFactory() - { + @Override + public ProxyFactory proxyFactory() { return (ProxyFactory.getInstance(getMBeanServerConnection())); } - public MBeanServerConnection mbeanServerConnection() - { + @Override + public MBeanServerConnection mbeanServerConnection() { return getMBeanServerConnection(); } - public ObjectName objectName() - { + @Override + public ObjectName objectName() { return getObjectName(); } - public String nameProp() - { + @Override + public String nameProp() { // name as found in the ObjectName return Util.getNameProp(getObjectName()); } - public String parentPath() - { + @Override + public String parentPath() { return Util.unquoteIfNeeded(getObjectName().getKeyProperty(PARENT_PATH_KEY)); } - public String type() - { + @Override + public String type() { return Util.getTypeProp(getObjectName()); } - public String getName() - { + @Override + public String getName() { // internal *unquoted* name, but we consider it invariant once fetched return mName; } - public ObjectName getParent() - { + @Override + public ObjectName getParent() { return mParentObjectName; } - public AMXProxy parent() - { - if ( mParentObjectName == null ) return null; - - final AMXProxy proxy = proxyFactory().getProxy(mParentObjectName); - - return proxy; + @Override + public AMXProxy parent() { + if (mParentObjectName == null) { + return null; + } + + return proxyFactory().getProxy(mParentObjectName); } - public String path() - { + @Override + public String path() { // special case DomainRoot, which has no parent - if (getParent() == null) - { + if (getParent() == null) { return DomainRoot.PATH; } @@ -981,18 +795,14 @@ public String path() return PathnameParser.path(parentPath, type, singleton() ? null : Util.getNameProp(on)); } - public ObjectName[] getChildren() - { + @Override + public ObjectName[] getChildren() { ObjectName[] objectNames = null; - try - { + try { objectNames = (ObjectName[]) getAttributeNoThrow(ATTR_CHILDREN); - } - catch (final Exception e) - { + } catch (final Exception e) { final Throwable t = ExceptionUtil.getRootCause(e); - if (!(t instanceof AttributeNotFoundException)) - { + if (!(t instanceof AttributeNotFoundException)) { throw new RuntimeException("Could not get Children attribute", e); } } @@ -1000,79 +810,66 @@ public ObjectName[] getChildren() } /** - Returns an array of children, including an empty array if there are none, but children - are possible. Returns null if children are not possible. + * Returns an array of children, including an empty array if there are none, but children are possible. Returns null if children are not possible. */ - public Set childrenSet() - { + @Override + public Set childrenSet() { return childrenSet(getChildren()); } - public Set childrenSet(final ObjectName[] objectNames) - { + public Set childrenSet(final ObjectName[] objectNames) { return objectNames == null ? null : SetUtil.newSet(proxyFactory().toProxy(objectNames)); } - public Set childrenTypes(final ObjectName[] objectNames) - { + public Set childrenTypes(final ObjectName[] objectNames) { final Set types = new HashSet(); - for (final ObjectName o : objectNames) - { + for (final ObjectName o : objectNames) { final String type = Util.getTypeProp(o); types.add(type); } return types; } - public Map childrenMap(final String type) - { + @Override + public Map childrenMap(final String type) { return childrenMap(type, AMXProxy.class); } - public Map childrenMap(final Class intf) - { - if (!intf.isInterface()) - { + @Override + public Map childrenMap(final Class intf) { + if (!intf.isInterface()) { throw new IllegalArgumentException("" + intf); } return childrenMap(Util.deduceType(intf), intf); } - private List childrenOfType(final String type) - { + private List childrenOfType(final String type) { final ObjectName[] objectNames = getChildren(); - if (objectNames == null) - { + if (objectNames == null) { return Collections.emptyList(); } - + final List items = new ArrayList(); - for (final ObjectName objectName : objectNames) - { - if (Util.getTypeProp(objectName).equals(type)) - { + for (final ObjectName objectName : objectNames) { + if (Util.getTypeProp(objectName).equals(type)) { items.add(objectName); } } return items; } - - public Map childrenMap(final String type, final Class intf) - { + + public Map childrenMap(final String type, final Class intf) { final Map m = new HashMap(); - for (final ObjectName objectName : childrenOfType(type)) - { - m.put( Util.unquoteIfNeeded(Util.getNameProp(objectName)), getProxy(objectName, intf)); + for (final ObjectName objectName : childrenOfType(type)) { + m.put(Util.unquoteIfNeeded(Util.getNameProp(objectName)), getProxy(objectName, intf)); } return m; } - public Map> childrenMaps() - { + public Map> childrenMaps() { final ObjectName[] children = getChildren(); - if (children == null) - { + if (children == null) { return null; } @@ -1080,73 +877,60 @@ public Map> childrenMaps() final Map> maps = new HashMap>(); final Set types = childrenTypes(children); - for (final String type : types) - { + for (final String type : types) { maps.put(type, new HashMap()); } - for (final AMXProxy proxy : childrenSet) - { - final Map m = maps.get( proxy.type() ); + for (final AMXProxy proxy : childrenSet) { + final Map m = maps.get(proxy.type()); m.put(proxy.nameProp(), proxy); } return maps; } - public Set childrenSet(final String type, final Class intf) - { + public Set childrenSet(final String type, final Class intf) { final Map m = childrenMap(type, intf); return new HashSet(m.values()); } - public AMXProxy child(final String type) - { + @Override + public AMXProxy child(final String type) { return child(type, AMXProxy.class); } - public T child(final Class intf) - { + @Override + public T child(final Class intf) { final String type = Util.deduceType(intf); - //sdebug( "Deduced type of " + intf.getName() + " = " + type ); return child(type, intf); } - public T child(final String type, final Class intf) - { - //sdebug( "Child " + type + " has interface " + intf.getName() ); + public T child(final String type, final Class intf) { final Map children = childrenMap(type, intf); - if (children.size() == 0) - { + if (children.isEmpty()) { return null; } - if (children.size() > 1) - { + if (children.size() > 1) { throw new IllegalArgumentException("Not a singleton: " + type); } final T child = children.values().iterator().next(); - if (!child.extra().singleton()) - { + if (!child.extra().singleton()) { throw new IllegalArgumentException("Not a singleton: " + type); } return child; } - public T child(final String type, final String name, final Class intf) - { + public T child(final String type, final String name, final Class intf) { final Set children = childrenSet(); - if (children == null) - { + if (children == null) { return null; } T child = null; - for (final AMXProxy c : children) - { + for (final AMXProxy c : children) { final ObjectName objectName = c.extra().objectName(); - if (Util.getTypeProp(objectName).equals(type) && Util.getNameProp(objectName).equals(name)) - { + if (Util.getTypeProp(objectName).equals(type) && Util.getNameProp(objectName).equals(name)) { child = c.as(intf); break; } @@ -1154,145 +938,135 @@ public T child(final String type, final String name, final return child; } - public final MBeanInfo mbeanInfo() - { + @Override + public final MBeanInfo mbeanInfo() { return getMBeanInfo(); } - - - public Map attributesMap( final Set attrNames ) - { - try - { + + @Override + public Map attributesMap(final Set attrNames) { + try { final String[] namesArray = attrNames.toArray(new String[attrNames.size()]); final AttributeList attrs = getAttributes(namesArray); return JMXUtil.attributeListToValueMap(attrs); - } - catch (Exception e) - { + } catch (Exception e) { throw new RuntimeException(e); } } - public Map attributesMap() - { - return attributesMap( attributeNames() ); + + @Override + public Map attributesMap() { + return attributesMap(attributeNames()); } - public MBeanAttributeInfo getAttributeInfo(final String name) - { - for (final MBeanAttributeInfo attrInfo : getMBeanInfo().getAttributes()) - { - if (attrInfo.getName().equals(name)) - { + public MBeanAttributeInfo getAttributeInfo(final String name) { + for (final MBeanAttributeInfo attrInfo : getMBeanInfo().getAttributes()) { + if (attrInfo.getName().equals(name)) { return attrInfo; } } return null; } - public Set attributeNames() - { + @Override + public Set attributeNames() { final String[] names = JMXUtil.getAttributeNames(getMBeanInfo().getAttributes()); return SetUtil.newStringSet(names); } - public static T getDescriptorField(final MBeanInfo info, final String name, final T defaultValue) - { + public static T getDescriptorField(final MBeanInfo info, final String name, final T defaultValue) { T value = (T) info.getDescriptor().getFieldValue(name); - if (value == null) - { + if (value == null) { value = defaultValue; } return value; } - public static boolean singleton(final MBeanInfo info) - { + public static boolean singleton(final MBeanInfo info) { return getDescriptorField(info, DESC_IS_SINGLETON, Boolean.FALSE); } - - public static boolean globalSingleton(final MBeanInfo info) - { + + public static boolean globalSingleton(final MBeanInfo info) { return getDescriptorField(info, DESC_IS_GLOBAL_SINGLETON, Boolean.FALSE); } - protected T getDescriptorField(final String name, final T defaultValue) - { + protected T getDescriptorField(final String name, final T defaultValue) { return getDescriptorField(getMBeanInfo(), name, defaultValue); } - public boolean singleton() - { + @Override + public boolean singleton() { return getDescriptorField(DESC_IS_SINGLETON, Boolean.FALSE); } - public boolean globalSingleton() - { + @Override + public boolean globalSingleton() { return getDescriptorField(DESC_IS_GLOBAL_SINGLETON, Boolean.FALSE); } - public String group() - { + @Override + public String group() { return getDescriptorField(DESC_GROUP, GROUP_OTHER); } - public boolean supportsAdoption() - { + @Override + public boolean supportsAdoption() { return getDescriptorField(DESC_SUPPORTS_ADOPTION, Boolean.FALSE); } private static final String[] EMPTY_STRINGS = new String[0]; - public String[] subTypes() - { + @Override + public String[] subTypes() { return getDescriptorField(DESC_SUB_TYPES, EMPTY_STRINGS); } - + + @Override public String java() { - final Tools tools = domainRootProxy().getTools(); - return tools.java( getObjectName() ); + final Tools tools = domainRootProxy().getTools(); + return tools.java(getObjectName()); } - + + @Override public Descriptor descriptor() { return getMBeanInfo().getDescriptor(); } - + + @Override public MBeanAttributeInfo attributeInfo(final String attrName) { - for( final MBeanAttributeInfo info: getMBeanInfo().getAttributes() ) - { - if ( info.getName().equals(attrName) ) - { + for (final MBeanAttributeInfo info : getMBeanInfo().getAttributes()) { + if (info.getName().equals(attrName)) { return info; } } return null; } - + @Override public MBeanOperationInfo operationInfo(final String operationName) { - for( final MBeanOperationInfo info: getMBeanInfo().getOperations() ) - { - if ( info.getName().equals(operationName) ) - { + for (final MBeanOperationInfo info : getMBeanInfo().getOperations()) { + if (info.getName().equals(operationName)) { return info; } } return null; } - + @Override - public boolean equals(final Object rhs) - { + public boolean equals(final Object rhs) { return super.equals(rhs); } @Override - public int hashCode() { + public int hashCode() { return super.hashCode(); } + + class UnknownMethodException extends RuntimeException { + + public UnknownMethodException(String method) { + super("Unknown method: " + method); + } + + } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/ProxyFactory.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/ProxyFactory.java index 50486a21b1c..eacaed44c3f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/ProxyFactory.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/core/proxy/ProxyFactory.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.core.proxy; import org.glassfish.admin.amx.base.DomainRoot; @@ -45,7 +47,6 @@ import org.glassfish.admin.amx.core.Util; import org.glassfish.admin.amx.util.AMXDebugHelper; import org.glassfish.admin.amx.util.ExceptionUtil; -import org.glassfish.admin.amx.util.StringUtil; import org.glassfish.admin.amx.util.jmx.JMXUtil; import org.glassfish.external.amx.AMXGlassfish; import org.glassfish.external.arc.Stability; @@ -63,7 +64,6 @@ import static org.glassfish.external.amx.AMX.DESC_STD_IMMUTABLE_INFO; import static org.glassfish.external.amx.AMX.NAME_KEY; -//import org.glassfish.api.amx.AMXUtil; /** * @deprecated Factory for {@link AMXProxy} proxies. */ @@ -86,9 +86,9 @@ public final class ProxyFactory implements NotificationListener { new AMXDebugHelper(ProxyFactory.class.getName()); private static void debug(final Object... args) { - //mDebug.println( args ); - System.out.println(StringUtil.toString(", ", args)); + mDebug.println( args ); } + private static final Map INSTANCES = Collections.synchronizedMap(new HashMap()); @@ -154,12 +154,11 @@ public boolean checkConnection() { try { getMBeanServerConnection().isRegistered(JMXUtil.getMBeanServerDelegateObjectName()); - connectionGood = true; + return true; } catch (Exception e) { connectionBad(); + return false; } - - return (connectionGood); } void notifsLost() { @@ -172,9 +171,8 @@ void notifsLost() { * internally as callback for {@link javax.management.NotificationListener}. * DO NOT CALL THIS METHOD. */ - public void handleNotification( - final Notification notifIn, - final Object handback) { + @Override + public void handleNotification(final Notification notifIn, final Object handback) { final String type = notifIn.getType(); if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) { @@ -192,20 +190,15 @@ public void handleNotification( debug("ProxyFactory.handleNotification: UNKNOWN notification: ", notifIn); } } - private final static String DOMAIN_ROOT_KEY = "DomainRoot"; - public DomainRoot createDomainRoot() - throws IOException { + public DomainRoot createDomainRoot() { return (mDomainRoot); } - public DomainRoot initDomainRoot() - throws IOException { + public DomainRoot initDomainRoot() throws IOException { final ObjectName domainRootObjectName = getDomainRootObjectName(); - final DomainRoot dr = getProxy(domainRootObjectName, DomainRoot.class); - - return (dr); + return getProxy(domainRootObjectName, DomainRoot.class); } /** @@ -277,9 +270,7 @@ public static ProxyFactory getInstance(final MBeanServerConnection conn) { * @param useMBeanServerID use the MBeanServerID to determine if it's the * same server */ - public static synchronized ProxyFactory getInstance( - final MBeanServerConnection conn, - final boolean useMBeanServerID) { + public static synchronized ProxyFactory getInstance(final MBeanServerConnection conn, final boolean useMBeanServerID) { ProxyFactory instance = findInstance(conn); if (instance == null) { @@ -292,7 +283,6 @@ public static synchronized ProxyFactory getInstance( } if (instance == null) { - //debug( "Creating new ProxyFactory for ConnectionSource / conn", connSource, conn ); instance = new ProxyFactory(conn); INSTANCES.put(conn, instance); } @@ -392,8 +382,7 @@ public T getProxy( return null; } - final T proxy = getProxy(objectName, info, intf); - return proxy; + return getProxy(objectName, info, intf); } /** @@ -406,8 +395,7 @@ public AMXProxy getProxy(final ObjectName objectName) { } final Class intf = genericInterface(info); - final AMXProxy proxy = getProxy(objectName, info, intf); - return proxy; + return getProxy(objectName, info, intf); } public static Class genericInterface(final MBeanInfo info) { @@ -434,11 +422,7 @@ public static Class genericInterface(final MBeanInfo info) { /** * NOTE: a null proxy may be returned if the MBean is no longer registered */ - T getProxy( - final ObjectName objectName, - final MBeanInfo mbeanInfoIn, - final Class intfIn) { - //debug( "ProxyFactory.createProxy: " + objectName + " of class " + expected.getName() + " with interface " + JMXUtil.interfaceName(mbeanInfo) + ", descriptor = " + mbeanInfo.getDescriptor() ); + T getProxy(final ObjectName objectName, final MBeanInfo mbeanInfoIn, final Class intfIn) { AMXProxy proxy = null; try { @@ -455,14 +439,11 @@ T getProxy( final AMXProxyHandler handler = new AMXProxyHandler(getMBeanServerConnection(), objectName, mbeanInfo); proxy = (AMXProxy) Proxy.newProxyInstance(intf.getClassLoader(), new Class[]{intf}, handler); - //debug( "CREATED proxy of type " + intf.getName() + ", metadata specifies " + AMXProxyHandler.interfaceName(mbeanInfo) ); } catch (IllegalArgumentException e) { - //debug( "createProxy", e ); throw e; } catch (Exception e) { final Throwable rootCause = ExceptionUtil.getRootCause(e); if (!(rootCause instanceof InstanceNotFoundException)) { - //debug( "createProxy", e ); throw new RuntimeException(e); } proxy = null; @@ -472,8 +453,7 @@ T getProxy( } protected static String toString(final Object o) { - //return( org.glassfish.admin.amx.util.stringifier.SmartStringifier.toString( o ) ); - return "" + o; + return(org.glassfish.admin.amx.util.stringifier.SmartStringifier.toString(o)); } /** @@ -503,8 +483,7 @@ public Set toProxySet(final Set objectNames) { s.add(proxy); } } catch (final Exception e) { - debug("ProxyFactory.toProxySet: exception for MBean ", - objectName, " = ", ExceptionUtil.getRootCause(e)); + debug("ProxyFactory.toProxySet: exception for MBean ", objectName, " = ", ExceptionUtil.getRootCause(e)); } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/AMXStartupService.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/AMXStartupService.java index 81413eac453..323db21a46f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/AMXStartupService.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/AMXStartupService.java @@ -163,7 +163,6 @@ public void postConstruct() { mMBeanTracker.setEmitMBeanStatus(false); - //final StandardMBean supportMBean = new StandardMBean(mMBeanTracker, MBeanTrackerMBean.class); mMBeanServer.registerMBean(mMBeanTracker, MBeanTrackerMBean.MBEAN_TRACKER_OBJECT_NAME); } catch (final Exception e) { logger.log(Level.WARNING, "AMX Startup Service: Initialisation error.", e); @@ -327,16 +326,16 @@ public synchronized ObjectName _loadAMXMBeans() { // loads the high-level AMX MBeans, like DomainRoot, QueryMgr, etc loadDomainRoot(); FeatureAvailability.getInstance().registerFeature(FeatureAvailability.AMX_CORE_READY_FEATURE, getDomainRoot()); - logger.fine("AMXStartupServiceNew: AMX core MBeans are ready for use, DomainRoot = " + getDomainRoot()); + logger.log(Level.FINE, "AMXStartupServiceNew: AMX core MBeans are ready for use, DomainRoot = {0}", getDomainRoot()); try { // Find and load any additional AMX subsystems final Collection loaders = mHabitat.getAllServices(AMXLoader.class); - logger.fine("AMXStartupService._loadAMXMBeans(): found this many loaders: " + loaders.size()); + logger.log(Level.FINE, "AMXStartupService._loadAMXMBeans(): found this many loaders: {0}", loaders.size()); final AMXLoaderThread[] threads = new AMXLoaderThread[loaders.size()]; int i = 0; for (final AMXLoader loader : loaders) { - logger.fine("AMXStartupService._loadAMXMBeans(): found this many loaders: " + loader); + logger.log(Level.FINE, "AMXStartupService._loadAMXMBeans(): found this many loaders: {0}", loader); threads[i] = new AMXLoaderThread(loader); threads[i].start(); ++i; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigImpl.java index d49c36bd535..81b6ec495d4 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigImpl.java @@ -37,7 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2016] Payara Foundation +// Portions Copyright [2016-2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.config; import java.beans.PropertyChangeEvent; @@ -68,41 +69,38 @@ import org.jvnet.hk2.config.*; /** -Base class from which all AMX Config MBeans should derive (but not "must"). -

+ * Base class from which all AMX Config MBeans should derive (but not "must"). + *

*/ @Taxonomy(stability = Stability.NOT_AN_INTERFACE) -public class AMXConfigImpl extends AMXImplBase -{ +public class AMXConfigImpl extends AMXImplBase { + private final ConfigBean mConfigBean; private static final Logger logger = AMXLoggerInfo.getLogger(); - /** MBeanInfo derived from the AMXConfigProxy interface, always the same */ + /** + * MBeanInfo derived from the AMXConfigProxy interface, always the same + */ private static MBeanInfo configMBeanInfo; - private static synchronized MBeanInfo getAMXConfigMBeanInfo() - { - if (configMBeanInfo == null) - { + private static synchronized MBeanInfo getAMXConfigMBeanInfo() { + if (configMBeanInfo == null) { configMBeanInfo = MBeanInfoSupport.getMBeanInfo(AMXConfigProxy.class); } return configMBeanInfo; } - + /** - * We save time and space by creating exactly one MBeanInfo for any given config interface; - * it can be shared among all instances since it is invariant. + * We save time and space by creating exactly one MBeanInfo for any given config interface; it can be shared among all instances since it is invariant. */ - private static final ConcurrentMap, MBeanInfo> mInfos = - new ConcurrentHashMap, MBeanInfo>(); + private static final ConcurrentMap, MBeanInfo> mInfos + = new ConcurrentHashMap, MBeanInfo>(); - private static MBeanInfo createMBeanInfo(final ConfigBean cb) - { + private static MBeanInfo createMBeanInfo(final ConfigBean cb) { Class intf = cb.getProxyType(); MBeanInfo newInfo = mInfos.get(intf); - if (newInfo != null) - { + if (newInfo != null) { return newInfo; } @@ -114,30 +112,25 @@ private static MBeanInfo createMBeanInfo(final ConfigBean cb) // make a list so we can remove "Children" attribute if this MBean cannot have any final List spiAttrInfos = ListUtil.newListFromArray(spiInfo.getAttributes()); - if (spt.isLeaf()) - { + if (spt.isLeaf()) { JMXUtil.remove(spiAttrInfos, ATTR_CHILDREN); } // Add in the AMX_SPI attributes, replacing any with the same name - for (final MBeanAttributeInfo attrInfo : spiAttrInfos) - { + for (final MBeanAttributeInfo attrInfo : spiAttrInfos) { // remove existing info final String attrName = attrInfo.getName(); final MBeanAttributeInfo priorAttrInfo = JMXUtil.remove(attrInfos, attrName); // special case the Name attribute to preserve its metadata - if (attrName.equals(ATTR_NAME) && priorAttrInfo != null) - { + if (attrName.equals(ATTR_NAME) && priorAttrInfo != null) { final Descriptor mergedD = JMXUtil.mergeDescriptors(attrInfo.getDescriptor(), priorAttrInfo.getDescriptor()); final MBeanAttributeInfo newAttrInfo = new MBeanAttributeInfo(attrName, attrInfo.getType(), attrInfo.getDescription(), attrInfo.isReadable(), attrInfo.isWritable(), attrInfo.isIs(), mergedD); attrInfos.add(newAttrInfo); - } - else - { + } else { attrInfos.add(attrInfo); } } @@ -167,8 +160,7 @@ private static MBeanInfo createMBeanInfo(final ConfigBean cb) public AMXConfigImpl( final ObjectName parentObjectName, - final ConfigBean configBean) - { + final ConfigBean configBean) { super(parentObjectName, createMBeanInfo(configBean)); mConfigBean = configBean; @@ -179,154 +171,123 @@ public AMXConfigImpl( @Override protected void setAttributeManually(final Attribute attr) - throws AttributeNotFoundException, InvalidAttributeValueException - { + throws AttributeNotFoundException, InvalidAttributeValueException { final AttributeList attrList = new AttributeList(); attrList.add(attr); - try - { + try { final AttributeList successList = setAttributesInConfigBean(attrList); - if (successList.size() == 0) - { + if (successList.isEmpty()) { throw new AttributeNotFoundException(attr.getName()); } - } - catch (final Exception e) - { + } catch (final Exception e) { // propogate the stack trace back, it's important for clients to have somethingto go on final Throwable rootCause = ExceptionUtil.getRootCause(e); - throw new AttributeNotFoundException( ExceptionUtil.toString(rootCause) ); + throw new AttributeNotFoundException(ExceptionUtil.toString(rootCause)); } } /** - Note that the default implementation sets attributes one at a time, but that - MBeans with transactional requirements (eg configuration) may wish to set them as a group. + * Note that the default implementation sets attributes one at a time, but that MBeans with transactional requirements (eg configuration) may wish to set + * them as a group. */ @Override - public AttributeList setAttributes(final AttributeList attrs) - { - try - { + public AttributeList setAttributes(final AttributeList attrs) { + try { return setAttributesTransactionally(attrs); - } - catch (final Exception e) - { + } catch (final Exception e) { // squelch, per JMX spec } // return an empty list, per JMX spec for failure return new AttributeList(); } - - public AttributeList setAttributesTransactionally(final AttributeList attrs) throws Exception - { + + public AttributeList setAttributesTransactionally(final AttributeList attrs) throws Exception { final AttributeList successList = new AttributeList(); - try - { + try { final AttributeList delegateSuccess = setAttributesInConfigBean(attrs); successList.addAll(delegateSuccess); - } - catch (final Exception e) - { + } catch (final Exception e) { // propogate the stack trace back, it's important for clients to have something to go on final Throwable rootCause = ExceptionUtil.getRootCause(e); - + // do not propagate back any proprietary exception; class might not exist on client - throw new Exception( ExceptionUtil.toString(rootCause) ); + throw new Exception(ExceptionUtil.toString(rootCause)); } return successList; } - /** - The actual name could be different than the 'name' property in the ObjectName if it - contains characters that are illegal for an ObjectName. - Also, there can be a Name attribute which is not a key value. + * The actual name could be different than the 'name' property in the ObjectName if it contains characters that are illegal for an ObjectName. Also, there + * can be a Name attribute which is not a key value. */ @Override - public String getName() - { + public String getName() { final ConfigBean cb = getConfigBean(); String name = AMXConfigLoader.getKey(cb); - if ( name == null ) - { + if (name == null) { // deal with annoying and rare case of name existing, but not a key value - name = cb.rawAttribute( "name" ); + name = cb.rawAttribute("name"); } - + return name == null ? NO_NAME : name; } - private final ConfigBean getConfigBean() - { + private ConfigBean getConfigBean() { return mConfigBean; } - private final ConfigBeanProxy getConfigBeanProxy() - { + private ConfigBeanProxy getConfigBeanProxy() { return getConfigBean().getProxy(getConfigBean().getProxyType()); } /** - Resolve a template String. See {@link AttributeResolver} for details. + * Resolve a template String. See {@link AttributeResolver} for details. */ - public String resolveAttributeValue(final String varString) - { - if (!AttributeResolverHelper.needsResolving(varString)) - { + public String resolveAttributeValue(final String varString) { + if (!AttributeResolverHelper.needsResolving(varString)) { return varString; } - return new AttributeResolverHelper(getSelf(AMXConfigProxy.class)).resolve(varString); + return new AttributeResolverHelper().resolve(varString); } - public String resolveAttribute(final String attrName) - { - try - { + public String resolveAttribute(final String attrName) { + try { final Object value = getAttribute(attrName); return resolveAttributeValue(value == null ? null : "" + value); - } - catch (final AttributeNotFoundException e) - { - logger.log(Level.SEVERE, AMXLoggerInfo.attributeNotfound, new Object[]{attrName,getObjectName()}); + } catch (final AttributeNotFoundException e) { + logger.log(Level.SEVERE, AMXLoggerInfo.attributeNotfound, new Object[]{attrName, getObjectName()}); return null; } } - public Boolean resolveBoolean(final String attrName) - { + public Boolean resolveBoolean(final String attrName) { return Boolean.parseBoolean(resolveAttribute(attrName)); } - public Integer resolveInteger(final String attrName) - { + public Integer resolveInteger(final String attrName) { return Integer.parseInt(resolveAttribute(attrName)); } - public Long resolveLong(final String attrName) - { + public Long resolveLong(final String attrName) { return Long.parseLong(resolveAttribute(attrName)); } - public AttributeList resolveAttributes(final String[] attrNames) - { + public AttributeList resolveAttributes(final String[] attrNames) { Issues.getAMXIssues().notDone("resolveAttributes: use annotations to create the correct type"); final AttributeList attrs = getAttributes(attrNames); final AttributeList resolvedAttrs = new AttributeList(); - for (final Object o : attrs) - { + for (final Object o : attrs) { Attribute r = (Attribute) o; // allow non-String attributes final Object value = r.getValue(); - if ((value instanceof String) && AttributeResolverHelper.needsResolving((String) value)) - { + if ((value instanceof String) && AttributeResolverHelper.needsResolving((String) value)) { final String resolvedValue = resolveAttributeValue((String) value); // TODO: use annotation to determine correct type r = new Attribute(r.getName(), resolvedValue); @@ -337,103 +298,80 @@ public AttributeList resolveAttributes(final String[] attrNames) return resolvedAttrs; } - //======================================================================================== - /** - Parameters for creating one or more children, each of which can (recursively) contain - other descendants. + * Parameters for creating one or more children, each of which can (recursively) contain other descendants. */ static class CreateParams { - final String mType; - final Map mAttrs; - final List mChildren; - - public CreateParams( final String type, final Map values ) - { - mAttrs = MapUtil.newMap(); + + final String mType; + final Map mAttrs; + final List mChildren; + + public CreateParams(final String type, final Map values) { + mAttrs = MapUtil.newMap(); mChildren = ListUtil.newList(); - mType = type; - - if ( values == null ) - { + mType = type; + + if (values == null) { return; // null is legal, no attributes } - - for (final Map.Entry me : values.entrySet()) - { + + for (final Map.Entry me : values.entrySet()) { final String nameAsProvided = me.getKey(); final String xmlName = ConfigBeanJMXSupport.toXMLName(nameAsProvided); // or type - final Object value = me.getValue(); - - if (value == null || - (value instanceof String) || - (value instanceof Number) || - (value instanceof Boolean)) - { - //System.out.println( "toAttributeChanges: " + xmlName + " = " + value ); + final Object value = me.getValue(); + + if (value == null + || (value instanceof String) + || (value instanceof Number) + || (value instanceof Boolean)) { // auto-convert specific basic types to String final String valueString = value == null ? null : "" + value; - mAttrs.put( xmlName, valueString); - } - else if (value instanceof String[]) - { + mAttrs.put(xmlName, valueString); + } else if (value instanceof String[]) { // A String[] is always mapped to a List - mAttrs.put( xmlName, ListUtil.asStringList( value ) ); - } - else if (value instanceof Map) - { + mAttrs.put(xmlName, ListUtil.asStringList(value)); + } else if (value instanceof Map) { // one sub-element whose type is its key in the containing Map final Map m = TypeCast.checkMap(Map.class.cast(value), String.class, Object.class); - final CreateParams child = new CreateParams( xmlName, m); - //cdebug( "CreateParams for Map: create child of type: " + xmlName ); + final CreateParams child = new CreateParams(xmlName, m); mChildren.add(child); - } - else if (value instanceof Map[]) - { + } else if (value instanceof Map[]) { // one or more sub elements whose type is its key in the containing Map - final Map[] maps = (Map[])value; - for( final Map m : maps ) - { - final Map mTyped = TypeCast.checkMap(m, String.class, Object.class); - final CreateParams child = new CreateParams( xmlName, mTyped); - //cdebug( "CreateParams for Map[]: create child of type: " + xmlName ); + final Map[] maps = (Map[]) value; + for (final Map m : maps) { + final Map mTyped = TypeCast.checkMap(m, String.class, Object.class); + final CreateParams child = new CreateParams(xmlName, mTyped); mChildren.add(child); } - } - else - { + } else { throw new IllegalArgumentException("Value of class " + value.getClass().getName() + " not supported for attribute " + nameAsProvided); } } } - + public String type() { return mType; } public String name() { return (String)mAttrs.get("name"); } public Map attrs() { return Collections.unmodifiableMap(mAttrs); } public List children() { return Collections.unmodifiableList(mChildren); } - + /** - Convert incoming attributes to HK2 requirements. + * Convert incoming attributes to HK2 requirements. */ - List - toAttributeChanges(final Map values) - { - if ( values == null ) return null; - + List + toAttributeChanges(final Map values) { + if (values == null) { + return null; + } + final List changes = ListUtil.newList(); - for (final Map.Entry entry : mAttrs.entrySet()) - { - String xmlName = entry.getKey(); - final Object value = entry.getValue(); - - if ( value instanceof String ) - { - changes.add( new ConfigSupport.SingleAttributeChange(xmlName, (String)value) ); - } - else - { + for (Map.Entry xmlEntry : mAttrs.entrySet()) { + final Object value = xmlEntry.getValue(); + if (value instanceof String) { + changes.add(new ConfigSupport.SingleAttributeChange(xmlEntry.getKey(), (String) value)); + } else { // what about String[]? throw new IllegalArgumentException(); } @@ -441,77 +379,61 @@ else if (value instanceof Map[]) return changes; } - public String toString( final String prefix ) - { + public String toString(final String prefix) { final StringBuilder buf = new StringBuilder(); final String NL = StringUtil.LS; - + // crude toString, really should indent - buf.append( prefix + mType + " = " + mAttrs + NL ); - if ( mChildren.size() != 0 ) - { - buf.append( prefix + "[" ); - for ( final CreateParams child : mChildren ) - { - buf.append( child.toString(" " + prefix ) + NL ); + buf.append(prefix).append(mType).append(" = ").append(mAttrs).append(NL); + if (!mChildren.isEmpty()) { + buf.append(prefix).append("["); + for (final CreateParams child : mChildren) { + buf.append(child.toString(" " + prefix)).append(NL); } - buf.append( prefix + "]" ); + buf.append(prefix).append(']'); } - + return buf.toString(); } - public String toString() - { + + @Override + public String toString() { return toString(""); } } - - + /** - To make error messages more friendly and quick sanity check, - verify that no conflicting children already exist. + * To make error messages more friendly and quick sanity check, verify that no conflicting children already exist. */ - private void - checkForConflicts(final List children) - { - final Map> existingChildren = getSelf().childrenMaps(); - for( final CreateParams params : children ) - { + private void + checkForConflicts(final List children) { + final Map> existingChildren = getSelf().childrenMaps(); + for (final CreateParams params : children) { final String type = params.type(); - final Map childrenOfType = existingChildren.get(type); - if ( childrenOfType != null ) - { + final Map childrenOfType = existingChildren.get(type); + if (childrenOfType != null) { // children of this type exist, check that there is no conflicting child already final AMXProxy firstChild = childrenOfType.values().iterator().next(); - if ( firstChild.extra().singleton() ) - { - throw new IllegalArgumentException( "Singleton child of type " + type + " already exists." ); + if (firstChild.extra().singleton()) { + throw new IllegalArgumentException("Singleton child of type " + type + " already exists."); } - if ( childrenOfType.get( params.name() ) != null) - { - throw new IllegalArgumentException( "Child of type " + type + " named " + params.name() + " already exists." ); + if (childrenOfType.get(params.name()) != null) { + throw new IllegalArgumentException("Child of type " + type + " named " + params.name() + " already exists."); } } } } - - ObjectName[] - createChildren( - final List children, - final Map attrs ) - { - cdebug( children.toString() ); + + ObjectName[] createChildren(final List children, final Map attrs) { + debug(children.toString()); checkForConflicts(children); final ConfigBeanProxy parent = getConfigBeanProxy(); - final ChildrenCreator creator = new ChildrenCreator( children, attrs); - try - { + final ChildrenCreator creator = new ChildrenCreator(children, attrs); + try { ConfigSupport.apply(creator, parent); - } - catch (Exception e) - { - AMXLoggerInfo.getLogger().log(Level.INFO, AMXLoggerInfo.cantCreateChildren, e ); + } catch (Exception e) { + AMXLoggerInfo.getLogger().log(Level.INFO, AMXLoggerInfo.cantCreateChildren, e); throw new RuntimeException(e); } @@ -520,61 +442,49 @@ public String toString() final List newDescendants = creator.configBeans(); final AMXConfigLoader amxLoader = SingletonEnforcer.get(AMXConfigLoader.class); - for( final ConfigBean newDescendant : newDescendants ) - { - amxLoader.handleConfigBean(newDescendant, true); - final ObjectName objectName = ConfigBeanRegistry.getInstance().getObjectName(newDescendant); - newMBeans.add(objectName); - //cdebug( "ADDED: " + objectName ); + for (final ConfigBean newDescendant : newDescendants) { + amxLoader.handleConfigBean(newDescendant, true); + final ObjectName objectName = ConfigBeanRegistry.getInstance().getObjectName(newDescendant); + newMBeans.add(objectName); } - return CollectionUtil.toArray( newMBeans, ObjectName.class ); + return CollectionUtil.toArray(newMBeans, ObjectName.class); } - - public ObjectName[] - createChildren( - final Map[]> childrenMaps, - final Map attrs ) - { + + public ObjectName[] + createChildren( + final Map[]> childrenMaps, + final Map attrs) { final List children = ListUtil.newList(); - for(Map.Entry[]> entry : childrenMaps.entrySet()) { - for(final Map m : entry.getValue()) { - children.add( new CreateParams(entry.getKey(),m) ); + for (Map.Entry[]> entry : childrenMaps.entrySet()) { + for (final Map m : entry.getValue()) { + children.add(new CreateParams(entry.getKey(), m)); } } - /* Find bug error - for( final String type : childrenMaps.keySet() ) - { - for( final Map m : childrenMaps.get(type) ) - { - children.add( new CreateParams(type, m) ); - } - } */ - - return createChildren( children, attrs); + return createChildren(children, attrs); } - - /** Create one or more children */ - private final class ChildrenCreator implements ConfigCode - { + + /** + * Create one or more children + */ + private final class ChildrenCreator implements ConfigCode { + private final List mChildrenMaps; - private final Map mAttrs; - private final List mNewConfigBeans; + private final Map mAttrs; + private final List mNewConfigBeans; - ChildrenCreator( final List childrenMaps, final Map attrs) - { + ChildrenCreator(final List childrenMaps, final Map attrs) { mChildrenMaps = childrenMaps; mAttrs = attrs; - mNewConfigBeans = ListUtil.newList(); + mNewConfigBeans = ListUtil.newList(); } + @Override public Object run(final ConfigBeanProxy... params) - throws PropertyVetoException, TransactionFailure - { - if (params.length != 1) - { + throws PropertyVetoException, TransactionFailure { + if (params.length != 1) { throw new IllegalArgumentException(); } final ConfigBeanProxy parent = params[0]; @@ -586,236 +496,199 @@ public Object run(final ConfigBeanProxy... params) } public Object _run( - final ConfigBeanProxy parent, - final ConfigSupport configSupport) - throws PropertyVetoException, TransactionFailure - { + final ConfigBeanProxy parent, + final ConfigSupport configSupport) + throws PropertyVetoException, TransactionFailure { final WriteableView parentW = WriteableView.class.cast(Proxy.getInvocationHandler(Proxy.class.cast(parent))); - + // if attributes were specified, set them first. - if ( mAttrs != null ) - { - setAttrs( parent, mAttrs ); + if (mAttrs != null) { + setAttrs(parent, mAttrs); } - + final SubElementsCallback callback = new SubElementsCallback(mChildrenMaps); - final ConfigBeanJMXSupport sptRoot = ConfigBeanJMXSupportRegistry.getInstance( Dom.unwrap(parent).getProxyType() ); - final List newDescendants = callback.recursiveCreate( parentW, sptRoot, mChildrenMaps); - mNewConfigBeans.addAll( newDescendants ); - + final ConfigBeanJMXSupport sptRoot = ConfigBeanJMXSupportRegistry.getInstance(Dom.unwrap(parent).getProxyType()); + final List newDescendants = callback.recursiveCreate(parentW, sptRoot, mChildrenMaps); + mNewConfigBeans.addAll(newDescendants); + return null; } - - public List configBeans() { return mNewConfigBeans; } + + public List configBeans() { + return mNewConfigBeans; + } } - public ObjectName createChild(final String type, final Map params) - { - final CreateParams childParams = new CreateParams( type, params ); - + public ObjectName createChild(final String type, final Map params) { + final CreateParams childParams = new CreateParams(type, params); + final List children = ListUtil.newList(); children.add(childParams); - final ObjectName[] objectNames = createChildren( children, null); - + final ObjectName[] objectNames = createChildren(children, null); + return objectNames[0]; } - + /** - Replace "Name" or "name" with the + * Replace "Name" or "name" with the */ - Map - replaceNameWithKey( - final Map attrs, - final ConfigBeanJMXSupport spt) - { + Map + replaceNameWithKey( + final Map attrs, + final ConfigBeanJMXSupport spt) { String key = null; - if ( attrs.containsKey(ATTR_NAME) ) - { + if (attrs.containsKey(ATTR_NAME)) { key = ATTR_NAME; - } - else if ( attrs.containsKey("name") ) - { + } else if (attrs.containsKey("name")) { key = "name"; } - - Map m = attrs; - - if ( key != null ) - { + + Map m = attrs; + + if (key != null) { // map "Name" or "name" to the actual key value (which could be "name') final String xmlKeyName = spt.getNameHint(); // rename to the appropriate key name, if it doesn't already exist // eg there could be a non-key attribute "Name" and another key attribute; leave that alone - if ( xmlKeyName != null && ! attrs.keySet().contains(xmlKeyName) ) - { - m = new HashMap(attrs); + if (xmlKeyName != null && !attrs.keySet().contains(xmlKeyName)) { + m = new HashMap(attrs); final Object value = m.remove(key); - m.put( xmlKeyName, value ); + m.put(xmlKeyName, value); } } - + return m; } - - /** exists so we can get the parameterized return type */ - public static List listOfString() { return null; } - - public static String convertAttributeName(final String s ) - { + + /** + * exists so we can get the parameterized return type + */ + public static List listOfString() { + return null; + } + + public static String convertAttributeName(final String s) { // do not alter any name that is already all lower-case or that contains a "-" */ - if ( s.equals( s.toLowerCase(Locale.getDefault()) ) || s.indexOf('-') >= 0 ) - { - return(s); + if (s.equals(s.toLowerCase(Locale.getDefault())) || s.indexOf('-') >= 0) { + return (s); } - + // Dom.convertName() has a bug: IsFooBar => is-foo-bar, but is-foo-bar => -foo-bar. - return Dom.convertName(s); } - + private void setAttrs( - final ConfigBeanProxy target, - final Map attrs ) - { - final WriteableView targetW = WriteableView.class.cast(Proxy.getInvocationHandler(Proxy.class.cast(target))); - - for ( final Map.Entry me : attrs.entrySet() ) - { + final ConfigBeanProxy target, + final Map attrs) { + final WriteableView targetW = WriteableView.class.cast(Proxy.getInvocationHandler(Proxy.class.cast(target))); + + for (final Map.Entry me : attrs.entrySet()) { final String attrName = me.getKey(); final Object attrValue = me.getValue(); final String xmlName = convertAttributeName(attrName); - - final ConfigBean targetCB = (ConfigBean)Dom.unwrap(target); - final ConfigModel.Property modelProp = targetCB.model.findIgnoreCase( xmlName ); - if ( modelProp == null ) - { - throw new IllegalArgumentException( "Can't find ConfigModel.Property for attr " + xmlName + " on " + targetCB.getProxyType() ); + + final ConfigBean targetCB = (ConfigBean) Dom.unwrap(target); + final ConfigModel.Property modelProp = targetCB.model.findIgnoreCase(xmlName); + if (modelProp == null) { + throw new IllegalArgumentException("Can't find ConfigModel.Property for attr " + xmlName + " on " + targetCB.getProxyType()); } - //cdebug( "setting attribute \"" + attrName + "\" to \"" + attrValue + "\" on " + type ); - if ( modelProp.isCollection() ) - { - //cdebug( "HANDLING COLLECTION FOR " + xmlName + " on " + targetCB.getProxyType().getName() ); - java.lang.reflect.Method m; - try - { - m = getClass().getMethod("listOfString", null); - } - catch( final Exception e ) - { + if (modelProp.isCollection()) { + java.lang.reflect.Method method; + try { + method = getClass().getMethod("listOfString", new Class[0]); + } catch (final NoSuchMethodException | SecurityException e) { throw new IllegalStateException("impossible"); } - final java.lang.reflect.Type listOfStringClass = m.getGenericReturnType(); - - List list; - if ( attrValue instanceof String[] ) - { - list = ListUtil.asStringList( attrValue ); - } - else - { - list = TypeCast.checkList( TypeCast.asList(attrValue), String.class); + final java.lang.reflect.Type listOfStringClass = method.getGenericReturnType(); + + List list; + if (attrValue instanceof String[]) { + list = ListUtil.asStringList(attrValue); + } else { + list = TypeCast.checkList(TypeCast.asList(attrValue), String.class); } - targetW.setter( modelProp, list, listOfStringClass); - } - else - { - targetW.setter( modelProp, attrValue, String.class); + targetW.setter(modelProp, list, listOfStringClass); + } else { + targetW.setter(modelProp, attrValue, String.class); } - //cdebug( "set attribute \"" + attrName + "\" to \"" + attrValue + "\" on " + type ); } } - + /** - Callback to create sub-elements (recursively) on a newly created child element. + * Callback to create sub-elements (recursively) on a newly created child element. */ - private final class SubElementsCallback implements TransactionCallBack - { + private final class SubElementsCallback implements TransactionCallBack { + private final List mSubs; - public SubElementsCallback(final List subs) - { + public SubElementsCallback(final List subs) { mSubs = subs; } - public void performOn(final WriteableView item) throws TransactionFailure - { - final ConfigBeanJMXSupport sptRoot = ConfigBeanJMXSupportRegistry.getInstance( com.sun.enterprise.config.serverbeans.Domain.class ); - - recursiveCreate( item, sptRoot, mSubs ); + @Override + public void performOn(final WriteableView item) throws TransactionFailure { + final ConfigBeanJMXSupport sptRoot = ConfigBeanJMXSupportRegistry.getInstance(com.sun.enterprise.config.serverbeans.Domain.class); + + recursiveCreate(item, sptRoot, mSubs); } - + /** - If the child is of a type matching an @Element that is a List, then - get that list and add it to it. + * If the child is of a type matching an @Element that is a List, then get that list and add it to it. */ private void addToList( - final WriteableView parent, - final ConfigBeanProxy child ) - { + final WriteableView parent, + final ConfigBeanProxy child) { final Class parentClass = parent.getProxyType(); - final Class childClass = Dom.unwrap(child).getProxyType(); - final ConfigBeanJMXSupport parentSpt = ConfigBeanJMXSupportRegistry.getInstance(parentClass); - + final Class childClass = Dom.unwrap(child).getProxyType(); + final ConfigBeanJMXSupport parentSpt = ConfigBeanJMXSupportRegistry.getInstance(parentClass); + final ConfigBeanJMXSupport.ElementMethodInfo elementInfo = parentSpt.getElementMethodInfo(childClass); - //cdebug( "Found: " + elementInfo + " for " + childClass + " on parent class " + parentClass.getName() ); - final ConfigBean parentBean = (ConfigBean)Dom.unwrap(parent.getProxy(parentClass)); - if ( elementInfo != null && Collection.class.isAssignableFrom(elementInfo.method().getReturnType()) ) - { + final ConfigBean parentBean = (ConfigBean) Dom.unwrap(parent.getProxy(parentClass)); + if (elementInfo != null && Collection.class.isAssignableFrom(elementInfo.method().getReturnType())) { // get the Collection and add the child - final ConfigModel.Property modelProp = parentBean.model.findIgnoreCase( elementInfo.xmlName() ); - final List list = (List)parent.getter( modelProp, elementInfo.method().getGenericReturnType() ); - //cdebug( "Adding child to list obtained via " + elementInfo.method().getName() + "(), " + childClass ); - list.add( child ); - } - else if (elementInfo != null) - { - //cdebug( "Child is a singleton, adding via setter " + elementInfo.method().getName() + "()" ); - final ConfigModel.Property modelProp = parentBean.model.findIgnoreCase( elementInfo.xmlName() ); - if ( modelProp == null ) - { - throw new IllegalArgumentException( "Can't find ConfigModel.Property for \"" + elementInfo.xmlName() + "\"" ); + final ConfigModel.Property modelProp = parentBean.model.findIgnoreCase(elementInfo.xmlName()); + final List list = (List) parent.getter(modelProp, elementInfo.method().getGenericReturnType()); + list.add(child); + } else if (elementInfo != null) { + final ConfigModel.Property modelProp = parentBean.model.findIgnoreCase(elementInfo.xmlName()); + if (modelProp == null) { + throw new IllegalArgumentException("Can't find ConfigModel.Property for \"" + elementInfo.xmlName() + "\""); } - parent.setter( modelProp, child, childClass ); + parent.setter(modelProp, child, childClass); } } - + private List recursiveCreate( - final WriteableView parent, - final ConfigBeanJMXSupport sptRoot, - final List subs ) throws TransactionFailure - { + final WriteableView parent, + final ConfigBeanJMXSupport sptRoot, + final List subs) throws TransactionFailure { final List newChildren = ListUtil.newList(); - + // create each sub-element, recursively - for (final CreateParams childParams : subs ) - { + for (final CreateParams childParams : subs) { final String type = childParams.type(); - //cdebug( "recursiveCreate: " + type ); - + final Class clazz = ConfigBeanJMXSupportRegistry.getConfigBeanProxyClassFor(sptRoot, type); - if ( clazz == null ) - { - throw new IllegalArgumentException("@Configured interface for type " + type + " cannot be found" ); + if (clazz == null) { + throw new IllegalArgumentException("@Configured interface for type " + type + " cannot be found"); } - + final ConfigBeanJMXSupport spt = ConfigBeanJMXSupportRegistry.getInstance(clazz); final ConfigBeanProxy childProxy = parent.allocateProxy(clazz); Dom newBean = Dom.unwrap(childProxy); newBean.addDefaultChildren(); - addToList( parent, childProxy); - final ConfigBean child = (ConfigBean)Dom.unwrap(childProxy); + addToList(parent, childProxy); + final ConfigBean child = (ConfigBean) Dom.unwrap(childProxy); newChildren.add(child); final WriteableView childW = WriteableView.class.cast(Proxy.getInvocationHandler(Proxy.class.cast(childProxy))); - //cdebug("Created sub-element of type: " + type + ", " + clazz); - - final Map childAttrs = replaceNameWithKey( childParams.attrs(), spt); - setAttrs( childProxy, childAttrs ); - - if ( childParams.children().size() != 0 ) - { - final List more = recursiveCreate( childW, spt, childParams.children() ); + + final Map childAttrs = replaceNameWithKey(childParams.attrs(), spt); + setAttrs(childProxy, childAttrs); + + if (!childParams.children().isEmpty()) { + final List more = recursiveCreate(childW, spt, childParams.children()); newChildren.addAll(more); } } @@ -823,11 +696,9 @@ private List recursiveCreate( } } - public ObjectName removeChild(final String type) - { + public ObjectName removeChild(final String type) { final ObjectName child = child(type); - if (child == null) - { + if (child == null) { logger.log(Level.SEVERE, AMXLoggerInfo.childNotfound, type); return null; } @@ -835,30 +706,24 @@ public ObjectName removeChild(final String type) return remove(child); } - public ObjectName removeChild(final String type, final String name) - { + public ObjectName removeChild(final String type, final String name) { final ObjectName child = child(type, name); - if (child == null) return null; + if (child == null) { + return null; + } return remove(child); } - private final ObjectName remove(final ObjectName childObjectName) - { + private ObjectName remove(final ObjectName childObjectName) { ObjectName removed = null; - try - { + try { final ConfigBean childConfigBean = ConfigBeanRegistry.getInstance().getConfigBean(childObjectName); - try - { - //cdebug("REMOVING config of class " + childConfigBean.getProxyType().getName() + " from parent of type " + - //getConfigBean().getProxyType().getName() + ", ObjectName = " + JMXUtil.toString(childObjectName)); + try { ConfigSupport.deleteChild(this.getConfigBean(), childConfigBean); removed = childObjectName; - } - catch (final TransactionFailure tf) - { + } catch (final TransactionFailure tf) { throw new RuntimeException("Transaction failure deleting " + JMXUtil.toString(childObjectName), tf); } @@ -868,14 +733,10 @@ private final ObjectName remove(final ObjectName childObjectName) final UnregistrationListener myListener = new UnregistrationListener(getMBeanServer(), childObjectName); final long TIMEOUT_MILLIS = 10 * 1000; final boolean unregisteredOK = myListener.waitForUnregister(TIMEOUT_MILLIS); - //cdebug( "Waiting for child to be unregistered: " + childObjectName ); - if (!unregisteredOK) - { + if (!unregisteredOK) { throw new RuntimeException("Something went wrong unregistering MBean " + JMXUtil.toString(childObjectName)); } - } - catch (final Exception e) - { + } catch (final Exception e) { throw new RuntimeException("Problem deleting " + childObjectName, e); } return removed; @@ -884,428 +745,324 @@ private final ObjectName remove(final ObjectName childObjectName) private Object invokeDuckMethod( final ConfigBeanJMXSupport.DuckTypedInfo info, Object[] args) - throws MBeanException - { - try - { - //cdebug( "invokeDuckMethod(): invoking: " + info.name() + " on " + info.method().getDeclaringClass() ); + throws MBeanException { + try { - if (!info.method().getDeclaringClass().isAssignableFrom(getConfigBeanProxy().getClass())) - { + if (!info.method().getDeclaringClass().isAssignableFrom(getConfigBeanProxy().getClass())) { throw new IllegalArgumentException("invokeDuckMethod: " + getConfigBean().getProxyType() + " not asssignable to " + info.method().getDeclaringClass()); } Object result = info.method().invoke(getConfigBeanProxy(), args); result = translateResult(result); - - // cdebug( "invokeDuckMethod(): invoked: " + info.name() + ", got " + result ); return result; - } - catch (final Exception e) - { + } catch (final Exception e) { throw new MBeanException(e); } } - - private ObjectName getObjectName( final ConfigBeanProxy cbp ) - { + + private ObjectName getObjectName(final ConfigBeanProxy cbp) { final Dom dom = Dom.unwrap(cbp); - - if ( dom instanceof ConfigBean ) - { - return ConfigBeanRegistry.getInstance().getObjectName( (ConfigBean)dom ); + + if (dom instanceof ConfigBean) { + return ConfigBeanRegistry.getInstance().getObjectName((ConfigBean) dom); } - + // we can't return a Dom over the wire return null; } /** - Convert results that contain local ConfigBeanProxy into ObjectNames. - Ignore other items, passing through unchanged. + * Convert results that contain local ConfigBeanProxy into ObjectNames. Ignore other items, passing through unchanged. */ - private Object translateResult(final Object result ) - { + private Object translateResult(final Object result) { // short-circuit the common case - if ( result instanceof String ) return result; - + if (result instanceof String) { + return result; + } + Object out = result; // ConfigBean types must be mapped back to ObjectName; they can't go across the wire - - if ( result instanceof ConfigBeanProxy ) - { - out = getObjectName( (ConfigBeanProxy)result ); - } - else if ( result instanceof Collection ) - { - final Collection c = (Collection)result; + if (result instanceof ConfigBeanProxy) { + out = getObjectName((ConfigBeanProxy) result); + } else if (result instanceof Collection) { + final Collection c = (Collection) result; final Collection translated = new ArrayList(); - for( final Object item : c ) - { - translated.add( translateResult(item) ); + for (final Object item : c) { + translated.add(translateResult(item)); } - - if ( result instanceof Set ) - { + + if (result instanceof Set) { out = new HashSet(translated); - } - else if ( result instanceof AbstractQueue ) - { + } else if (result instanceof AbstractQueue) { out = new LinkedBlockingDeque(translated); - } - else - { + } else { out = translated; } - } - else if ( result instanceof Map ) - { - final Map resultMap = (Map)result; + } else if (result instanceof Map) { + final Map resultMap = (Map) result; Map outMap = new HashMap(); - for( final Object meo : resultMap.entrySet() ) - { - Map.Entry me = (Map.Entry)meo; - outMap.put( translateResult(me.getKey()), translateResult( me.getValue() ) ); + for (final Object meo : resultMap.entrySet()) { + Map.Entry me = (Map.Entry) meo; + outMap.put(translateResult(me.getKey()), translateResult(me.getValue())); } out = outMap; - } - else if ( result.getClass().isArray() ) - { + } else if (result.getClass().isArray()) { final Class componentType = result.getClass().getComponentType(); - if ( ConfigBeanProxy.class.isAssignableFrom(componentType) ) - { - final Object[] items = (Object[])result; + if (ConfigBeanProxy.class.isAssignableFrom(componentType)) { + final Object[] items = (Object[]) result; final ObjectName[] objectNames = new ObjectName[items.length]; - for( int i = 0; i < items.length; ++i ) - { - objectNames[i] = getObjectName( (ConfigBeanProxy)items[i] ); + for (int i = 0; i < items.length; ++i) { + objectNames[i] = getObjectName((ConfigBeanProxy) items[i]); } out = objectNames; } } - + return out; } - - /** - Automatically figure out getFactory(), - createConfig(), removeConfig(). + /** + * Automatically figure out getFactory(), createConfig(), removeConfig(). + * */ @Override protected Object invokeManually( String operationName, Object[] args, String[] types) - throws MBeanException, ReflectionException, NoSuchMethodException, AttributeNotFoundException - { + throws MBeanException, ReflectionException, NoSuchMethodException, AttributeNotFoundException { Object result = null; debugMethod(operationName, args); ConfigBeanJMXSupport.DuckTypedInfo duckTypedInfo = null; - if ((duckTypedInfo = getConfigBeanJMXSupport().findDuckTyped(operationName, types)) != null) - { + if ((duckTypedInfo = getConfigBeanJMXSupport().findDuckTyped(operationName, types)) != null) { result = invokeDuckMethod(duckTypedInfo, args); - } - else - { + } else { result = super.invokeManually(operationName, args, types); } return result; } - public void sendConfigCreatedNotification(final ObjectName configObjectName) - { + public void sendConfigCreatedNotification(final ObjectName configObjectName) { sendNotification(CONFIG_CREATED_NOTIFICATION_TYPE, CONFIG_REMOVED_NOTIFICATION_TYPE, CONFIG_OBJECT_NAME_KEY, configObjectName); } - public void sendConfigRemovedNotification(final ObjectName configObjectName) - { + public void sendConfigRemovedNotification(final ObjectName configObjectName) { sendNotification(CONFIG_REMOVED_NOTIFICATION_TYPE, CONFIG_REMOVED_NOTIFICATION_TYPE, CONFIG_OBJECT_NAME_KEY, configObjectName); } - private final ConfigBeanJMXSupport getConfigBeanJMXSupport() - { + private ConfigBeanJMXSupport getConfigBeanJMXSupport() { return ConfigBeanJMXSupportRegistry.getInstance(getConfigBean()); } - private static final Map getDefaultValues(final Class intf, boolean useAMXAttributeNames) - { + private static Map getDefaultValues(final Class intf, boolean useAMXAttributeNames) { return ConfigBeanJMXSupportRegistry.getInstance(intf).getDefaultValues(useAMXAttributeNames); } - public final Map getDefaultValues(final String type, final boolean useAMXAttributeNames) - { + public final Map getDefaultValues(final String type, final boolean useAMXAttributeNames) { final Class intf = getConfigBeanProxyClassForContainedType(type); return getDefaultValues(intf, useAMXAttributeNames); } - public final Map getDefaultValues(final boolean useAMXAttributeNames) - { + public final Map getDefaultValues(final boolean useAMXAttributeNames) { return getDefaultValues(mConfigBean.getProxyType(), useAMXAttributeNames); } - private Class getConfigBeanProxyClassForContainedType(final String type) - { + private Class getConfigBeanProxyClassForContainedType(final String type) { final ConfigBeanJMXSupport spt = getConfigBeanJMXSupport(); return ConfigBeanJMXSupportRegistry.getConfigBeanProxyClassFor(spt, type); } @Override - protected String[] attributeNameToType(final String attributeName) - { - return new String[] - { - Util.typeFromName(attributeName), attributeName - }; + protected String[] attributeNameToType(final String attributeName) { + return new String[]{ + Util.typeFromName(attributeName), attributeName + }; } @Override protected Object getAttributeManually(final String name) - throws AttributeNotFoundException, ReflectionException, MBeanException - { + throws AttributeNotFoundException, ReflectionException, MBeanException { return getAttributeFromConfigBean(name); } - //------------------------------------------------------------- /** - Get an Attribute. This is a bit tricky, because the target can be an XML attribute, - an XML string element, or an XML list of elements. + * Get an Attribute. This is a bit tricky, because the target can be an XML attribute, an XML string element, or an XML list of elements. */ - protected final Object getAttributeFromConfigBean(final String amxName) - { + protected final Object getAttributeFromConfigBean(final String amxName) { Object result = null; final MBeanAttributeInfo attrInfo = getAttributeInfo(amxName); - if ( attrInfo == null ) - { + if (attrInfo == null) { // // check for PSEUDO ATTTRIBUTES implemented as methods eg getFoo() // - //cdebug( "getAttributeFromConfigBean: no info for " + amxName ); - + ConfigBeanJMXSupport.DuckTypedInfo info = getConfigBeanJMXSupport().findDuckTyped("get" + amxName, null); - if ( info == null ) - { + if (info == null) { info = getConfigBeanJMXSupport().findDuckTyped("is" + amxName, null); } - if ( info != null ) - { - //cdebug( "getAttributeFromConfigBean: found DuckTyped for " + amxName ); - try - { - result = invokeDuckMethod( info, null); + if (info != null) { + try { + result = invokeDuckMethod(info, null); return result; + } catch (final Exception e) { + throw new RuntimeException(new MBeanException(e, amxName)); } - catch( final Exception e ) - { - throw new RuntimeException( new MBeanException( e, amxName ) ); - } - - } - else - { - //cdebug( "getAttributeFromConfigBean: no DuckTyped for " + amxName ); + } - throw new RuntimeException( new AttributeNotFoundException( amxName ) ); + throw new RuntimeException(new AttributeNotFoundException(amxName)); } final String xmlName = ConfigBeanJMXSupport.xmlName(attrInfo, amxName); final boolean isAttribute = ConfigBeanJMXSupport.isAttribute(attrInfo); - if (isAttribute) - { + if (isAttribute) { result = mConfigBean.rawAttribute(xmlName); - } - else if (ConfigBeanJMXSupport.isElement(attrInfo)) - { - if (String.class.getName().equals(attrInfo.getType())) - { + } else if (ConfigBeanJMXSupport.isElement(attrInfo)) { + if (String.class.getName().equals(attrInfo.getType())) { final List leaf = mConfigBean.leafElements(xmlName); - if (leaf != null) - { - try - { - result = (String) leaf.get(0); - } - catch (final Exception e) - { + if (leaf != null) { + try { + result = leaf.get(0); + } catch (final Exception e) { // doesn't exist, return null } } - } - else if (attrInfo.getType().equals(String[].class.getName())) - { - //final String elementClass = (String)d.getFieldValue( DESC_ELEMENT_CLASS ); + } else if (attrInfo.getType().equals(String[].class.getName())) { final List leaf = mConfigBean.leafElements(xmlName); - if (leaf != null) - { + if (leaf != null) { // verify that it is List -- no other types are supported in this way final List elems = TypeCast.checkList(leaf, String.class); result = CollectionUtil.toArray(elems, String.class); } - } - else - { + } else { throw new IllegalArgumentException("getAttributeFromConfigBean: unsupported return type: " + attrInfo.getType()); } } - //debug( "Attribute " + amxName + " has class " + ((result == null) ? "null" : result.getClass()) ); return result; } - private static final class MyTransactionListener implements TransactionListener - { + private static final class MyTransactionListener implements TransactionListener { + private final List mChangeEvents = new ArrayList(); private final ConfigBean mTarget; - MyTransactionListener(final ConfigBean target) - { + MyTransactionListener(final ConfigBean target) { mTarget = target; } - public void transactionCommited(List changes) - { + @Override + public void transactionCommited(List changes) { // include only events that match the desired config bean; other transactions // could generate events on other ConfigBeans. For that matter, it's unclear // why more than one transaction on the same ConfigBean couldn't be "heard" here. - for (final PropertyChangeEvent event : changes) - { + for (final PropertyChangeEvent event : changes) { final Object source = event.getSource(); - if (source instanceof ConfigBeanProxy) - { + if (source instanceof ConfigBeanProxy) { final Dom dom = Dom.unwrap((ConfigBeanProxy) source); - if (dom instanceof ConfigBean) - { - if (mTarget == (ConfigBean) dom) - { - mChangeEvents.add(event); - } + if (dom instanceof ConfigBean && mTarget == (ConfigBean) dom) { + mChangeEvents.add(event); } } } } - public void unprocessedTransactedEvents(List changes) - { + @Override + public void unprocessedTransactedEvents(List changes) { // amx probably does not care that some changes were not processed successfully // and will require a restart } - List getChangeEvents() - { + List getChangeEvents() { return mChangeEvents; } - }; + } private void joinTransaction(final Transaction t, final WriteableView writeable) - throws TransactionFailure - { - if (!writeable.join(t)) - { + throws TransactionFailure { + if (!writeable.join(t)) { t.rollback(); throw new TransactionFailure("Cannot enlist " + writeable.getProxyType() + " in transaction", null); } } private static void commit(final Transaction t) - throws TransactionFailure - { - try - { + throws TransactionFailure { + try { t.commit(); - } - catch (final RetryableException e) - { + } catch (final RetryableException e) { t.rollback(); throw new TransactionFailure(e.getMessage(), e); - } - catch (final TransactionFailure e) - { - //cdebug("failure, not retryable..."); + } catch (final TransactionFailure e) { t.rollback(); throw e; } } static WriteableView getWriteableView(final T s, final ConfigBean sourceBean) - throws TransactionFailure - { + throws TransactionFailure { final WriteableView f = new WriteableView(s); - if (sourceBean.getLock().tryLock()) - { + if (sourceBean.getLock().tryLock()) { return f; } throw new TransactionFailure("Config bean already locked " + sourceBean, null); } - private static Type getCollectionGenericType() - { - try - { + private static Type getCollectionGenericType() { + try { return ConfigSupport.class.getDeclaredMethod("defaultPropertyValue", (Class[]) null).getGenericReturnType(); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // not supposed to happen, throw any reasonabl exception throw new IllegalArgumentException(); } } /** - Handle an update to a collection, returning the List that results. + * Handle an update to a collection, returning the List that results. */ private List handleCollection( final WriteableView writeable, final ConfigModel.Property prop, - final List argValues) - { + final List argValues) { final Object o = writeable.getter(prop, getCollectionGenericType()); final List masterList = TypeCast.checkList(TypeCast.asList(o), String.class); - //cdebug( "Existing values: {" + CollectionUtil.toString( masterList ) + "}"); - //cdebug( "Arg values: {" + CollectionUtil.toString( argValues ) + "}"); - masterList.retainAll(argValues); - for (final String s : argValues) - { - if (!masterList.contains(s)) - { + for (final String s : argValues) { + if (!masterList.contains(s)) { masterList.add(s); } } - //cdebug( "Existing values list before commit: {" + CollectionUtil.toString( masterList ) + "}"); return new ArrayList(masterList); } - private class Applyer - { + private class Applyer { + final Transaction mTransaction; final ConfigBean mConfigBean; final WriteableView mWriteable; - public Applyer(final ConfigBean cb) throws TransactionFailure - { + public Applyer(final ConfigBean cb) throws TransactionFailure { this(cb, new Transaction()); } public Applyer(final ConfigBean cb, final Transaction t) - throws TransactionFailure - { + throws TransactionFailure { mConfigBean = cb; mTransaction = t; @@ -1314,72 +1071,56 @@ public Applyer(final ConfigBean cb, final Transaction t) } protected void makeChanges() - throws TransactionFailure - { + throws TransactionFailure { } final void apply() - throws TransactionFailure - { - try - { + throws TransactionFailure { + try { joinTransaction(mTransaction, mWriteable); makeChanges(); commit(mTransaction); - } - finally - { + } finally { mConfigBean.getLock().unlock(); } } } - protected ConfigModel.Property getConfigModel_Property(final String xmlName) - { + protected ConfigModel.Property getConfigModel_Property(final String xmlName) { final ConfigModel.Property cmp = mConfigBean.model.findIgnoreCase(xmlName); - if (cmp == null) - { + if (cmp == null) { throw new IllegalArgumentException("Illegal name: " + xmlName); } return cmp; } - private final class MakeChangesApplyer extends Applyer - { + private final class MakeChangesApplyer extends Applyer { + private final Map mChanges; public MakeChangesApplyer( final ConfigBean cb, final Map changes) - throws TransactionFailure - { + throws TransactionFailure { super(cb); mChanges = changes; } - protected void makeChanges() - throws TransactionFailure - { - for (final Map.Entry entry : mChanges.entrySet()) - { - String xmlName = entry.getKey(); - final Object value = entry.getValue(); - final ConfigModel.Property prop = getConfigModel_Property(xmlName); - - if (prop.isCollection()) - { + @Override + protected void makeChanges() throws TransactionFailure { + for (Map.Entry xmlEntry : mChanges.entrySet()) { + final Object value = xmlEntry.getValue(); + final ConfigModel.Property prop = getConfigModel_Property(xmlEntry.getKey()); + + if (prop.isCollection()) { handleCollection(mWriteable, prop, ListUtil.asStringList(value)); - } - else if (value == null || (value instanceof String)) - { + } else if (value == null || (value instanceof String)) { mWriteable.setter(prop, value, String.class); - } - else - { - throw new TransactionFailure("Illegal data type for attribute " + xmlName + ": " + value.getClass().getName()); + } else { + throw new TransactionFailure("Illegal data type for attribute " + xmlEntry.getKey() + ": " + value.getClass().getName()); } } } @@ -1388,62 +1129,43 @@ else if (value == null || (value instanceof String)) private Map mapNamesAndValues( final Map amxAttrs, - final Map noMatch) - { + final Map noMatch) { final Map xmlAttrs = new HashMap(); final Map attrInfos = getAttributeInfos(); - for (final Map.Entry me : amxAttrs.entrySet()) - { + for (final Map.Entry me : amxAttrs.entrySet()) { final String amxAttrName = me.getKey(); final Object valueIn = me.getValue(); final MBeanAttributeInfo attrInfo = attrInfos.get(amxAttrName); - if (attrInfo == null) - { + if (attrInfo == null) { debug("WARNING: setAttributes(): no MBeanAttributeInfo found for: " + amxAttrName); noMatch.put(amxAttrName, valueIn); continue; } final String xmlName = ConfigBeanJMXSupport.xmlName(attrInfo, amxAttrName); - if (xmlName != null) - { - //cdebug( "mapNamesAndValues: " + xmlName ); - + if (xmlName != null) { + final Object value = valueIn; - + // We accept only Strings, String[] or null - if (valueIn == null || (value instanceof String)) - { + if (valueIn == null || (value instanceof String)) { xmlAttrs.put(xmlName, (String) value); - } - else - { + } else { final ConfigModel.Property prop = getConfigModel_Property(xmlName); - if ( prop != null && prop.isCollection() ) - { - //cdebug( "mapNamesAndValues: is a collection: " + xmlName ); - if ((valueIn instanceof String[]) || (valueIn instanceof List)) - { - //cdebug( "mapNamesAndValues: is a collection, setting value to List: " + xmlName ); + if (prop != null && prop.isCollection()) { + if ((valueIn instanceof String[]) || (valueIn instanceof List)) { xmlAttrs.put(xmlName, ListUtil.asStringList(valueIn)); - } - else - { + } else { noMatch.put(amxAttrName, valueIn); } - } - else - { + } else { noMatch.put(amxAttrName, valueIn); } } - // debug( "Attribute " + amxAttrName + "<=>" + xmlName + " is of class " + ((value == null) ? null : value.getClass().getName()) ); - } - else - { + } else { debug("WARNING: setAttributes(): no xmlName match found for AMX attribute: " + amxAttrName); noMatch.put(amxAttrName, valueIn); } @@ -1452,51 +1174,39 @@ private Map mapNamesAndValues( return xmlAttrs; } - public AttributeList setAttributesInConfigBean(final AttributeList attrsIn) throws TransactionFailure - { + public AttributeList setAttributesInConfigBean(final AttributeList attrsIn) throws TransactionFailure { // now map the AMX attribute names to xml attribute names final Map amxAttrs = JMXUtil.attributeListToValueMap(attrsIn); final Map notMatched = new HashMap(); final Map xmlAttrs = mapNamesAndValues(amxAttrs, notMatched); - if (notMatched.keySet().size() != 0) - { - cdebug("setAttributes: failed to map these AMX attributes: {" + CollectionUtil.toString(notMatched.keySet(), ", ") + "}"); + if (!notMatched.keySet().isEmpty()) { + debug("setAttributes: failed to map these AMX attributes: {" + CollectionUtil.toString(notMatched.keySet(), ", ") + "}"); } - - //System.out.println( "setAttributesInConfigBean: " + amxAttrs); final AttributeList successfulAttrs = new AttributeList(); final Transactions transactions = mConfigBean.getHabitat().getService(Transactions.class); - if (xmlAttrs.size() != 0) - { - //cdebug( "DelegateToConfigBeanDelegate.setAttributes(): " + attrsIn.size() + " attributes: {" + - // CollectionUtil.toString(amxAttrs.keySet()) + "} mapped to xml names {" + CollectionUtil.toString(xmlAttrs.keySet()) + "}"); + if (!xmlAttrs.isEmpty()) { final MyTransactionListener myListener = new MyTransactionListener(mConfigBean); transactions.addTransactionsListener(myListener); // results should contain only those that succeeded which will be all or none // depending on whether the transaction worked or not - try - { + try { final MakeChangesApplyer mca = new MakeChangesApplyer(mConfigBean, xmlAttrs); mca.apply(); // use 'attrsIn' vs 'attrs' in case not all values are 'String' successfulAttrs.addAll(attrsIn); - } - catch (final TransactionFailure tf) - { + } catch (final TransactionFailure tf) { // empty results -- no Exception should be thrown per JMX spec - cdebug(ExceptionUtil.toString(tf)); - throw(tf); - } - finally - { + debug(ExceptionUtil.toString(tf)); + throw (tf); + } finally { transactions.waitForDrain(); transactions.removeTransactionsListener(myListener); @@ -1505,62 +1215,31 @@ public AttributeList setAttributesInConfigBean(final AttributeList attrsIn) thro return successfulAttrs; } - + /** - Share one sequence number for *all* Config MBeans to keep overhead low - instead of + * Share one sequence number for *all* Config MBeans to keep overhead low instead of */ private static final AtomicLong sSequenceNumber = new AtomicLong(0); - - void - issueAttributeChangeForXmlAttrName( - final String xmlAttrName, - final String message, - final Object oldValue, - final Object newValue, - final long whenChanged ) - { - final Map m = getConfigBeanJMXSupport().getFromXMLNameMapping(); - final String attributeName = m.containsKey(xmlAttrName) ? m.get(xmlAttrName) : xmlAttrName; - if ( attributeName.equals(xmlAttrName) ) // will *always* be different due to camel case + + void issueAttributeChangeForXmlAttrName(final String xmlAttrName, final String message, final Object oldValue, final Object newValue, + final long whenChanged) { + + final Map m = getConfigBeanJMXSupport().getFromXMLNameMapping(); + final String attributeName = m.containsKey(xmlAttrName) ? m.get(xmlAttrName) : xmlAttrName; + if (attributeName.equals(xmlAttrName)) // will *always* be different due to camel case { - //cdebug( "issueAttributeChangeForXmlAttrName(): MBean attribute name not found for xml name, using xml name: " + xmlAttrName ); logger.log(Level.SEVERE, AMXLoggerInfo.attributeNotfound, xmlAttrName); } - - final String attributeType = String.class.getName(); - - getLogger().fine( getObjectName() + " -- " + attributeName + " = " + newValue + " <== " + oldValue ); - - // if ( getListenerCount() == 0 ) return; - - final long sequenceNumber = sSequenceNumber.getAndIncrement(); - final AttributeChangeNotification notif = - new AttributeChangeNotification( getObjectName(), sequenceNumber, whenChanged, message, attributeName, attributeType, oldValue, newValue); - - sendNotification( notif ); - - //cdebug( "AMXConfigImpl.issueAttributeChangeForXmlAttrName(): sent: " + notif ); - } -} - - - - - - - - - - - - - - - - + final String attributeType = String.class.getName(); + getLogger().log(Level.FINE, "{0} -- {1} = {2} <== {3}", new Object[]{getObjectName(), attributeName, newValue, oldValue}); + final long sequenceNumber = sSequenceNumber.getAndIncrement(); + final AttributeChangeNotification notif + = new AttributeChangeNotification(getObjectName(), sequenceNumber, whenChanged, message, attributeName, attributeType, oldValue, newValue); + sendNotification(notif); + } +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigLoader.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigLoader.java index bff126916e6..fd42cdb1cd5 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigLoader.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigLoader.java @@ -38,7 +38,7 @@ * holder. */ - // Portions Copyright [2016-2018] [Payara Foundation and/or its affiliates] + // Portions Copyright [2016-2019] [Payara Foundation and/or its affiliates] package org.glassfish.admin.amx.impl.config; @@ -72,19 +72,16 @@ import org.jvnet.hk2.config.*; /** -Responsible for loading ConfigBeanProxy MBeans (com.sun.enterprise.config.serverbeans.*) + * Responsible for loading ConfigBeanProxy MBeans (com.sun.enterprise.config.serverbeans.*) * @author llc */ @Taxonomy(stability = Stability.NOT_AN_INTERFACE) -public final class AMXConfigLoader - implements TransactionListener { +public final class AMXConfigLoader implements TransactionListener { - private static void debug(final String s) { - System.out.println(s); - } + private static final Logger mLogger = AMXLoggerInfo.getLogger(); + private volatile AMXConfigLoaderThread mLoaderThread; private final Transactions mTransactions; - private final Logger mLogger = AMXLoggerInfo.getLogger(); private final PendingConfigBeans mPendingConfigBeans; private final ConfigBeanRegistry mRegistry = ConfigBeanRegistry.getInstance(); private final MBeanServer mServer; @@ -156,7 +153,6 @@ private void issueAttributeChange( } if (changed) { - //debug( "AMXConfigLoader.issueAttributeChange(): " + xmlAttrName + ": {" + oldValue + " => " + newValue + "}"); final Object impl = mRegistry.getImpl(cb); if (!(impl instanceof AMXConfigImpl)) { throw new IllegalStateException("impossible"); @@ -170,7 +166,6 @@ private void issueAttributeChange( private void sortAndDispatch( final List events, final long whenChanged) { - //debug( "AMXConfigLoader.sortAndDispatch: " + events.size() + " events" ); final List newConfigBeans = new ArrayList(); final List remainingEvents = new ArrayList(); @@ -196,7 +191,6 @@ private void sortAndDispatch( // REMOVE final ConfigBeanProxy cbp = (ConfigBeanProxy) oldValue; final ConfigBean cb = asConfigBean(ConfigBean.unwrap(cbp)); - //debug( "AMXConfigLoader.sortAndDispatch: remove (recursive) ConfigBean: " + mRegistry.getObjectName(cb) ); configBeanRemoved(cb); } else { remainingEvents.add(event); @@ -210,43 +204,35 @@ private void sortAndDispatch( final Object newValue = event.getNewValue(); final Object source = event.getSource(); final String propertyName = event.getPropertyName(); - //final String sourceString = (source instanceof ConfigBeanProxy) ? ConfigSupport.proxyType((ConfigBeanProxy)source).getName() : "" + source; - - //debug( "AMXConfigLoader.sortAndDispatch (ATTR change): name = " + propertyName + - // ", oldValue = " + oldValue + ", newValue = " + newValue + ", source = " + sourceString ); if (source instanceof ConfigBeanProxy) { // CHANGE final ConfigBeanProxy cbp = (ConfigBeanProxy) source; final ConfigBean cb = asConfigBean(ConfigBean.unwrap(cbp)); - //final Class proxyClass = ConfigSupport.proxyType(cbp); // change events without prior add // we shouldn't have to check for this, but it's a bug in the caller: no even for // new ConfigBean, but changes come along anyway if (mRegistry.getObjectName(cb) == null) { - if (!newConfigBeans.contains(cb)) { - //debug( "AMXConfigLoader.sortAndDispatch: process new ConfigBean (WORKAROUND): " + proxyClass.getNameProp() ); - if (handleConfigBean(cb, false)) { + if (!newConfigBeans.contains(cb) && handleConfigBean(cb, false)) { newConfigBeans.add(cb); - } } } else { issueAttributeChange(cb, propertyName, oldValue, newValue, whenChanged); } } else { - debug("AMXConfigLoader.sortAndDispatch: WARNING: source is not a ConfigBean"); + mLogger.log(Level.WARNING, "AMXConfigLoader.sortAndDispatch: source is not a ConfigBean"); } } } } + @Override public void transactionCommited(final List changes) { - //final PropertyChangeEvent[] changesArray = new PropertyChangeEvent[changes.size()]; - //changes.toArray( changesArray ); sortAndDispatch(changes, System.currentTimeMillis()); } + @Override public void unprocessedTransactedEvents(List changes) { // not interested... } @@ -289,10 +275,8 @@ boolean handleConfigBean(final ConfigBean cb, final boolean waitDone) { */ private ConfigBean getActualParent(final ConfigBean configBean) { ConfigBean parent = asConfigBean(configBean.parent()); - if (parent == null) { - if (!configBean.getProxyType().getName().endsWith("Domain")) { + if (parent == null && !configBean.getProxyType().getName().endsWith("Domain")) { throw new IllegalStateException("WARNING: parent is null for " + configBean.getProxyType().getName() + ", see issue #10528"); - } } return parent; @@ -381,7 +365,6 @@ private ObjectName registerOne(final PendingConfigBeanJob job) { // that are parents, and thus already registered. if (objectName == null) { objectName = registerConfigBeanAsMBean(cb); - //debug( "AMXConfigLoaderThread.registerOne(): " + objectName); } } catch (final Throwable t) { mLogger.log(Level.WARNING, AMXLoggerInfo.cantRegister, new Object[]{getType(cb), getKey(cb), t}); @@ -392,6 +375,7 @@ private ObjectName registerOne(final PendingConfigBeanJob job) { return objectName; } + @Override public void run() { try { doRun(); @@ -444,12 +428,9 @@ protected void doRun() throws Exception { private ObjectName registerConfigBeanAsMBean(final ConfigBean cb) { ObjectName objectName = null; - //debug( "registerConfigBeanAsMBean: " + cb.getProxyType().getName() + ", object = " + cb ); final ConfigBean parentCB = getActualParent(cb); if (parentCB != null && mRegistry.getObjectName(parentCB) == null) { - //debug( "REGISTER parent first: " + parentCB.getProxyType().getName() ); registerConfigBeanAsMBean(parentCB); - //debug( "REGISTERED parent: " + parentCB.getProxyType().getName() + " as " + JMXUtil.toString(parentCB.getObjectName()) ); } objectName = _registerConfigBeanAsMBean(cb, parentCB); assert objectName == null || mRegistry.getObjectName(cb) != null; @@ -464,7 +445,6 @@ private ObjectName _registerConfigBeanAsMBean( final ConfigBean parentCB) { final Class cbClass = cb.getProxyType(); - //debug( "_registerConfigBeanAsMBean: " + cb.getProxyType().getName() ); ObjectName objectName = mRegistry.getObjectName(cb); if (objectName != null) { @@ -475,13 +455,11 @@ private ObjectName _registerConfigBeanAsMBean( + " must be registered first before child = " + cbClass.getName()); } - // debug( "Preparing ConfigBean for registration with ObjectNameInfo = " + objectNameInfo.toString() + ", AMXMBeanMetaData = " + metadata ); - objectName = buildObjectName(cb); objectName = createAndRegister(cb, objectName); if (objectName != null) { - mLogger.fine("REGISTERED MBEAN: " + objectName); + mLogger.log(Level.FINE, "REGISTERED MBEAN: {0}", objectName); } return objectName; @@ -504,16 +482,11 @@ private ObjectName createAndRegister( final ObjectInstance instance = mServer.registerMBean(impl, objectNameIn); objectName = instance.getObjectName(); mRegistry.add(cb, objectName, impl); - - //System.out.println( "AMXConfigLoader.createAndRegister(): REGISTERED: " + objectName + " at " + System.currentTimeMillis() ); - //System.out.println( JMXUtil.toString( mServer.getMBeanInfo(objectName) ) ); } catch (InstanceAlreadyExistsException ex) { mLogger.log(Level.FINE, ExceptionUtil.toString(ex)); - objectName = null; } catch (final JMException e) { - debug(ExceptionUtil.toString(e)); - + mLogger.log(Level.SEVERE, ExceptionUtil.toString(e)); objectName = null; } return objectName; @@ -580,13 +553,7 @@ private ObjectName buildObjectName(final ConfigBean cb) { mLogger.log(Level.WARNING, AMXLoggerInfo.nonsingletonConfigbean, new Object[] {cb.getProxyType().getName() ,name}); } - //debug( "Type/name for " + cb.getProxyType().getName() + " = " + type + " = " + name ); - - final ObjectName objectName = ObjectNameBuilder.buildChildObjectName(mServer, parentObjectName, type, quoteIfNeeded(name)); - - //debug( "ObjectName for " + cb.getProxyType().getName() + " = " + objectName + " of parent " + parentObjectName ); - - return objectName; + return ObjectNameBuilder.buildChildObjectName(mServer, parentObjectName, type, quoteIfNeeded(name)); } /** diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigStartupService.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigStartupService.java index ca5182b1fa5..9174d2e2451 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigStartupService.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AMXConfigStartupService.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.config; import com.sun.enterprise.config.serverbeans.Domain; @@ -49,21 +51,15 @@ import org.jvnet.hk2.annotations.Service; import javax.inject.Inject; -import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; -import javax.management.StandardMBean; - import org.glassfish.external.arc.Stability; import org.glassfish.external.arc.Taxonomy; -import org.glassfish.admin.amx.config.AMXConfigConstants; -import org.glassfish.admin.amx.impl.config.AMXConfigLoader; import org.glassfish.admin.amx.impl.util.ImplUtil; import org.glassfish.admin.amx.impl.util.InjectedValues; import org.glassfish.admin.amx.util.AMXLoggerInfo; -import org.glassfish.admin.amx.util.FeatureAvailability; import org.glassfish.admin.mbeanserver.PendingConfigBeans; import org.glassfish.api.amx.AMXLoader; import org.jvnet.hk2.config.Transactions; @@ -79,9 +75,6 @@ public final class AMXConfigStartupService org.glassfish.hk2.api.PreDestroy, AMXLoader { - private static void debug(final String s) { - System.out.println(s); - } @Inject InjectedValues mInjectedValues; @Inject//(name=AppserverMBeanServerFactory.OFFICIAL_MBEANSERVER) @@ -93,10 +86,7 @@ private static void debug(final String s) { private volatile AMXConfigLoader mLoader; private volatile PendingConfigBeans mPendingConfigBeansBackup; - public AMXConfigStartupService() { - //debug( "AMXStartupService.AMXStartupService()" ); - } - + @Override public void postConstruct() { final TimingDelta delta = new TimingDelta(); @@ -111,6 +101,7 @@ public void postConstruct() { AMXLoggerInfo.getLogger().log(Level.FINE, "Initialized AMXConfig Startup service in {0} ms", delta.elapsedMillis()); } + @Override public void preDestroy() { AMXLoggerInfo.getLogger().info(AMXLoggerInfo.stoppingAMX); unloadAMXMBeans(); @@ -132,9 +123,9 @@ public AMXProxy getDomainConfigProxy() { return ProxyFactory.getInstance(mMBeanServer).getProxy(getDomainConfig(), AMXProxy.class); } + @Override public synchronized ObjectName loadAMXMBeans() { if (mLoader == null) { - //getDomainRootProxy().waitAMXReady(); if(mPendingConfigBeans.size() == 0) { mPendingConfigBeans = mPendingConfigBeansBackup; } @@ -145,6 +136,7 @@ public synchronized ObjectName loadAMXMBeans() { return getDomainConfig(); } + @Override public synchronized void unloadAMXMBeans() { final AMXProxy domainConfigProxy = getDomainConfigProxy(); if (domainConfigProxy != null) { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java index 894238f9d99..9c2d960abf7 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java @@ -37,9 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.config; -import org.glassfish.admin.amx.config.AMXConfigProxy; import org.glassfish.external.arc.Stability; import org.glassfish.external.arc.Taxonomy; import org.jvnet.hk2.config.TranslationException; @@ -66,13 +67,6 @@ @Taxonomy( stability = Stability.UNCOMMITTED) public class AttributeResolverHelper extends VariableResolver { - private static void debug(final String s) { - System.out.println("##### " + s); - } - - public AttributeResolverHelper(final AMXConfigProxy amx) { - } - @Override protected String getVariableValue(final String varName) throws TranslationException { String result = varName; @@ -90,17 +84,13 @@ protected String getVariableValue(final String varName) throws TranslationExcept * Return true if the string is a template string of the for ${...} */ public static boolean needsResolving(final String value) { - return value != null && value.indexOf("${") >= 0; + return value != null && value.contains("${"); } /** * Resolve the String using the target resolver (MBean). */ public String resolve(final String in) throws TranslationException { - final String result = translate(in); - - //debug( "AttributeResolverHelper.resolve(): " + in + " ===> " + result ); - - return result; + return translate(in); } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanJMXSupport.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanJMXSupport.java index 259eb15a9a6..5bf52056af3 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanJMXSupport.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanJMXSupport.java @@ -37,11 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ package org.glassfish.admin.amx.impl.config; import java.lang.annotation.Annotation; @@ -61,7 +58,6 @@ import java.util.Set; import javax.management.Descriptor; import javax.management.MBeanAttributeInfo; -import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; import javax.management.AttributeChangeNotification; @@ -83,7 +79,6 @@ import org.glassfish.admin.amx.core.Util; import static org.glassfish.admin.amx.config.AMXConfigConstants.*; import org.glassfish.admin.amx.config.AMXConfigProxy; -import org.glassfish.admin.amx.impl.util.ImplUtil; import org.glassfish.admin.amx.util.ClassUtil; import org.glassfish.admin.amx.util.CollectionUtil; import org.glassfish.admin.amx.util.MapUtil; @@ -108,6 +103,7 @@ import org.glassfish.admin.amx.impl.util.InjectedValues; import java.util.logging.Level; +import java.util.logging.Logger; import org.glassfish.admin.amx.util.AMXLoggerInfo; @@ -132,6 +128,8 @@ class ConfigBeanJMXSupport private final MBeanInfo mMBeanInfo; private final String mKey; // xml name + + private static final Logger LOGGER = AMXLoggerInfo.getLogger(); private static String nameFromKey(final String key) { @@ -156,10 +154,6 @@ private static String nameFromKey(final String key) ConfigBeanJMXSupport(final ConfigBean configBean) { this(configBean.getProxyType(), nameFromKey(configBean.model.key)); - - //debug( "ConfigBeanJMXSupport: " + configBean.getProxyType().getName() + ": key=" + configBean.model.key + ", keyedAs=" + configBean.model.keyedAs); - - //debug( toString() ); } /** @@ -179,50 +173,44 @@ private static String nameFromKey(final String key) mMBeanInfo = _getMBeanInfo(); sanityCheckMBeanInfo(); mNameHint = findNameHint(); - - /** - if (hasConfiguredBug() && key == null) { - ImplUtil.getLogger().warning("ConfigBeanJMXSupport (AMX): working around @Configured bug for " + mIntf.getName() + - ", using \"" + configuredBugKey() + "\" as the key attribute"); - } - */ } public Class getIntf() { return mIntf; } + @Override public String toString() { final StringBuilder buf = new StringBuilder(); final String DELIM = ", "; - final String NL = StringUtil.NEWLINE(); + final String NL = StringUtil.LS; - buf.append(mIntf.getName() + " = "); - buf.append(NL + "Attributes: {" + NL); + buf.append(mIntf.getName()).append(" = "); + buf.append(NL).append("Attributes: {").append(NL); for (final AttributeMethodInfo info : mAttrInfos) { - buf.append(info.attrName() + "/" + info.xmlName() + DELIM); + buf.append(info.attrName()).append("/").append(info.xmlName()).append(DELIM); } - buf.append(NL + "}" + NL + "Elements: {" + NL); + buf.append(NL).append("}").append(NL).append("Elements: {").append(NL); for (final ElementMethodInfo info : mElementInfos) { - buf.append(info.attrName() + "/" + info.xmlName() + DELIM); + buf.append(info.attrName()).append("/").append(info.xmlName()).append(DELIM); } final Set childTypes = childTypes().keySet(); - buf.append(NL + "}" + NL + "Child types: {" + NL); + buf.append(NL).append("}").append(NL).append("Child types: {").append(NL); for (final String type : childTypes) { - buf.append(type + DELIM); + buf.append(type).append(DELIM); } - buf.append(NL + "}" + NL + "DuckTyped: {" + NL); + buf.append(NL).append("}").append(NL).append("DuckTyped: {").append(NL); for (final DuckTypedInfo info : mDuckTypedInfos) { - buf.append(info + NL); + buf.append(info).append(NL); } - buf.append(NL + "}" + NL); + buf.append(NL).append("}").append(NL); return buf.toString(); } @@ -258,11 +246,9 @@ public DuckTypedInfo findDuckTyped(final String name, final String[] types) final int numTypes = types == null ? 0 : types.length; for (final DuckTypedInfo candidate : mDuckTypedInfos) { - // debug( "Match " + name + "=" + numTypes + " against " + candidate.name() + "=" + candidate.signature().length ); final Class[] sig = candidate.signature(); if (candidate.name().equals(name) && numTypes == sig.length) { - //debug( "Matched DuckTyped method: " + name ); if (isPerfectMatch(types, sig)) { info = candidate; @@ -348,16 +334,7 @@ private MBeanInfo _getMBeanInfo() final Descriptor descriptor = descriptor(); final MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[] {ATTRIBUTE_CHANGE_NOTIF_INFO}; - final MBeanInfo info = new MBeanInfo( - classname, - description, - attrs, - null, - operations, - notifications, - descriptor); - - return info; + return new MBeanInfo(classname, description, attrs, null, operations, notifications, descriptor); } private boolean hasNameAttribute() @@ -376,14 +353,11 @@ private void sanityCheckMBeanInfo() { // verify that we don't have an item with getName() that's marked as a singleton // another ID could be used too (eg 'thread-pool-id'), no way to tell. - if (isSingleton()) + if (isSingleton() && hasNameAttribute()) { - if (hasNameAttribute()) - { AMXLoggerInfo.getLogger().log(Level.FINE, "ConfigBeanJMXSupport (AMX): @Configured interface {0} has getName() which is not a key value. Remove getName() or use @Attribute(key=true)", mIntf.getName()); - } } } @@ -394,11 +368,6 @@ public boolean isSingleton() { return false; } - /* - if (hasConfiguredBug()) { - return false; - } - */ for (final AttributeMethodInfo info : mAttrInfos) { @@ -423,7 +392,7 @@ public boolean isSingleton() // Tricky case FIXME: what if there are List elements. boolean isLeaf() { - return mElementInfos.size() == 0; + return mElementInfos.isEmpty(); } /** partial list (quick check) of legal remoteable types */ @@ -483,7 +452,6 @@ private static boolean isRemoteableType(final Class clazz) private static boolean isRemoteableDuckTyped(final Method m, final DuckTyped duckTyped) { - boolean isRemotable = true; final Class returnType = m.getReturnType(); if (!isRemoteableType(returnType)) @@ -526,32 +494,31 @@ private void findStuff( final List duckTyped) { - for (final Method m : intf.getMethods()) + for (final Method method : intf.getMethods()) { AttributeMethodInfo a; - //debug( "Method: " + m.getName() + " on " + m.getDeclaringClass() ); - if ((a = AttributeMethodInfo.get(m)) != null) + if ((a = AttributeMethodInfo.get(method)) != null) { attrs.add(a); if ( a.returnType() != String.class ) { AMXLoggerInfo.getLogger().log(Level.INFO, AMXLoggerInfo.illegalNonstring, - new Object[]{intf.getName(), m.getName(), a.returnType().getName()}); + new Object[]{intf.getName(), method.getName(), a.returnType().getName()}); } continue; } - ElementMethodInfo e; - if ((e = ElementMethodInfo.get(m)) != null) + ElementMethodInfo element; + if ((element = ElementMethodInfo.get(method)) != null) { - elements.add(e); + elements.add(element); continue; } - final DuckTyped dt = m.getAnnotation(DuckTyped.class); - if (dt != null && isRemoteableDuckTyped(m, dt)) + final DuckTyped dt = method.getAnnotation(DuckTyped.class); + if (dt != null && isRemoteableDuckTyped(method, dt)) { - duckTyped.add(new DuckTypedInfo(m, dt)); + duckTyped.add(new DuckTypedInfo(method, dt)); } } } @@ -568,9 +535,9 @@ public List sanityCheckConfigured() problems.add( "Missing defaultValue for Boolean @Configured " + mIntf.getName() + ".get" + info.attrName() + "()" ); } } - if ( problems.size() != 0 ) + if (!problems.isEmpty()) { - System.out.println( CollectionUtil.toString( problems, "\n" ) ); + LOGGER.log(Level.SEVERE, CollectionUtil.toString(problems, "\n" )); } return problems; } @@ -754,9 +721,7 @@ public MBeanOperationInfo duckTypedToMBeanOperationInfo(final DuckTypedInfo info } final MBeanParameterInfo[] paramInfosArray = CollectionUtil.toArray(paramInfos, MBeanParameterInfo.class); - final MBeanOperationInfo opInfo = new MBeanOperationInfo(name, description, - paramInfosArray, type.getName(), impact, descriptor); - return opInfo; + return new MBeanOperationInfo(name, description, paramInfosArray, type.getName(), impact, descriptor); } public MBeanOperationInfo[] toMBeanOperationInfos() @@ -793,9 +758,7 @@ private void addAnnotationsToDescriptor(final Descriptor d, final AttributeMetho continue; } - //debug( "INVOKING: " + fieldName + ", returnType = " + m.getReturnType() ); - if (m.getParameterTypes().length == 0) - { + if (m.getParameterCount() == 0) { try { final Object fieldValue = m.invoke(a); @@ -824,7 +787,6 @@ public MBeanAttributeInfo attributeToMBeanAttributeInfo(final AttributeMethodInf final String name = info.attrName(); final String xmlName = info.xmlName(); descriptor.setField(DESC_XML_NAME, xmlName); - //debug( m.getName() + " => " + name + " => " + xmlName ); if (info.pattern() != null) { @@ -856,15 +818,13 @@ public MBeanAttributeInfo attributeToMBeanAttributeInfo(final AttributeMethodInf // we assume that all getters are writeable for now final boolean isWriteable = true; final boolean isIs = false; - final MBeanAttributeInfo attrInfo = - new MBeanAttributeInfo(name, type.getName(), description, isReadable, isWriteable, isIs, descriptor); - return attrInfo; + return new MBeanAttributeInfo(name, type.getName(), description, isReadable, isWriteable, isIs, descriptor); } /** An @Element("*") is anonymous, no specified type, could be anything */ public static final String ANONYMOUS_SUB_ELEMENT = "*"; - private static abstract class MethodInfo + private abstract static class MethodInfo { protected final Method mMethod; @@ -955,7 +915,6 @@ public List> anonymousTypes() { return null; } - //System.out.println( "ANONYMOUS ELEMENT LIST: " + anon ); final Class[] interfaces = getTypesImplementing(anon); final List> types = ListUtil.newList(); @@ -967,11 +926,13 @@ public List> anonymousTypes() return types; } + @Override public boolean required() { return mElement.required(); } + @Override public boolean key() { return mElement.key(); @@ -996,7 +957,6 @@ public static Class[] getTypesImplementing(final Class clazz) final String classname = model.targetTypeName; final Class intf = model.classLoaderHolder.loadClass(classname); interfaces[i] = intf; - //System.out.println( "Loaded: " + intf + " with tagName of " + model.getTagName() ); ++i; } } @@ -1005,8 +965,7 @@ public static Class[] getTypesImplementing(final Class clazz) } catch (final Exception e) { - AMXLoggerInfo.getLogger().log( Level.INFO, AMXLoggerInfo.cantGetTypesImplementing, - new Object[] {clazz, e.getLocalizedMessage()} ); + AMXLoggerInfo.getLogger().log( Level.INFO, AMXLoggerInfo.cantGetTypesImplementing, new Object[] {clazz, e.getLocalizedMessage()} ); throw new RuntimeException(e); } } @@ -1042,43 +1001,37 @@ private static boolean isIntegral(final String s) /** Create the default min/max values for primitive types */ private static Map, long[]> makeMIN_MAX() { - final Map, long[]> m = new HashMap, long[]>(); + final Map, long[]> minMaxPairs = new HashMap, long[]>(); - long[] mm = new long[] + long[] minMaxPair = new long[] { Byte.MIN_VALUE, Byte.MAX_VALUE }; - m.put(byte.class, mm); - m.put(Byte.class, mm); + minMaxPairs.put(byte.class, minMaxPair); + minMaxPairs.put(Byte.class, minMaxPair); - mm = new long[] + minMaxPair = new long[] { Short.MIN_VALUE, Short.MAX_VALUE }; - m.put(short.class, mm); - m.put(Short.class, mm); + minMaxPairs.put(short.class, minMaxPair); + minMaxPairs.put(Short.class, minMaxPair); - mm = new long[] + minMaxPair = new long[] { Integer.MIN_VALUE, Integer.MAX_VALUE }; - m.put(int.class, mm); - m.put(Integer.class, mm); + minMaxPairs.put(int.class, minMaxPair); + minMaxPairs.put(Integer.class, minMaxPair); - mm = new long[] + minMaxPair = new long[] { Long.MIN_VALUE, Long.MAX_VALUE }; - m.put(long.class, mm); - m.put(Long.class, mm); + minMaxPairs.put(long.class, minMaxPair); + minMaxPairs.put(Long.class, minMaxPair); - /* - m.put(PositiveInteger.class, new long[] { 1, Integer.MAX_VALUE } ); - m.put(NonNegativeInteger.class, new long[] { 0, Integer.MAX_VALUE } ); - m.put(Port.class, new long[] { 0, 65535 } ); - */ - - return m; + return minMaxPairs; } private static final Map, long[]> MIN_MAX = makeMIN_MAX(); @@ -1109,11 +1062,13 @@ public Attribute attribute() return mAttribute; } + @Override public boolean required() { return mAttribute.required(); } + @Override public boolean key() { return mAttribute.key(); @@ -1278,6 +1233,7 @@ public Class[] signature() return method().getParameterTypes(); } + @Override public String toString() { String paramsString = ""; @@ -1288,7 +1244,7 @@ public String toString() final String delim = ", "; for (final Class paramClass : method().getParameterTypes()) { - builder.append(ClassUtil.stripPackageName(paramClass.getName()) + delim); + builder.append(ClassUtil.stripPackageName(paramClass.getName())).append(delim); } builder.setLength(builder.length() - delim.length()); paramsString = builder.toString(); @@ -1305,8 +1261,7 @@ public String toString() */ public Set> childInterfaces() { - final Set> intfs = childInterfaces(mElementInfos); - return intfs; + return childInterfaces(mElementInfos); } private static Class internalReturnType(final Method method) @@ -1339,8 +1294,8 @@ private static Class internalReturnType(final Method method) } catch (final Exception e) { - System.out.println("AMX ConfigBeanAMXSupport: can't get generic return type for method " + - method.getDeclaringClass().getName() + "." + method.getName() + "(): " + e.getClass().getName() + " = " + e.getMessage()); + LOGGER.log(Level.SEVERE, "AMX ConfigBeanAMXSupport: can''t get generic return type for method {0}.{1}(): {2} = {3}", + new Object[]{method.getDeclaringClass().getName(), method.getName(), e.getClass().getName(), e.getMessage()}); } return returnType; @@ -1462,7 +1417,6 @@ public MBeanAttributeInfo elementToMBeanAttributeInfo(final Method m) final String name = info.attrName(); // eg strip the "get" final String xmlName = info.xmlName(); - //debug( m.getName() + " => " + name + " => " + xmlName ); final Class methodReturnType = info.returnType(); Class returnType = null; @@ -1549,7 +1503,7 @@ public static String toXMLName(final String name) return name == null ? name : Dom.convertName(name); } - private final static String DEFAULT_NAME_HINT = "name"; + private static final String DEFAULT_NAME_HINT = "name"; private static final class NameHint { @@ -1590,39 +1544,20 @@ private NameHint findNameHint() return new NameHint(mKey); } - // final String configuredBugKey = configuredBugKey(); - for (final AttributeMethodInfo info : mAttrInfos) { if (info.key()) { - //debug( "findNameHint: mKey = " + mKey + ", info says " + info.xmlName() ); return new NameHint(info.xmlName()); } - /* - else if (configuredBugKey != null && info.attrName().equalsIgnoreCase(configuredBugKey)) { - //debug( "findNameHint: mKey = " + mKey + ", workaround says " + configuredBugKey ); - return new NameHint(configuredBugKey); - } - */ } - - /** - Is this possible? - for (final ElementMethodInfo info : mElements.values()) { - if (info.getElement().key()) { - return new NameHint(info.getName(), true); - } - - } - */ return NameHint.NAME; } public Map getDefaultValues(final boolean useAttributeNames) { - final Map m = new HashMap(); + final Map defaultValueMap = new HashMap(); final MBeanInfo info = getMBeanInfo(); for (final MBeanAttributeInfo attrInfo : info.getAttributes()) @@ -1634,40 +1569,10 @@ public Map getDefaultValues(final boolean useAttributeNames) { final String attrName = attrInfo.getName(); final String name = useAttributeNames ? attrName : xmlName(attrInfo, attrName); - m.put(name, defaultValue); + defaultValueMap.put(name, defaultValue); } } - return m; - } - - private static void debug(final String s) - { - System.out.println("### " + s); + return defaultValueMap; } } - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanRegistry.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanRegistry.java index 3c4135e9f31..0d1b3d2d8b4 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanRegistry.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/ConfigBeanRegistry.java @@ -37,11 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ - -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.impl.config; @@ -59,7 +55,6 @@ */ @Taxonomy( stability=Stability.NOT_AN_INTERFACE ) public final class ConfigBeanRegistry { - private static void debug( final String s ) { System.out.println(s); } public static final class MBeanInstance { @@ -102,7 +97,6 @@ public synchronized void add(final ConfigBean cb, final ObjectName objectName, final MBeanInstance mb = new MBeanInstance(cb, objectName, impl); mFromConfigBean.put(cb, mb ); mFromObjectName.put(objectName, mb); - //debug( "ConfigBeanRegistry.add(): " + objectName ); } public synchronized void remove(final ObjectName objectName) @@ -113,7 +107,6 @@ public synchronized void remove(final ObjectName objectName) mFromObjectName.remove(objectName); mFromConfigBean.remove(mb.mConfigBean); } - //debug( "ConfigBeanRegistry.remove(): " + objectName ); } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXImplBase.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXImplBase.java index 1af9b36e74a..55509535928 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXImplBase.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXImplBase.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import java.lang.reflect.InvocationTargetException; @@ -56,7 +58,6 @@ import org.glassfish.admin.amx.core.Util; import org.glassfish.admin.amx.core.proxy.ProxyFactory; import org.glassfish.admin.amx.impl.AMXStartupService; -import org.glassfish.admin.amx.impl.util.ImplUtil; import org.glassfish.admin.amx.impl.util.MBeanInfoSupport; import org.glassfish.admin.amx.impl.util.ObjectNameBuilder; import org.glassfish.admin.amx.util.*; @@ -91,18 +92,13 @@ If there is no getter or setter Method, then the getAttributeManually() or public class AMXImplBase extends MBeanImplBase implements DynamicMBean, NotificationEmitter, AMX_SPI { - /** console debug */ - protected static void cdebug(final String s) { - System.out.println(s); - } - protected static final String GET = "get"; protected static final String SET = "set"; private final ObjectName mParent; // subclasses should set this value protected volatile MBeanInfo mMBeanInfo; - /** Whether AttributeChangeNotifications aree mitted. */ - private final boolean mEmitAttributeChangeNotifications = true; + /** Whether AttributeChangeNotifications are mitted. */ + private static final boolean M_EMIT_ATTRIBUTE_CHANGE_NOTIFICATIONS = true; private static final Logger logger = AMXLoggerInfo.getLogger(); @@ -128,22 +124,23 @@ public AMXImplBase( } + @Override public MBeanInfo getMBeanInfo() { return mMBeanInfo; } protected final boolean shouldEmitNotifications() { - return (mEmitAttributeChangeNotifications && getListenerCount() != 0); + return (M_EMIT_ATTRIBUTE_CHANGE_NOTIFICATIONS && getListenerCount() != 0); } private static final MBeanNotificationInfo[] EMPTY_NOTIFICATIONS = new MBeanNotificationInfo[0]; + @Override public MBeanNotificationInfo[] getNotificationInfo() { return (EMPTY_NOTIFICATIONS); } protected ProxyFactory getProxyFactory() { - //return( ProxyFactory.getInstance( mConnectionSource, true ) ); return (ProxyFactory.getInstance(getMBeanServer())); } @@ -163,6 +160,7 @@ protected AMXProxy getSelf() { } + @Override public final ObjectName getParent() { return mParent; } @@ -184,10 +182,11 @@ public MBeanTrackerMBean getMBeanTracker() { } + @Override public ObjectName[] getChildren() { final Set children = getMBeanTracker().getChildrenOf(getObjectName()); if (children == null) { - return null; + return new ObjectName[0]; } return CollectionUtil.toArray(children, ObjectName.class); @@ -224,7 +223,6 @@ public Map getChildrenMap(final String type) { protected boolean supportsChildren() { - // return getSelf().extra().subTypes() != null; return true; } @@ -247,7 +245,6 @@ protected ObjectName child(final String type) { protected ObjectName child(final Class intf) { final String type = Util.deduceType(intf); - //System.out.println( "child: deduceType = " + type ); return child(type); } @@ -338,6 +335,7 @@ and finally by calling getAttributeManually(), which a subclass @param name name of the Attribute @return value of the Attribute */ + @Override public final Object getAttribute(final String name) throws AttributeNotFoundException { Object result = null; @@ -374,15 +372,11 @@ protected boolean attributeTypeMatches(final String attributeName, final Class children = null; for (final String type : types) { children = getChildrenMap(type); - if (children.keySet().size() != 0) { + if (!children.keySet().isEmpty()) { break; } } - if (children == null || children.keySet().size() == 0) { + if (children == null || children.keySet().isEmpty()) { result = EMPTY_OBJECT_NAMES; } else { result = new ObjectName[children.keySet().size()]; @@ -525,7 +508,6 @@ protected ObjectName[] getObjectNamesForAttribute(final String attributeName) { /** get child ObjectName corresponding to the AttributeName */ protected ObjectName getObjectNameAttribute(final String attributeName) { final String[] types = attributeNameToType(attributeName); - //cdebug( "getObjectNameAttribute: " + attributeName + ", look for types: " + StringUtil.toString(types) ); ObjectName result = null; for (final String type : types) { @@ -534,7 +516,6 @@ protected ObjectName getObjectNameAttribute(final String attributeName) { } } - //cdebug( "getObjectNameAttribute: " + attributeName + " = " + result); return result; } @@ -558,6 +539,7 @@ protected void setAttributeManually(final Attribute attr) } + @Override public void setAttribute(final Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException { final String name = attr.getName(); @@ -566,16 +548,9 @@ public void setAttribute(final Attribute attr) throw new IllegalArgumentException("Attribute is read-only: " + attr.getName()); } - boolean failure = true; - try { setAttributeInternal(attr); - failure = false; - } catch (AttributeNotFoundException e) { - throw e; - } catch (InvalidAttributeValueException e) { - throw e; - } catch (RuntimeException e) { + } catch (AttributeNotFoundException | InvalidAttributeValueException | RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); @@ -591,12 +566,9 @@ and finally by calling setAttributeManually(), which a subclass @param attr the Attribute */ - protected void setAttributeInternal(final Attribute attr) - throws AttributeNotFoundException, InvalidAttributeValueException, - ReflectionException, MBeanException { + protected void setAttributeInternal(final Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException { trace("setAttribute: " + attr.getName() + " = " + attr.getValue()); - boolean handleManually = false; final Method m = findSetter(attr); boolean shouldEmitNotifications = shouldEmitNotifications(); @@ -647,7 +619,6 @@ protected synchronized void sendAttributeChangeNotification( final AttributeChangeNotification n = builder.buildAttributeChange(msg, name, attrType, when, oldValue, newValue); - //System.out.println("AttributeChangeNotification: " + AttributeChangeNotificationStringifier.DEFAULT.stringify(n)); logger.log(Level.INFO, AMXLoggerInfo.attributeChangeNotification, AttributeChangeNotificationStringifier.DEFAULT.stringify(n)); sendNotification(n); } @@ -657,6 +628,7 @@ protected synchronized void sendAttributeChangeNotification( Note that the default implementation sets attributes one at a time, but that MBeans with transactional requirements (eg configuration) may wish to set them as a group. */ + @Override public AttributeList setAttributes(final AttributeList attrs) { final AttributeList successList = new AttributeList(); @@ -689,7 +661,7 @@ Find a getXXX() method that matches the Attribute @param name the name to which "get" will be prepended @return a Method or null if not found */ - static private final Class[] GETTER_SIG = new Class[0]; + private static final Class[] GETTER_SIG = new Class[0]; protected final Method findGetter(String name) { final String methodName = GET + name; @@ -733,7 +705,6 @@ protected final Method findSetter(final Attribute attr) { final Class primitiveClass = ClassUtil.objectClassToPrimitiveClass(valueClass); if (setter == null && primitiveClass != valueClass) { - //trace( "findSetter: retrying for primitive class: " + primitiveClass ); // the Attribute value is always an object. But it may be // that the setter takes a primitive type. So for example, // the Attribute may contain a value of type Boolean, but the setter @@ -746,7 +717,6 @@ protected final Method findSetter(final Attribute attr) { } protected static final String GET_PREFIX = "get"; protected static final String OBJECT_NAME_SUFFIX = "ObjectName"; - // protected static final String OBJECT_NAME_MAP_SUFFIX = "ObjectNameMap"; protected boolean operationNameMatches( final String operationName, @@ -800,26 +770,20 @@ Generic handling of invoke(). Converts the types[] to a Class[], then attempts to locate a suitable Method. If a suitable Method is found, it is invoked. If not found the subclass is expected to handle it in invokeManually(); */ - public final Object invoke( - String operationName, - Object[] args, - String[] types) - throws MBeanException, ReflectionException { + @Override + public final Object invoke(String operationName, Object[] args, String[] types) throws MBeanException, ReflectionException { Object result = null; - boolean unimplemented = false; final int numArgs = args != null ? args.length : 0; - //cdebug("invoke: " + operationName + ", num args = " + numArgs ); try { final Class[] signature = ClassUtil.signatureFromClassnames(types); - final Method m = findMethod(operationName, signature); - if (m != null) { + final Method invokeMethod = findMethod(operationName, signature); + if (invokeMethod != null) { debugMethod("invoking method: " + operationName, args); - result = m.invoke(this, args); + result = invokeMethod.invoke(this, args); } else if (operationName.equals("toString") && numArgs == 0) { result = toString(); } else { - //cdebug( "No method found for " + operationName ); result = invokeManually(operationName, args, types); } } catch (Exception e) { @@ -851,6 +815,7 @@ protected Object invokeManually( A subclass might need to override this method if its name contains characters that are illegal for the ObjectName. */ + @Override public String getName() { String name = Util.getNameProp(getObjectName()); @@ -876,6 +841,7 @@ protected ObjectName preRegisterModifyName( Since it's called only once (per instance) for an MBean Registration, it has no performance impact on later use, but guarantees visibility of all non-final instance variables. */ + @Override public final synchronized ObjectName preRegister( final MBeanServer server, final ObjectName nameIn) @@ -915,15 +881,16 @@ protected MBeanInfo postRegisterModifyMBeanInfo(final MBeanInfo info) { /** Important: must be synchronized so that preDeregisterHook cannot be called prior to existing postRegisterHook() */ + @Override protected synchronized void postRegisterHook(final Boolean registrationSucceeded) { - if (registrationSucceeded.booleanValue()) { + if (registrationSucceeded) { mMBeanInfo = postRegisterModifyMBeanInfo(mMBeanInfo); registerChildren(); } } - - // hook for subclasses + protected void registerChildren() { + // hook for subclasses } /** Important: must be synchronized so that it cannot be called prior to exiting postRegisterHook() */ @@ -960,6 +927,7 @@ protected String stringify(Object o) { return (SmartStringifier.toString(o)); } + @Override public String toString() { return java(); } @@ -982,11 +950,3 @@ protected ObjectNameBuilder getObjectNames() { return new ObjectNameBuilder(getMBeanServer(), getObjectName()); } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXSupport.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXSupport.java index 832a7af9fd8..ed8072bf1ee 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXSupport.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/AMXSupport.java @@ -44,14 +44,4 @@ MBeans for AMX. */ public interface AMXSupport { -} - - - - - - - - - - +} \ No newline at end of file diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/BulkAccessImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/BulkAccessImpl.java index f02f83ac41d..b1f612b2778 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/BulkAccessImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/BulkAccessImpl.java @@ -205,14 +205,3 @@ public Object[] bulkInvoke( return (results); } } - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ComplianceMonitor.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ComplianceMonitor.java index b73dec96a3c..170e85545c1 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ComplianceMonitor.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ComplianceMonitor.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import java.util.ArrayList; @@ -51,7 +53,6 @@ import javax.management.*; import org.glassfish.admin.amx.base.DomainRoot; import org.glassfish.admin.amx.core.AMXValidator; -import org.glassfish.admin.amx.impl.util.ImplUtil; import org.glassfish.admin.amx.util.AMXLoggerInfo; import org.glassfish.admin.amx.util.jmx.JMXUtil; @@ -70,7 +71,7 @@ public final class ComplianceMonitor implements NotificationListener { /** offloads the validation so as not to block during Notifications */ private final ValidatorThread mValidatorThread; - private final Logger mLogger = AMXLoggerInfo.getLogger(); + private static final Logger MLOGGER = AMXLoggerInfo.getLogger(); private ComplianceMonitor(final DomainRoot domainRoot) { mDomainRoot = domainRoot; @@ -84,7 +85,7 @@ private ComplianceMonitor(final DomainRoot domainRoot) { mValidatorThread = new ValidatorThread(mServer, mValidationLevel, mUnregisterNonCompliant, mLogInaccessibleAttributes); - mLogger.log(Level.INFO, AMXLoggerInfo.aMXComplianceMonitorLevel, new Object[] {mValidationLevel, mUnregisterNonCompliant, + MLOGGER.log(Level.INFO, AMXLoggerInfo.aMXComplianceMonitorLevel, new Object[] {mValidationLevel, mUnregisterNonCompliant, mLogInaccessibleAttributes}); } @@ -103,7 +104,6 @@ private void listen() { // queue all existing MBeans final Set existing = JMXUtil.queryLocalMBeans(mServer, mDomainRoot.objectName().getDomain(), System.getProperty("com.sun.ass.instanceName")); for (final ObjectName objectName : existing) { - //debug( "Queueing for validation: " + objectName ); validate(objectName); } } @@ -139,6 +139,7 @@ public void start() { } } + @Override public void handleNotification(final Notification notifIn, final Object handback) { if ((notifIn instanceof MBeanServerNotification) && notifIn.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) { @@ -198,6 +199,7 @@ public void add(final ObjectName objectName) { mMBeans.add(objectName); } + @Override public void run() { try { doRun(); @@ -206,8 +208,7 @@ public void run() { } } - protected void doRun() throws InterruptedException { - //debug( "ValidatorThread.doRun(): started" ); + protected void doRun() throws InterruptedException {; while (true) { final ObjectName next = mMBeans.take(); // BLOCK until ready final List toValidate = new ArrayList(); @@ -220,7 +221,6 @@ protected void doRun() throws InterruptedException { // process available MBeans as a group so we can emit summary information as a group. final AMXValidator validator = new AMXValidator(mServer, mValidationLevel, mUnregisterNonCompliant, mLogInaccessibleAttributes); try { - //debug( "VALIDATING MBeans: " + toValidate.size() ); final ObjectName[] objectNames = new ObjectName[toValidate.size()]; toValidate.toArray(objectNames); final AMXValidator.ValidationResult result = validator.validate(objectNames); @@ -238,29 +238,4 @@ protected void doRun() throws InterruptedException { } } - private static void debug(final Object o) { - System.out.println(o.toString()); - } } - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/DomainRootImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/DomainRootImpl.java index 69364e2fa8e..ac0bee96fb6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/DomainRootImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/DomainRootImpl.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import com.sun.appserv.server.util.Version; @@ -105,19 +107,21 @@ public ObjectName getBulkAccess() { return child(BulkAccess.class); } + @Override protected ObjectName preRegisterHook(final MBeanServer server, final ObjectName selfObjectName) throws Exception { // DomainRoot has not yet been registered; any MBeans that exist are non-compliant // because they cannot have a Parent. final Set existing = JMXUtil.queryAllInDomain(server, selfObjectName.getDomain()); - if (existing.size() != 0) { + if (!existing.isEmpty()) { logger.log(Level.INFO, AMXLoggerInfo.mbeanExist, CollectionUtil.toString(existing, ", ")); } return selfObjectName; } + @Override public void preRegisterDone() throws Exception { super.preRegisterDone(); @@ -129,7 +133,7 @@ protected void postRegisterHook(final Boolean registrationSucceeded) { // Start compliance after everything else; it uses key MBeans like Paths //turning off ComplianceMonitor for now to help embedded runs. - if (registrationSucceeded.booleanValue()) { + if (registrationSucceeded) { // start compliance monitoring immediately, even before children are registered mCompliance = ComplianceMonitor.getInstance(getDomainRootProxy()); mCompliance.start(); @@ -158,10 +162,8 @@ public String getAppserverDomainName() { @Override protected final void registerChildren() { super.registerChildren(); - //System.out.println("Registering children of DomainRoot"); final ObjectName self = getObjectName(); - final ObjectNameBuilder objectNames = - new ObjectNameBuilder(getMBeanServer(), self); + final ObjectNameBuilder objectNames = new ObjectNameBuilder(getMBeanServer(), self); ObjectName childObjectName = null; Object mbean = null; @@ -204,7 +206,7 @@ protected final void registerChildren() { mbean = new ExtImpl(self); registerChild(mbean, childObjectName); - childObjectName = objectNames.buildChildObjectName(server, extObjectName, Realms.class); + childObjectName = ObjectNameBuilder.buildChildObjectName(server, extObjectName, Realms.class); mbean = new RealmsImpl(extObjectName); registerChild(mbean, childObjectName); @@ -255,20 +257,6 @@ public Object[] getUptimeMillis() { final long elapsed = System.currentTimeMillis() - env.getStartupContext().getCreationTime(); final Duration duration = new Duration(elapsed); - return new Object[]{ - elapsed, duration.toString() - }; + return new Object[]{elapsed, duration.toString()}; } } - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ExtImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ExtImpl.java index 4b84e633ad6..d97c0c344f5 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ExtImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ExtImpl.java @@ -53,14 +53,3 @@ public ExtImpl(final ObjectName parentObjectName) { } // children are added elsewhere, by other modules } - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/LoggingImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/LoggingImpl.java index 3bc4c39fd50..bae50a7e336 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/LoggingImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/LoggingImpl.java @@ -67,7 +67,6 @@ import static org.glassfish.admin.amx.logging.LogFileAccess.*; import static org.glassfish.admin.amx.logging.LogRecordEmitter.*; -//import com.sun.enterprise.server.logging.LoggingImplHook; /** * Implementation of {@link Logging}.

The following is a GlassFish V2 * comment, and needs work for v3:
AMX Logging MBean is hooked directly into @@ -75,14 +74,13 @@ * com.sun.enterprise.server.logging.FileandSyslogHandler which uses * com.sun.enterprise.server.logging.AMXLoggingHook to instantiate and call an * instance of LoggingImpl. + * @deprecated from Payara 5.193 as does not appear to be used */ public final class LoggingImpl extends AMXImplBase //implements /*Logging,*/ LoggingImplHook { private final Map mLevelToNotificationTypeMap; private final Map mNotificationTypeToNotificationBuilderMap; - private static final String SERVER_LOG_NAME = "server.log"; - private static final String ACCESS_LOG_NAME = "access.log"; private final LoggingConfigImpl loggingConfig; private final GFFileHandler gfFileHandler; private final LogFilter logFilter; @@ -90,7 +88,8 @@ public final class LoggingImpl extends AMXImplBase //implements /*Logging,*/ Log private final Logger logger; private final ServiceLocator mHabitat; final String FILE_SEP; - private final String mServerName; + + private static MBeanNotificationInfo[] SELF_NOTIFICATION_INFOS = null; /** * Used internally to get the Logging ObjectName for a particular server @@ -111,7 +110,6 @@ public static ObjectName getObjectName(final String serverName) { public LoggingImpl(final ObjectName parent, final String serverName) { super(parent, Logging.class); - mServerName = serverName; FILE_SEP = System.getProperty("file.separator"); mLevelToNotificationTypeMap = initLevelToNotificationTypeMap(); @@ -125,29 +123,6 @@ public LoggingImpl(final ObjectName parent, final String serverName) { logger = Logger.getAnonymousLogger(); } - /** - * Hook for subclass to modify anything in MBeanInfo. - * - * @Override - */ - /* - @Override - protected MBeanInfo - postRegisterModifyMBeanInfo( final MBeanInfo info ) - { - final MBeanOperationInfo[] ops = info.getOperations(); - - final int idx = JMXUtil.findMBeanOperationInfo( info, "queryServerLog", null); - - final MBeanOperationInfo op = ops[idx]; - ops[idx] = new MBeanOperationInfo( op.getName(), op.getDescription(), - op.getSignature(), Map.class.getName(), - MBeanOperationInfo.INFO ); - - return JMXUtil.newMBeanInfo( info, ops ); - } - */ - private static MBeanNotificationInfo[] SELF_NOTIFICATION_INFOS = null; /** * getMBeanInfo() can be called frequently. By making this static, we avoid @@ -164,6 +139,7 @@ private static synchronized MBeanNotificationInfo[] getSelfNotificationInfos() { return (SELF_NOTIFICATION_INFOS); } + @Override public MBeanNotificationInfo[] getNotificationInfo() { final MBeanNotificationInfo[] superInfos = super.getNotificationInfo(); @@ -173,11 +149,8 @@ public MBeanNotificationInfo[] getNotificationInfo() { return all; } - /** - * FIXME - */ private void unimplemented() { - throw new RuntimeException("Not implemented."); + throw new UnsupportedOperationException("Not implemented."); } public void setModuleLogLevel( @@ -206,8 +179,7 @@ public String getModuleLogLevel(final String module) { public Map getLoggingProperties() { try { - Map props = loggingConfig.getLoggingProperties(); - return props; + return loggingConfig.getLoggingProperties(); } catch (java.io.IOException e) { logger.log(Level.WARNING, "Can not get module log level"); return null; @@ -284,13 +256,16 @@ public synchronized void rotateAllLogFiles() { public synchronized void rotateLogFile(final String key) { - if (ACCESS_KEY.equals(key)) { - throw new IllegalArgumentException("not supported: " + key); - //getLogMBean().rotateAccessLog(); - } else if (SERVER_KEY.equals(key)) { - gfFileHandler.rotate(); - } else { + if (null == key) { throw new IllegalArgumentException("" + key); + } else switch (key) { + case ACCESS_KEY: + throw new IllegalArgumentException("not supported: " + key); + case SERVER_KEY: + gfFileHandler.rotate(); + break; + default: + throw new IllegalArgumentException("" + key); } } @@ -355,10 +330,9 @@ public List queryServerLog( Set modules, List nameValuePairs, String anySearch) { - final List result = queryServerLogInternal( + return queryServerLogInternal( name, startIndex, searchForward, maximumNumberOfResults, fromTime, toTime, logLevel, modules, nameValuePairs, anySearch); - return result; } private List queryServerLogInternal( @@ -394,22 +368,23 @@ private List queryServerLogInternal( sortAscending = false; } - final AttributeList result = logFilter.getLogRecordsUsingQuery(actualName, - Long.valueOf(startIndex), + final AttributeList result = logFilter.getLogRecordsUsingQuery(actualName, startIndex, searchForward, sortAscending, maximumNumberOfResults, - fromTime == null ? null - : new Date(fromTime), - toTime == null ? null - : new Date(toTime), + fromTime == null ? null : new Date(fromTime), + toTime == null ? null : new Date(toTime), logLevel, false, moduleList, props, anySearch); return convertQueryResult(result); } + /** + * This method will always throw an exception + * @throws UnsupportedOperationException + */ public Map[] getErrorInfo() { - unimplemented(); + unimplemented();//throws UnsupportedOperationException final List> infos = Collections.emptyList(); //getLogMBean().getErrorInformation(); @@ -434,7 +409,7 @@ public Map[] getErrorInfo() { return results; } - private static final Integer INTEGER_0 = Integer.valueOf(0); + private static final Integer INTEGER_0 = 0; private static final Map EMPTY_ERROR_DISTRIBUTION_MAP = Collections.emptyMap(); private static final Set LEGAL_DISTRIBUTION_LEVELS = @@ -448,8 +423,7 @@ public Map getErrorDistribution(long timestamp, String level) { unimplemented(); - Map result = - null; //getLogMBean().getErrorDistribution( timestamp, Level.parse( level ) ); + Map result = null; // query may return null instead of an empty Map if (result != null) { @@ -469,47 +443,26 @@ public Map getErrorDistribution(long timestamp, String level) { public void setKeepErrorStatisticsForIntervals(final int num) { unimplemented(); - //getLogMBean().setKeepErrorStatisticsForIntervals( num ); } public int getKeepErrorStatisticsForIntervals() { return 0; - /* - unimplemented(); - return getLogMBean().getKeepErrorStatisticsForIntervals(); - */ } public void setErrorStatisticsIntervalMinutes(final long minutes) { unimplemented(); - //getLogMBean().setErrorStatisticsIntervalDuration( minutes ); } public long getErrorStatisticsIntervalMinutes() { return 0; - /* - unimplemented(); - return getLogMBean().getErrorStatisticsIntervalDuration(); - */ } public String[] getLoggerNames() { return EMPTY_STRING_ARRAY; - /*unimplemented(); - final List names = - TypeCast.checkList( getLogMBean().getLoggerNames(), String.class ); - - return names.toArray( EMPTY_STRING_ARRAY ); */ } public String[] getLoggerNamesUnder(final String loggerName) { unimplemented(); - /* - final List names = TypeCast.checkList( - getLogMBean().getLoggerNamesUnder( loggerName ), String.class ); - - return names.toArray( EMPTY_STRING_ARRAY ); - */ return null; } @@ -541,7 +494,7 @@ public String[] getDiagnosticChecks(String messageID, String moduleName) { public String getDiagnosticURI(final String messageID) { unimplemented(); - return null; //getLogMBean().getDiagnosticURIForMessageId( messageID ); + return null; } private static final Object[] LEVELS_AND_NOTIF_TYPES = new Object[]{ Level.SEVERE, LOG_RECORD_SEVERE_NOTIFICATION_TYPE, @@ -568,6 +521,7 @@ private String logLevelToNotificationType(final Level level) { return mLevelToNotificationTypeMap.get(level); } + @Override protected void preRegisterDone() throws Exception { initNotificationTypeToNotificationBuilderMap(getObjectName()); @@ -624,10 +578,7 @@ private Map logRecordToMap( * Internal use only, called by * com.sun.enterprise.server.logging.AMXLoggingHook. */ - public void privateLoggingHook( - final LogRecord logRecord, - final Formatter formatter) { - //debug( "LoggingImpl.privateLoggingHook: " + formatter.format( logRecord ) ); + public void privateLoggingHook(final LogRecord logRecord, final Formatter formatter) { if (logRecord.getThreadID() == mMyThreadID) { debug("privateLoggingHook: recusive call!!!"); @@ -657,8 +608,6 @@ public void privateLoggingHook( debug("privateLoggingHook: sending: " + notif); sendNotification(notif); - } else { - // debug( "privateLogHook: no listeners for level " + level ); } } finally { mMyThreadID = -1; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MBeanImplBase.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MBeanImplBase.java index 12f58022c12..bab0bee55c0 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MBeanImplBase.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MBeanImplBase.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import org.glassfish.admin.amx.util.AMXDebug; @@ -56,8 +58,8 @@ import java.util.logging.Logger; /** -Absolute base impl class. Should contain only core functionality, -nothing to do with appserver specifics. + * Absolute base impl class. Should contain only core functionality, + * nothing to do with appserver specifics. */ public abstract class MBeanImplBase implements MBeanRegistration, NotificationSender { @@ -104,7 +106,7 @@ public final int getNotificationTypeListenerCount(final String type) { @return an empty array Subclass may wish to override this. */ - synchronized protected final NotificationEmitterSupport getNotificationEmitter() { + protected final synchronized NotificationEmitterSupport getNotificationEmitter() { if (mNotificationEmitter == null) { mNotificationEmitter = new NotificationEmitterSupport(true); } @@ -137,6 +139,7 @@ public synchronized void removeNotificationListener( getNotificationEmitter().removeNotificationListener(listener, filter, handback); } + @Override public void sendNotification(final Notification notification) { getNotificationEmitter().sendNotification(notification); } @@ -325,10 +328,8 @@ protected static String quote(final Object o) { return (StringUtil.quote("" + o)); } - public ObjectName preRegister( - final MBeanServer server, - final ObjectName nameIn) - throws Exception { + @Override + public ObjectName preRegister(final MBeanServer server, final ObjectName nameIn) throws Exception { assert (nameIn != null); mServer = server; mSelfObjectName = nameIn; @@ -340,11 +341,12 @@ public ObjectName preRegister( protected void postRegisterHook(final Boolean registrationSucceeded) { } + @Override public final void postRegister(final Boolean registrationSucceeded) { - if (registrationSucceeded.booleanValue()) { - getMBeanLogger().finest("postRegister: " + getObjectName()); + if (registrationSucceeded) { + getMBeanLogger().log(Level.FINEST, "postRegister: {0}", getObjectName()); } else { - getMBeanLogger().finest("postRegister: FAILURE: " + getObjectName()); + getMBeanLogger().log(Level.FINEST, "postRegister: FAILURE: {0}", getObjectName()); } postRegisterHook(registrationSucceeded); @@ -354,9 +356,10 @@ protected void preDeregisterHook() throws Exception { } + @Override public final void preDeregister() throws Exception { - getMBeanLogger().finest("preDeregister: " + getObjectName()); + getMBeanLogger().log(Level.FINEST, "preDeregister: {0}", getObjectName()); preDeregisterHook(); } @@ -364,8 +367,9 @@ public final void preDeregister() protected void postDeregisterHook() { } + @Override public final void postDeregister() { - getMBeanLogger().finest("postDeregister: " + getObjectName()); + getMBeanLogger().log(Level.FINEST, "postDeregister: {0}", getObjectName()); postDeregisterHook(); @@ -454,24 +458,4 @@ protected void debug(final Object... args) { } } - protected boolean sleepMillis(final long millis) { - boolean interrupted = false; - - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - Thread.interrupted(); - interrupted = true; - } - - return interrupted; - } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MonitoringRootImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MonitoringRootImpl.java index 4294d08e823..75685a6e548 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MonitoringRootImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/MonitoringRootImpl.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payra Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import java.util.logging.Level; @@ -50,7 +52,7 @@ public class MonitoringRootImpl extends AMXImplBase // implements MonitoringRoot { - private final Logger mLogger = AMXLoggerInfo.getLogger(); + private static final Logger MLOGGER = AMXLoggerInfo.getLogger(); public MonitoringRootImpl(final ObjectName parent) { super(parent, MonitoringRoot.class); @@ -66,10 +68,9 @@ protected final void registerChildren() { ObjectName childObjectName = null; Object mbean = null; - mLogger.log(Level.INFO, AMXLoggerInfo.registerChild, System.getProperty("com.sun.aas.instanceName")); + MLOGGER.log(Level.INFO, AMXLoggerInfo.registerChild, System.getProperty("com.sun.aas.instanceName")); // when clustering comes along, some other party will need to register MBeans // for each non-DAS instance - // childObjectName = objectNames.buildChildObjectName(ServerMon.class, AMXGlassfish.DEFAULT.dasName()); childObjectName = objectNames.buildChildObjectName(ServerMon.class, System.getProperty("com.sun.aas.instanceName")); mbean = new ServerMonitoringImpl(self); registerChild(mbean, childObjectName); @@ -79,46 +80,3 @@ public ObjectName[] getServerMon() { return getChildren(ServerMon.class); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ParentChildren.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ParentChildren.java index 1c5730b8ca1..91c1b8d0390 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ParentChildren.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ParentChildren.java @@ -164,39 +164,3 @@ public static String getHierarchyString(final AMXProxy top) { return StringUtil.toLines(pc.toLines(true)); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/PathnamesImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/PathnamesImpl.java index 4d08f51ae86..3112b13097c 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/PathnamesImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/PathnamesImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.impl.mbean; @@ -94,15 +94,11 @@ public ObjectName resolvePath(final String path) { final String parentPath = parser.parentPath(); - //cdebug( "resolvePath: " + parser.toString() + ", parentPath = " + parentPath ); - // fixed query based on the path, which will find all MBeans with that parent path final String props = Util.makeProp(PARENT_PATH_KEY, Util.quoteIfNeeded(parentPath)); final ObjectName pattern = JMXUtil.newObjectNamePattern(getObjectName().getDomain(), props); final Set s = getMBeanServer().queryNames(pattern, null); - //cdebug( "resolvePath: " + path + " = query for parent path: " + pattern + " yields children: " + s.size() ); - ObjectName objectName = null; final String type = parser.type(); final String name = parser.name(); @@ -111,8 +107,6 @@ public ObjectName resolvePath(final String path) { if (type.equals(Util.getTypeProp(child))) { final String nameProp = Util.getNameProp(child); - //cdebug( "type match for " + path + ", objectName = " + child); - if (nameProp == null) { if (name == null) { // no name, we matched on type alone @@ -120,7 +114,6 @@ public ObjectName resolvePath(final String path) { break; } // badly formed: a name is specified, but none is present for this type - //cdebug( "A name is specified in path, but the type has none: path = " + path + ", objectName = " + child); continue; } @@ -143,7 +136,7 @@ public ObjectName resolvePath(final String path) { objectName = child; break; } - } //cdebug( "No match on type: " + type + " != " + Util.getTypeProp(child) ); + } } @@ -154,7 +147,6 @@ public ObjectName resolvePath(final String path) { } if (objectName != null) { - //cdebug( "Matched " + path + " to " + objectName); mPathnameCache.put(path, objectName); } @@ -327,20 +319,3 @@ public String dump(final String path) { return buf.toString(); } } - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/QueryMgrImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/QueryMgrImpl.java index 320b5c595b4..59bf7ebbf32 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/QueryMgrImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/QueryMgrImpl.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import org.glassfish.admin.amx.core.Util; @@ -50,7 +52,6 @@ import org.glassfish.admin.amx.util.CollectionUtil; import javax.management.ObjectName; -import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -72,8 +73,7 @@ public ObjectName[] queryProps(final String props) { return queryPattern(Util.newObjectNamePattern(getJMXDomain(), props)); } - public ObjectName[] queryTypes(final Set types) - throws IOException { + public ObjectName[] queryTypes(final Set types) { final Set result = new HashSet(); for (final ObjectName objectName : queryAll()) { @@ -131,9 +131,7 @@ private Set matchWild( final String[] regexValues = convertToRegex(wildValues); final ObjectNameQueryImpl query = new ObjectNameQueryImpl(); - final Set resultSet = query.matchAll(candidates, regexNames, regexValues); - - return resultSet; + return query.matchAll(candidates, regexNames, regexValues); } public ObjectName[] queryWildAll( @@ -153,7 +151,7 @@ public ObjectName[] queryAll() { return asArray(names); } - private final ObjectName[] asArray(final Set items) { + private ObjectName[] asArray(final Set items) { return CollectionUtil.toArray(items, ObjectName.class); } @@ -190,16 +188,3 @@ public ObjectName[] queryDescendants(final ObjectName parentObjectName) { return Util.toObjectNamesArray(items); } } - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RealmsImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RealmsImpl.java index 25ca074ea7b..1ee8d6698f6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RealmsImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RealmsImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -// Portions Copyright [2017-2018] [Payara Foundation and/or its affiliates] +// Portions Copyright [2017-2019] [Payara Foundation and/or its affiliates] package org.glassfish.admin.amx.impl.mbean; import static java.util.logging.Level.WARNING; @@ -70,7 +70,6 @@ import com.sun.enterprise.config.serverbeans.SecurityService; import com.sun.enterprise.security.SecurityLifecycle; import com.sun.enterprise.security.auth.WebAndEjbToJaasBridge; -import com.sun.enterprise.security.auth.login.LoginContextDriver; import com.sun.enterprise.security.auth.realm.Realm; import com.sun.enterprise.security.auth.realm.RealmsManager; import com.sun.enterprise.security.auth.realm.User; @@ -146,7 +145,7 @@ private void _loadRealms() { } } - if (goodRealms.size() != 0) { + if (!goodRealms.isEmpty()) { String goodRealm = goodRealms.iterator().next(); try { String defaultRealm = getSecurityService().getDefaultRealm(); @@ -306,7 +305,7 @@ public String getAnonymousUser() { // Get FileRealm class name String fileRealmClassName = adminFileAuthRealm.getClassname(); - if (fileRealmClassName != null && !fileRealmClassName.equals(FILE_REALM_CLASSNAME)) { + if (!fileRealmClassName.equals(FILE_REALM_CLASSNAME)) { // This condition can arise if admin-realm is not a File realm. Then the API to extract // the anonymous user should be integrated for the logic below this line of code. for now, // we treat this as an error and instead of throwing exception return false; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RuntimeRootImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RuntimeRootImpl.java index 8ac56372e6c..e44aab9bbb9 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RuntimeRootImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/RuntimeRootImpl.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates // Portions Copyright [2019] [Payara Foundation and/or its affiliates] @@ -154,9 +155,7 @@ public void restartDomain() private NetworkConfig networkConfig() { - final NetworkConfig config = InjectedValues.getInstance().getHabitat().getService( - NetworkConfig.class, ServerEnvironment.DEFAULT_INSTANCE_NAME); - return config; + return InjectedValues.getInstance().getHabitat().getService(NetworkConfig.class, ServerEnvironment.DEFAULT_INSTANCE_NAME); } private static final String ADMIN_LISTENER_NAME = "admin-listener"; @@ -165,8 +164,7 @@ private NetworkListener getAdminListener() { final NetworkConfig network = networkConfig(); - final NetworkListener listener = network.getNetworkListener(ADMIN_LISTENER_NAME); - return listener; + return network.getNetworkListener(ADMIN_LISTENER_NAME); } private int getRESTPort() @@ -190,31 +188,23 @@ public String getRESTBaseURL() throws MalformedURLException } - public String executeREST(final String cmd) - { + public String executeREST(final String cmd) { String result = null; HttpURLConnection conn = null; - try - { + try { final String url = getRESTBaseURL() + cmd; final URL invoke = new URL(url); - //System.out.println( "Opening connection to: " + invoke ); conn = (HttpURLConnection) invoke.openConnection(); final InputStream is = conn.getInputStream(); result = toString(is); is.close(); - } - catch (Exception e) - { + } catch (Exception e) { result = ExceptionUtil.toString(e); - } - finally - { - if (conn != null) - { + } finally { + if (conn != null) { conn.disconnect(); } } @@ -261,38 +251,36 @@ public String getJVMReport(final String type) final String NL = StringUtil.LS; final String target = "das"; String result = "FAILED"; - if ("summary".equals(type)) - { - result = info.getSummary(target); - } - else if ("memory".equals(type)) - { - result = info.getMemoryInformation(target); - } - else if ("thread".equals(type)) - { - result = info.getThreadDump(target); - } - else if ("class".equals(type)) - { - result = info.getClassInformation(target); - } - else if ("log".equals(type)) - { - result = info.getLogInformation(target); - } - else if ("all".equals(type)) - { - result = "SUMMARY" + NL + NL + getJVMReport("summary") + NL + NL + - "MEMORY" + NL + NL + getJVMReport("memory") + NL + NL + - "THREADS" + NL + NL + getJVMReport("thread") + NL + NL + - "CLASSES" + NL + NL + getJVMReport("class") + NL + NL + - "LOGGING" + NL + NL + getJVMReport("log"); - } - else + if (null == type) { throw new IllegalArgumentException("Unsupported JVM report type: " + type); } + else switch (type) { + case "summary": + result = info.getSummary(target); + break; + case "memory": + result = info.getMemoryInformation(target); + break; + case "thread": + result = info.getThreadDump(target); + break; + case "class": + result = info.getClassInformation(target); + break; + case "log": + result = info.getLogInformation(target); + break; + case "all": + result = "SUMMARY" + NL + NL + getJVMReport("summary") + NL + NL + + "MEMORY" + NL + NL + getJVMReport("memory") + NL + NL + + "THREADS" + NL + NL + getJVMReport("thread") + NL + NL + + "CLASSES" + NL + NL + getJVMReport("class") + NL + NL + + "LOGGING" + NL + NL + getJVMReport("log"); + break; + default: + throw new IllegalArgumentException("Unsupported JVM report type: " + type); + } if (result != null) { @@ -316,7 +304,6 @@ public boolean isStartedInDebugMode() if( opt.startsWith(prefix) ) { final String value = opt.substring( prefix.length() ).toLowerCase(Locale.ENGLISH); - //System.out.println( "RuntimeRootImpl.isRunningInDebugMode(): found: " + prefix + value ); inDebugMode = Boolean.parseBoolean(value); break; } @@ -324,29 +311,4 @@ public boolean isStartedInDebugMode() } return inDebugMode; } -} - - - - - - - - - - - - - - - - - - - - - - - - - +} \ No newline at end of file diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SampleImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SampleImpl.java index 414200c059b..5d172c6f053 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SampleImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SampleImpl.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import javax.management.Attribute; @@ -45,16 +47,11 @@ import javax.management.MBeanInfo; import javax.management.ObjectName; import javax.management.openmbean.*; -import javax.management.remote.JMXServiceURL; import java.io.Serializable; import java.util.Collections; -import java.util.HashMap; import java.util.Map; -import java.util.Map.Entry; import java.util.List; -import java.util.ArrayList; -import java.util.HashSet; import java.util.HashMap; import org.glassfish.admin.amx.base.Sample; @@ -63,7 +60,6 @@ import org.glassfish.admin.amx.util.MapUtil; import org.glassfish.admin.amx.util.ListUtil; import org.glassfish.admin.amx.util.SetUtil; -import org.glassfish.admin.amx.util.StringUtil; import org.glassfish.admin.amx.util.CollectionUtil; import org.glassfish.admin.amx.core.Util; @@ -97,7 +93,6 @@ public void addAttribute(final String name, final Serializable value) { } mAttributes.put(name, value); - //mExtendedMBeanInfo = null; } public void removeAttribute(final String name) { @@ -108,22 +103,21 @@ public void removeAttribute(final String name) { private synchronized MBeanInfo createMBeanInfo(final MBeanInfo baseMBeanInfo) { final MBeanAttributeInfo[] dynamicAttrInfos = new MBeanAttributeInfo[mAttributes.keySet().size()]; int i = 0; - for (final Entry entry : mAttributes.entrySet()) { - String name = entry.getKey(); - final Object value = entry.getValue(); + for (Map.Entry entry : mAttributes.entrySet()) { + final Serializable value = entry.getValue(); final String type = value == null ? String.class.getName() : value.getClass().getName(); - dynamicAttrInfos[i] = new MBeanAttributeInfo(name, type, "dynamically-added Attribute", + dynamicAttrInfos[i] = new MBeanAttributeInfo(entry.getKey(), type, "dynamically-added Attribute", true, true, false); ++i; } - final MBeanAttributeInfo[] attrInfos = - JMXUtil.mergeMBeanAttributeInfos(dynamicAttrInfos, baseMBeanInfo.getAttributes()); + final MBeanAttributeInfo[] attrInfos = JMXUtil.mergeMBeanAttributeInfos(dynamicAttrInfos, baseMBeanInfo.getAttributes()); return (JMXUtil.newMBeanInfo(baseMBeanInfo, attrInfos)); } + @Override public synchronized MBeanInfo getMBeanInfo() { if (mExtendedMBeanInfo == null) { mExtendedMBeanInfo = createMBeanInfo(super.getMBeanInfo()); @@ -132,6 +126,7 @@ public synchronized MBeanInfo getMBeanInfo() { return (mExtendedMBeanInfo); } + @Override protected Serializable getAttributeManually(final String name) { if (!mAttributes.containsKey(name)) { throw new RuntimeException(new AttributeNotFoundException(name)); @@ -139,6 +134,7 @@ protected Serializable getAttributeManually(final String name) { return mAttributes.get(name); } + @Override protected void setAttributeManually(final Attribute attr) { mAttributes.put(attr.getName(), Serializable.class.cast(attr.getValue())); } @@ -155,6 +151,7 @@ public EmitterThread(final Serializable data, final int numNotifs, final long in mIntervalMillis = intervalMillis; } + @Override public void run() { for (int i = 0; i < mNumNotifs; ++i) { sendNotification(Sample.SAMPLE_NOTIFICATION_TYPE, Sample.USER_DATA_KEY, mData); @@ -171,7 +168,7 @@ public void run() { public void uploadBytes(final byte[] bytes) { // do nothing; just a bandwidth test } - private final static int MEGABYTE = 1024 * 1024; + private static final int MEGABYTE = 1024 * 1024; public byte[] downloadBytes(final int numBytes) { if (numBytes < 0 || numBytes > 10 * MEGABYTE) { @@ -237,19 +234,6 @@ public Object[] getAllSortsOfStuff() { } stuff.add(table); - final Object[] result = CollectionUtil.toArray(stuff, Object.class); - - return result; + return CollectionUtil.toArray(stuff, Object.class); } } - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerMonitoringImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerMonitoringImpl.java index 41c9dc1868d..64e30819e59 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerMonitoringImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerMonitoringImpl.java @@ -49,42 +49,3 @@ public ServerMonitoringImpl(final ObjectName parent) { super(parent, ServerMon.class); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerRuntimeImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerRuntimeImpl.java index c634068596a..b24e54b4e1f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerRuntimeImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ServerRuntimeImpl.java @@ -37,12 +37,12 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.impl.mbean; import javax.management.ObjectName; import org.glassfish.admin.amx.base.ServerRuntime; -import org.glassfish.admin.amx.impl.mbean.AMXImplBase; /** * Parent for all runtime-related MBeans for a particular server @@ -54,42 +54,3 @@ public ServerRuntimeImpl(final ObjectName parent) { super(parent, ServerRuntime.class); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoFactory.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoFactory.java index 18484ccbec9..b8b081944cb 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoFactory.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoFactory.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Coyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import javax.management.MBeanServer; @@ -47,7 +49,9 @@ */ public final class SystemInfoFactory { - static SystemInfoImpl INSTANCE = null; + private static SystemInfoImpl INSTANCE = null; + + private SystemInfoFactory() {}; /** Return the actual implementation class, because some method(s) are needed internal to the @@ -68,8 +72,6 @@ public static synchronized SystemInfoImpl createInstance(final MBeanServer serve INSTANCE = new SystemInfoImpl(server); new SystemInfoIniter(server, INSTANCE).init(); - } else { - //throw new RuntimeException("can only initialize once--bug"); } return INSTANCE; } @@ -80,11 +82,3 @@ public static synchronized void removeInstance() { } } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoImpl.java index 52f3d509e65..7bc811b66d2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoImpl.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.mbean; import java.util.ArrayList; @@ -81,7 +83,7 @@ public void addFeature(final String featureName, final boolean available) { throw new IllegalArgumentException(); } - mFeatures.put(featureName, Boolean.valueOf(available)); + mFeatures.put(featureName, available); } public String[] getFeatureNames() { @@ -95,7 +97,6 @@ public String[] getFeatureNames() { } public boolean supportsFeature(final String key) { - boolean supports = false; Boolean result = mFeatures.get(key); if (result == null) { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoIniter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoIniter.java index 1b15999e401..01986dce8fe 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoIniter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/SystemInfoIniter.java @@ -76,11 +76,3 @@ private boolean isRunningInDomainAdminServer() { return true; } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ToolsImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ToolsImpl.java index 86d48572855..518242e88c8 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ToolsImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/mbean/ToolsImpl.java @@ -57,8 +57,6 @@ public class ToolsImpl extends AMXImplBase // implements Tools { - private static final String NL = StringUtil.NEWLINE(); - public ToolsImpl(final ObjectName parent) { super(parent, Tools.class); } @@ -70,8 +68,8 @@ private static ObjectName newObjectName(final String s) { } return null; } - static private final String WILD_SUFFIX = ",*"; - static private final String WILD_ALL = "*"; + private static final String WILD_SUFFIX = ",*"; + private static final String WILD_ALL = "*"; public String getInfo() { return info("*"); @@ -112,8 +110,8 @@ public String info(final Collection objectNames) { final StringBuilder buf = new StringBuilder(); - if (objectNames.size() != 0) { - final String NL = StringUtil.NEWLINE(); + if (!objectNames.isEmpty()) { + final String NL = StringUtil.LS; for (final ObjectName objectName : objectNames) { final MBeanInfo mbeanInfo = getProxyFactory().getMBeanInfo(objectName); if (mbeanInfo == null) { @@ -222,39 +220,3 @@ public String getHierarchy() { } } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ImplUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ImplUtil.java index 7767263adfc..f4edb5743cc 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ImplUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ImplUtil.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.util; import java.util.Set; @@ -47,10 +49,6 @@ public final class ImplUtil { - private static void debug(final String s) { - System.out.println(s); - } - /** Unload this AMX MBean and all its children. MBean should be unloaded at the leafs first, working back to DomainRoot so as to @@ -61,8 +59,6 @@ public static void unregisterAMXMBeans(final AMXProxy top) { throw new IllegalArgumentException(); } - //debug( "ImplUtil.unregisterOneMBean: unregistering hierarchy under: " + top.objectName() ); - final MBeanServer mbeanServer = (MBeanServer) top.extra().mbeanServerConnection(); final Set children = top.extra().childrenSet(); @@ -86,8 +82,6 @@ public static void unregisterAMXMBeans(final MBeanServer mbs, final ObjectName o */ public static boolean unregisterOneMBean(final MBeanServer mbeanServer, final ObjectName objectName) { boolean success = false; - //getLogger().fine( "UNREGISTER MBEAN: " + objectName ); - //debug( "ImplUtil.unregisterOneMBean: unregistering: " + objectName ); try { mbeanServer.unregisterMBean(objectName); } catch (final Exception e) { @@ -97,34 +91,3 @@ public static boolean unregisterOneMBean(final MBeanServer mbeanServer, final Ob return success; } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/InjectedValues.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/InjectedValues.java index 116b0dacc6a..699206b1355 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/InjectedValues.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/InjectedValues.java @@ -104,19 +104,4 @@ public static InjectedValues getInstance() { return getDefaultServices().getService(InjectedValues.class); } - public InjectedValues() { - } } - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/Issues.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/Issues.java index 2441cebbe8e..8aa16790e03 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/Issues.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/Issues.java @@ -67,36 +67,3 @@ public void notDone(final String description) { } } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/MBeanInfoSupport.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/MBeanInfoSupport.java index 884ba39ac3e..423769118fd 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/MBeanInfoSupport.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/MBeanInfoSupport.java @@ -37,11 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ package org.glassfish.admin.amx.impl.util; import java.lang.annotation.Annotation; @@ -57,9 +54,7 @@ import java.util.logging.Level; import javax.management.Descriptor; import javax.management.MBeanAttributeInfo; -import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; -import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ObjectName; @@ -85,9 +80,6 @@ public final class MBeanInfoSupport { private MBeanInfoSupport() { } - private static void debug(final Object o) { - System.out.println(o.toString()); - } private static MBeanInfo amxspiMBeanInfo = null; public static synchronized MBeanInfo getAMX_SPIMBeanInfo() { @@ -151,7 +143,6 @@ public static MBeanInfo getMBeanInfo(final Class intf) { operationInfos, null, d); - //debug( "MBeanInfoSupport.getMBeanInfo(): " + mbeanInfo ); return (mbeanInfo); } @@ -176,11 +167,9 @@ public static void findInterfaceMethods(final Class intf, } else if (numArgs == 0 && JMXUtil.isIsOrGetter(method)) { attrName = JMXUtil.getAttributeName(method); getters.put(attrName, method); - //debug( "findInterfaceMethods: getter: " + attrName ); } else if (numArgs == 1 && JMXUtil.isSetter(method)) { attrName = JMXUtil.getAttributeName(method); setters.put(attrName, method); - //debug( "findInterfaceMethods: setter: " + attrName ); } else { AMXLoggerInfo.getLogger().log(Level.WARNING, AMXLoggerInfo.attributeNotGetterSetter, new Object[]{intf.getName(), method.getName()}); @@ -210,27 +199,6 @@ public static void findInterfaceMethods(final Class intf, } } - /* - java.util.Iterator iter = null; - trace( "-------------------- getterSetters -------------------" ); - iter = getterSetters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getNameProp() + ", " ); - } - trace( "-------------------- getters -------------------" ); - iter = getters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getNameProp() + ", " ); - } - trace( "-------------------- setters -------------------" ); - iter = setters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getNameProp() + ", " ); - } - */ } /** @@ -289,7 +257,6 @@ private static List generateAttributeInfos( write, JMXUtil.isIs(m)); infos.add(info); - //debug( "Added MBeanAttributeInfo for: " + attrName ); } return (infos); diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ObjectNameBuilder.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ObjectNameBuilder.java index e2f6319e85d..de67194363f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ObjectNameBuilder.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/ObjectNameBuilder.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.util; import java.util.ArrayList; @@ -44,12 +46,10 @@ import java.util.List; import javax.management.MBeanServer; import javax.management.ObjectName; -import org.glassfish.admin.amx.base.DomainRoot; import org.glassfish.admin.amx.core.AMXProxy; import org.glassfish.admin.amx.core.Util; import org.glassfish.admin.amx.core.proxy.ProxyFactory; import org.glassfish.admin.amx.util.jmx.JMXUtil; -import org.glassfish.admin.amx.util.stringifier.SmartStringifier; import static org.glassfish.external.amx.AMX.*; @@ -78,15 +78,9 @@ public ObjectNameBuilder(final MBeanServer mbeanServer, final ObjectName parent) mJMXDomain = parent.getDomain(); } - private static void debug(final Object o) { - System.out.println("" + o); - //AMXDebug.getInstance().getOutput( "org.glassfish.admin.amx.support.ObjectNameBuilder" ).println( o ); - } - public String getJMXDomain() { return (mJMXDomain); } - private static final String[] EMPTY_STRING_ARRAY = new String[0]; public static String makeWild(String props) { return (Util.concatenateProps(props, JMXUtil.WILD_PROP)); @@ -98,7 +92,6 @@ public static String makeWild(String props) { public static List getAncestors( final MBeanServer server, final ObjectName start) { - //debug( "ObjectNameBuilder.getAncestors(): type = " + start ); AMXProxy amx = ProxyFactory.getInstance(server).getProxy(start, AMXProxy.class); final List ancestors = new ArrayList(); @@ -151,15 +144,8 @@ public static ObjectName buildChildObjectName( final ObjectName parent, final String type, final String childName) { - //debug( "ObjectNameBuilder.buildChildObjectName(): type = " + type + ", name = " + childName + ", parent = " + parent ); String props = Util.makeRequiredProps(type, childName); - /* - final String parentPath = PathnameParser.path( parent); - final String path = PathnameParser.path(parentPath, type, childName); - final String pathProp = Util.makeProp(PATH_KEY,path); - props = Util.concatenateProps(pathProp, props); - */ final AMXProxy parentProxy = ProxyFactory.getInstance(server).getProxy(parent, AMXProxy.class); final String parentPath = parentProxy.path(); final String parentPathProp = Util.makeProp(PARENT_PATH_KEY, Util.quoteIfNeeded(parentPath)); @@ -174,7 +160,6 @@ public static ObjectName buildChildObjectName( final Class intf, final String name) { final String type = Util.deduceType(intf); - //final String pathType = Util.getPathType(intf); return buildChildObjectName(server, parent, type, name); } @@ -186,12 +171,3 @@ public static ObjectName buildChildObjectName( return buildChildObjectName(server, parent, intf, null); } } - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/UnregistrationListener.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/UnregistrationListener.java index a6517ab0073..bf2a14b7c0a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/UnregistrationListener.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/util/UnregistrationListener.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.impl.util; import javax.management.*; @@ -62,6 +64,7 @@ public UnregistrationListener(final MBeanServerConnection conn, final ObjectName // DO NOT listen here; thread-safety problem } + @Override public void handleNotification(final Notification notifIn, final Object handback) { if (notifIn instanceof MBeanServerNotification) { final MBeanServerNotification notif = (MBeanServerNotification) notifIn; @@ -73,10 +76,6 @@ public void handleNotification(final Notification notifIn, final Object handback } } - private static void cdebug(final String s) { - System.out.println(s); - } - /** Wait (block) until the MBean is unregistered. @return true if unregistered, false if an error diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java index cddc0ce8264..e3fbc7940ed 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java @@ -174,9 +174,3 @@ public Map getErrorDistribution( @ManagedAttribute public long getErrorStatisticsIntervalMinutes(); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogFileAccess.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogFileAccess.java index 0a96c06ca4c..76294b99c98 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogFileAccess.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogFileAccess.java @@ -145,17 +145,3 @@ public String getLogFile( @ManagedOperation(impact=MBeanOperationInfo.ACTION) public void rotateLogFile( @Param(name="key") String key ); } - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQuery.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQuery.java index 77b02a1e7ac..ee9b8e25e8f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQuery.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQuery.java @@ -180,9 +180,3 @@ public static LogQueryResult toLogQueryResult(final List items } } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntry.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntry.java index 6857d2aefd4..808652a6b97 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntry.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntry.java @@ -133,9 +133,3 @@ The ID of the thread that emitted the entry (may be null). */ public String getThreadID(); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntryImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntryImpl.java index 96ac7f2b043..f4fdef49337 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntryImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryEntryImpl.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.logging; @@ -51,45 +52,40 @@ import org.glassfish.external.arc.Stability; import org.glassfish.external.arc.Taxonomy; -//import static org.glassfish.admin.amx.logging.LogRecordFields; - /** - INTERNAL USE ONLY--not part of the API - - @since AS 9.0 + * INTERNAL USE ONLY--not part of the API + * + * @since AS 9.0 */ @Taxonomy(stability = Stability.EXPERIMENTAL) public final class LogQueryEntryImpl - implements LogQueryEntry -{ - private transient Map mNameValuePairsMap; - - final long mRecordNumber; - final Date mDate; - final String mLevel; - final String mProductName; - final String mMessage; - final String mMessageID; - final String mModule; - final String mNameValuePairs; - - public - LogQueryEntryImpl( - final long recordNumber, - final Date date, - final String level, - final String productName, - final String module, - final String nameValuePairs, - final String messageID, - final String message) - { - if ( date == null || level == null || message == null || - nameValuePairs == null ) - { + implements LogQueryEntry { + + private Map mNameValuePairsMap; + + final long mRecordNumber; + final Date mDate; + final String mLevel; + final String mProductName; + final String mMessage; + final String mMessageID; + final String mModule; + final String mNameValuePairs; + + public LogQueryEntryImpl( + final long recordNumber, + final Date date, + final String level, + final String productName, + final String module, + final String nameValuePairs, + final String messageID, + final String message) { + if (date == null || level == null || message == null + || nameValuePairs == null) { throw new IllegalArgumentException(); } - + mRecordNumber = recordNumber; mDate = date; mLevel = Level.parse( level ).toString(); @@ -99,15 +95,12 @@ public final class LogQueryEntryImpl mMessageID = messageID; mNameValuePairs = nameValuePairs; } - - public - LogQueryEntryImpl( final Object[] values ) - { - if ( values.length != NUM_FIELDS ) - { - throw new IllegalArgumentException( "wrong number of fields: " + values.length); + + public LogQueryEntryImpl(final Object[] values) { + if (values.length != NUM_FIELDS) { + throw new IllegalArgumentException("wrong number of fields: " + values.length); } - + mRecordNumber = (Long)values[ RECORD_NUMBER_INDEX ]; mDate = (Date)values[ DATE_INDEX ]; mLevel = Level.parse( (String)values[ LEVEL_INDEX ] ).toString(); @@ -117,12 +110,11 @@ public final class LogQueryEntryImpl mMessage = (String)values[ MESSAGE_INDEX ]; mNameValuePairs = (String)values[ NAME_VALUE_PAIRS_INDEX ]; } - - public Object[] - getFields() - { - final Object[] fields = new Object[ NUM_FIELDS ]; - + + @Override + public Object[] getFields() { + final Object[] fields = new Object[NUM_FIELDS]; + fields[ RECORD_NUMBER_INDEX ] = mRecordNumber; fields[ DATE_INDEX ] = mDate; fields[ LEVEL_INDEX ] = mLevel; @@ -131,182 +123,130 @@ public final class LogQueryEntryImpl fields[ MODULE_INDEX ] = mModule; fields[ MESSAGE_INDEX ] = mMessage; fields[ NAME_VALUE_PAIRS_INDEX ]= mNameValuePairs; - + return fields; - } - - /* - public - LogQueryEntryImpl( final CompositeData data ) - { - this( OpenMBeanUtil.compositeDataToMap( data ) ); } - public CompositeType - getCompositeType() - throws OpenDataException - { - return OpenMBeanUtil.mapToCompositeType( getMapClassName(), - getMapClassName(), asMap(), null ); - } - - public CompositeData - asCompositeData() - throws OpenDataException - { - return new CompositeDataSupport( getCompositeType(), asMap() ); - } - - */ - - public long - getRecordNumber() - { + @Override + public long getRecordNumber() { return mRecordNumber; } - - public Date - getDate() - { + + @Override + public Date getDate() { return mDate; } - - public String - getModule() - { + + @Override + public String getModule() { return mModule; } - - public String - getLevel() - { + + @Override + public String getLevel() { return mLevel; } - - public String - getProductName() - { + + @Override + public String getProductName() { return mProductName; } - - public String - getMessage() - { + + @Override + public String getMessage() { return mMessage; } - - public String - getMessageID() - { + + @Override + public String getMessageID() { return mMessageID; } - - public String - getNameValuePairs() - { + + @Override + public String getNameValuePairs() { return mNameValuePairs; } - - /** delimiter between name/value pairs */ + + /** + * delimiter between name/value pairs + */ private static final String NVP_PAIRS_DELIM = ";"; - /** delimiter between name and value */ + /** + * delimiter between name and value + */ private static final String PAIR_DELIM = "="; - - private Map - parseNameValuePairs() - { - final String src = getNameValuePairs(); - final Map m = new HashMap(); - - final String[] pairs = src.split( NVP_PAIRS_DELIM ); - - for( String pair : pairs ) - { - final int idx = pair.indexOf( PAIR_DELIM ); - if ( idx < 0 ) - { - throw new IllegalArgumentException( src ); + + private Map parseNameValuePairs() { + final String src = getNameValuePairs(); + final Map m = new HashMap(); + + final String[] pairs = src.split(NVP_PAIRS_DELIM); + + for (String pair : pairs) { + final int idx = pair.indexOf(PAIR_DELIM); + if (idx < 0) { + throw new IllegalArgumentException(src); } - final String name = pair.substring( 0, idx ).trim(); - final String value = pair.substring( idx + 1, pair.length() ).trim(); - - m.put( name, value ); + final String name = pair.substring(0, idx).trim(); + final String value = pair.substring(idx + 1, pair.length()).trim(); + + m.put(name, value); } - + return m; } - - public Map - getNameValuePairsMap() - { - if ( mNameValuePairsMap == null ) - { - mNameValuePairsMap = parseNameValuePairs(); + + @Override + public Map getNameValuePairsMap() { + if (mNameValuePairsMap == null) { + mNameValuePairsMap = parseNameValuePairs(); } - + return mNameValuePairsMap; } - - public String - getThreadID() - { - return getNameValuePairsMap().get( THREAD_ID_KEY ); + + @Override + public String getThreadID() { + return getNameValuePairsMap().get(THREAD_ID_KEY); } - - public String - getObjectName() - { - return getNameValuePairsMap().get( OBJECTNAME_KEY ); + + public String getObjectName() { + return getNameValuePairsMap().get(OBJECTNAME_KEY); } - - public String - toString() - { + + @Override + public String toString() { final String D = "|"; - + // [#|DATE|LEVEL|PRODUCT_NAME|MODULE|NAME_VALUE_PAIRS|MESSAGE|#] - return "[#" + - getRecordNumber() + D + - getDate() + D + - getLevel() + D + - getProductName() + D + - getModule() + D + - getNameValuePairs() + D + - getMessage() + D + - getMessageID() + D + - "]"; + return "[#" + + getRecordNumber() + D + + getDate() + D + + getLevel() + D + + getProductName() + D + + getModule() + D + + getNameValuePairs() + D + + getMessage() + D + + getMessageID() + D + + "]"; } - - public int - hashCode() - { - return ObjectUtil.hashCode( mDate, mLevel, - mProductName, mMessage, mMessageID, mModule, mNameValuePairs) ^ - ObjectUtil.hashCode( mRecordNumber ); - } - - public boolean - equals( final Object rhs ) - { - boolean equal = false; - - if ( this == rhs ) - { - equal = true; - } - else if ( rhs instanceof LogQueryEntry ) - { - final LogQueryEntry e = (LogQueryEntry)rhs; - - equal = ArrayUtil.arraysEqual( getFields(), e.getFields() ); - } - return equal; + @Override + public int hashCode() { + return ObjectUtil.hashCode(mDate, mLevel, mProductName, mMessage, mMessageID, mModule, mNameValuePairs) ^ ObjectUtil.hashCode(mRecordNumber); } -} - - - + @Override + public boolean equals(final Object rhs) { + boolean equal = false; + if (this == rhs) { + equal = true; + } else if (rhs instanceof LogQueryEntry) { + final LogQueryEntry e = (LogQueryEntry) rhs; + equal = ArrayUtil.arraysEqual(getFields(), e.getFields()); + } + return equal; + } +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResult.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResult.java index 0942ccce87e..592b7e119c2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResult.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResult.java @@ -68,9 +68,3 @@ public interface LogQueryResult */ public LogQueryEntry[] getEntries(); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResultImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResultImpl.java index 73add8dc08f..7a5634047ab 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResultImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogQueryResultImpl.java @@ -37,7 +37,6 @@ * only if the new code is made subject to such option by the copyright * holder. */ - package org.glassfish.admin.amx.logging; import org.glassfish.admin.amx.util.ArrayUtil; @@ -49,113 +48,92 @@ import org.glassfish.external.arc.Taxonomy; /** - INTERNAL USE ONLY--not part of the API - @since AS 9.0 + * INTERNAL USE ONLY--not part of the API + * + * @since AS 9.0 */ @Taxonomy(stability = Stability.EXPERIMENTAL) -public final class LogQueryResultImpl - implements LogQueryResult -{ - private String[] mFieldNames; - private LogQueryEntry[] mEntries; - - public - LogQueryResultImpl( - final String[] fieldNames, - final LogQueryEntry[] entries ) - { - mFieldNames = fieldNames; - mEntries = entries; +public final class LogQueryResultImpl implements LogQueryResult { + + private final String[] mFieldNames; + private final LogQueryEntry[] mEntries; + + public LogQueryResultImpl(final String[] fieldNames, final LogQueryEntry[] entries) { + mFieldNames = fieldNames; + mEntries = entries; } - + /** - Instantiate using result from {@link Logging#queryServerLog}. - The first Object[] is a String[] of the field names. - Subsequent Object[] are the data values. + * Instantiate using result from {@link Logging#queryServerLog}. The first Object[] is a String[] of the field names. Subsequent Object[] are the data + * values. */ - public - LogQueryResultImpl( final List records ) - { - mFieldNames = (String[])records.get( 0 ); - - mEntries = new LogQueryEntry[ records.size() - 1 ]; - for( int i = 0; i < mEntries.length; ++i ) - { - mEntries[ i ] = new LogQueryEntryImpl( records.get( i+1 ) ); + public LogQueryResultImpl(final List records) { + mFieldNames = (String[]) records.get(0); + + mEntries = new LogQueryEntry[records.size() - 1]; + for (int i = 0; i < mEntries.length; ++i) { + mEntries[i] = new LogQueryEntryImpl(records.get(i + 1)); } } - - public String[] - getFieldNames() - { + + @Override + public String[] getFieldNames() { return mFieldNames; } - - public LogQueryEntry[] - getEntries() - { + + @Override + public LogQueryEntry[] getEntries() { return mEntries; } - - private static final String FIELD_DELIM = "\t"; - private static final String NEWLINE = System.getProperty( "line.separator" );; + + private static final String FIELD_DELIM = "\t"; + private static final String NEWLINE = System.getProperty("line.separator"); + + ; /** Output a tab-delimited String with a header line. Each subsequent line represents another log record. */ - public String - toString() - { + @Override + public String toString() { final StringBuilder builder = new StringBuilder(); - - for( final String s : getFieldNames() ) - { - builder.append( s ); - builder.append( FIELD_DELIM ); + + for (final String s : getFieldNames()) { + builder.append(s); + builder.append(FIELD_DELIM); } - builder.replace( builder.length() - 1, builder.length(), NEWLINE ); - - for ( final LogQueryEntry entry : getEntries() ) - { - final Object[] fields = entry.getFields(); - for( final Object o : fields ) - { - builder.append( o.toString() ); - builder.append( FIELD_DELIM ); + builder.replace(builder.length() - 1, builder.length(), NEWLINE); + + for (final LogQueryEntry entry : getEntries()) { + final Object[] fields = entry.getFields(); + for (final Object o : fields) { + builder.append(o.toString()); + builder.append(FIELD_DELIM); } - builder.replace( builder.length() - 1, builder.length(), NEWLINE ); + builder.replace(builder.length() - 1, builder.length(), NEWLINE); } - + return builder.toString(); } - - public int - hashCode() - { - return ObjectUtil.hashCode( getFieldNames(), getEntries() ); - } - - public boolean - equals( final Object rhs ) - { - boolean equal = rhs instanceof LogQueryResult; - - if ( equal ) - { - final LogQueryResult r = (LogQueryResult)rhs; - - equal = ArrayUtil.arraysEqual( getFieldNames(), r.getFieldNames() ) && - ArrayUtil.arraysEqual( getEntries(), r.getEntries() ); - - } - - return equal; + + @Override + public int hashCode() { + return ObjectUtil.hashCode(getFieldNames(), getEntries()); } - - -} + @Override + public boolean equals(final Object rhs) { + boolean equal = rhs instanceof LogQueryResult; + if (equal) { + final LogQueryResult r = (LogQueryResult) rhs; + equal = ArrayUtil.arraysEqual(getFieldNames(), r.getFieldNames()) + && ArrayUtil.arraysEqual(getEntries(), r.getEntries()); + } + return equal; + } + +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java index f841d86a596..ea323f9c78a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java @@ -211,8 +211,3 @@ public interface LogRecordEmitter extends NotificationEmitter, ListenerInfo @ManagedOperation(impact=MBeanOperationInfo.INFO) public int getLogLevelListenerCount( @Param(name="logLevel") final Level logLevel ); } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordFields.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordFields.java index fdf543fe00e..808a870ced4 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordFields.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordFields.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.logging; @@ -45,43 +46,42 @@ /** - Indices into log record fields as returned by - {@link LogQuery#queryServerLog}. Also - @since AppServer 9.0 + * Indices into log record fields as returned by + * {@link LogQuery#queryServerLog}. Also + * @since AppServer 9.0 */ @Taxonomy(stability = Stability.EXPERIMENTAL) -public final class LogRecordFields -{ - private LogRecordFields() {} +public final class LogRecordFields { + + private LogRecordFields() {} - /** Value is of class java.lang.Integer */ - public final static int RECORD_NUMBER_INDEX = 0; + /** Value is of class java.lang.Integer */ + public static final int RECORD_NUMBER_INDEX = 0; - /** Value is of class java.util.Date */ - public final static int DATE_INDEX = 1; + /** Value is of class java.util.Date */ + public static final int DATE_INDEX = 1; - /** Value is of class java.lang.String */ - public final static int LEVEL_INDEX = 2; + /** Value is of class java.lang.String */ + public static final int LEVEL_INDEX = 2; - /** Value is of class java.lang.String */ - public final static int PRODUCT_NAME_INDEX = 3; + /** Value is of class java.lang.String */ + public static final int PRODUCT_NAME_INDEX = 3; - /** Value is of class java.lang.Integer */ - public final static int MESSAGE_INDEX = 7; + /** Value is of class java.lang.Integer */ + public static final int MESSAGE_INDEX = 7; - /** Value is of class java.lang.String */ - public final static int MESSAGE_ID_INDEX = 6; //need to extract from the message text + /** Value is of class java.lang.String */ + public static final int MESSAGE_ID_INDEX = 6; //need to extract from the message text - /** Value is of class java.lang.String */ - public final static int MODULE_INDEX = 4; + /** Value is of class java.lang.String */ + public static final int MODULE_INDEX = 4; - /** Value is of class java.lang.String */ - public final static int NAME_VALUE_PAIRS_INDEX = 5; + /** Value is of class java.lang.String */ + public static final int NAME_VALUE_PAIRS_INDEX = 5; /** Number of fields provided by {@link LogQuery#queryServerLog} */ - public final static int NUM_FIELDS = MESSAGE_INDEX + 1; + public static final int NUM_FIELDS = MESSAGE_INDEX + 1; - public final static String THREAD_ID_KEY = "_ThreadID"; - public final static String OBJECTNAME_KEY = "_ObjectName"; + public static final String THREAD_ID_KEY = "_ThreadID"; + public static final String OBJECTNAME_KEY = "_ObjectName"; } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogUtil.java deleted file mode 100644 index 2847d4ebae7..00000000000 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogUtil.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can - * obtain a copy of the License at - * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html - * or packager/legal/LICENSE.txt. See the License for the specific - * language governing permissions and limitations under the License. - * - * When distributing the software, include this License Header Notice in each - * file and include the License file at packager/legal/LICENSE.txt. - * - * GPL Classpath Exception: - * Oracle designates this particular file as subject to the "Classpath" - * exception as provided by Oracle in the GPL Version 2 section of the License - * file that accompanied this code. - * - * Modifications: - * If applicable, add the following below the License Header, with the fields - * enclosed by brackets [] replaced by your own identifying information: - * "Portions Copyright [year] [name of copyright owner]" - * - * Contributor(s): - * If you wish your version of this file to be governed by only the CDDL or - * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL - * Version 2] license." If you don't indicate a single choice of license, a - * recipient has the option to distribute your version of this file under - * either the CDDL, the GPL Version 2 or to extend the choice of license to - * its licensees as provided above. However, if you add GPL Version 2 code - * and therefore, elected the GPL Version 2 license, then the option applies - * only if the new code is made subject to such option by the copyright - * holder. - */ - -package org.glassfish.admin.amx.logging; - -import javax.management.openmbean.CompositeData; -import org.glassfish.external.arc.Stability; -import org.glassfish.external.arc.Taxonomy; - - -/** - @since AS 9.0 - */ -@Taxonomy(stability = Stability.EXPERIMENTAL) -public final class LogUtil -{ - private LogUtil() {} - - /** - Instantiate a {@link LogQueryResult} - using a CompositeData as returned from - {@link LogQuery#queryServerLog}. - */ - public static final LogQueryResult - createLogQueryResult( final CompositeData data ) - { - return null; - } -} - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java index a8f6e7303b2..83cfa8b76ed 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -186,7 +187,7 @@ public final class AMXDebug private final char[] ILLEGAL_CHARS_ARRAY = { '\u0000', - '?', '*', '|', '\'', '|', '\\', '/', ':', + '?', '*', '|', '\'', '|', '\\', '/', ':' }; private AMXDebug() @@ -197,7 +198,7 @@ private AMXDebug() ILLEGAL_CHARS.add(c); } - NEWLINE = System.getProperty("line.separator"); + NEWLINE = System.lineSeparator(); assert (NEWLINE != null); String value = System.getProperty(AMX_DEBUG_ENABLED_SPROP); @@ -228,13 +229,12 @@ private AMXDebug() mDebug = _getOutput(this.getClass().getName()); mark(mDebug, getStdMarker("AMXDebug started ")); mDebug.println("*** System Properties ***"); - dumpSystemProps(mDebug); + dumpSystemProps(); mark(mDebug, getStdMarker("AMXDebug initialization done")); } - private void dumpSystemProps(final Output output) - { + private void dumpSystemProps() { final java.util.Properties props = System.getProperties(); Set keyset = props.keySet(); @@ -553,7 +553,7 @@ private String makeSafeForFile(final String id) debug may be dynamically enabled or disabled without any users of the Output having to be aware of it. */ - public final static class WrapOutput implements Output + public static final class WrapOutput implements Output { private volatile Output mWrapped; @@ -662,15 +662,3 @@ public static String methodString(final String name, final Object... args) } } - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebugHelper.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebugHelper.java index 0f3a757e468..24c3632e3ae 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebugHelper.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebugHelper.java @@ -37,12 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; -import org.glassfish.admin.amx.util.Output; -import org.glassfish.admin.amx.util.StringUtil; - /** Convenient wrapper around {@link AMXDebug}. Can be made non-final if necessary; declared as 'final' until needed. @@ -69,7 +67,7 @@ public AMXDebugHelper() this("debug"); } - public boolean getEchoToStdOut(final boolean echo) + public boolean getEchoToStdOut() { return mEchoToStdOut; } @@ -151,7 +149,3 @@ public void dumpStack(final String msg) } } - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXLoggerInfo.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXLoggerInfo.java index 3875f13c32b..e270ef55724 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXLoggerInfo.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXLoggerInfo.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.util; import java.util.logging.Logger; @@ -50,6 +52,9 @@ */ /* Module private */ public class AMXLoggerInfo { + + private AMXLoggerInfo () {} + public static final String LOGMSG_PREFIX = "NCLS-COM"; @LogMessagesResourceBundle diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayConversion.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayConversion.java index a1c9e5f950a..97bb4bc68f2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayConversion.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayConversion.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -157,26 +158,20 @@ public static Object[] subArray(final Object[] in, int start, int end) return (result); } - public static Set toSet(T[] array) - { - Set theSet; - if (array.length == 0) - { - theSet = Collections.emptySet(); - } - else if (array.length == 1) - { - theSet = Collections.singleton(array[ 0]); - } - else - { - theSet = new HashSet(); - for (int i = 0; i < array.length; ++i) - { - theSet.add(array[i]); - } + public static Set toSet(T[] array) { + switch (array.length) { + case 0: + return Collections.emptySet(); + case 1: + return Collections.singleton(array[ 0]); + default: + Set theSet = new HashSet(); + for (int i = 0; i < array.length; ++i) + { + theSet.add(array[i]); + } + return theSet; } - return (theSet); } /* diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayUtil.java index 45fd244111b..bacde87d395 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ArrayUtil.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -86,12 +87,8 @@ else if (array1 == null || array2 == null) { equal = false; } - else if (ClassUtil.objectIsArray(a1)) - { - if (!arraysEqual(a1, a2)) - { - equal = false; - } + else if (ClassUtil.objectIsArray(a1) && !arraysEqual(a1, a2)) { + equal = false; } } @@ -196,28 +193,3 @@ public static T[] newArray( } } - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ClassUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ClassUtil.java index d8d76c3a8dc..ade1f649c49 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ClassUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ClassUtil.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -262,41 +263,8 @@ public static String getArrayMemberClassName(String classname) if (classnameIsPrimitiveArray(classname)) { final char lastChar = classname.charAt(classnameLength - 1); - - switch (lastChar) - { - default: - throw new RuntimeException("illegal primitive"); - - // a simple type - case 'Z': - result = "boolean"; - break; - case 'B': - result = "byte"; - break; - case 'C': - result = "char"; - break; - case 'S': - result = "short"; - break; - case 'I': - result = "int"; - break; - case 'J': - result = "long"; - break; - case 'F': - result = "float"; - break; - case 'D': - result = "double"; - break; - } - } - else - { + result = primitiveLetterToClassName(lastChar); + } else { // strip leading "[L" and trailing ";" result = classname.substring(2, classnameLength - 1); } @@ -307,7 +275,7 @@ public static String getArrayMemberClassName(String classname) /** Class.forName does not work for primitive types, so we need to do it ourselves here. */ - final static class ClassNameToClassMapping + static final class ClassNameToClassMapping { String mName; @@ -342,13 +310,7 @@ public static Class classForName(String name) try { c = Class.forName(name); - } - catch (ClassNotFoundException e) - { - c = Class.forName(name, true, Thread.currentThread().getContextClassLoader()); - } - catch (NoClassDefFoundError e) - { + } catch (ClassNotFoundException | NoClassDefFoundError e) { c = Class.forName(name, true, Thread.currentThread().getContextClassLoader()); } @@ -632,7 +594,7 @@ public static String getFriendlyClassname(Class theClass) @param type @return a friendlier string representing the type */ - final static String javaLang = "java.lang."; + static final String javaLang = "java.lang."; public static String getFriendlyClassname(String type) { @@ -650,43 +612,12 @@ public static String getFriendlyClassname(String type) // strip all the '[' characters result = type.substring(depth, type.length()); - if (result.startsWith("L") && result.endsWith(";")) - { + if (result.startsWith("L") && result.endsWith(";")) { result = result.substring(1, result.length() - 1); - } - else if (result.length() == 1) - { + } else if (result.length() == 1) { + // a simple type - switch (result.charAt(0)) - { - case 'Z': - result = "boolean"; - break; - case 'B': - result = "byte"; - break; - case 'C': - result = "char"; - break; - case 'S': - result = "short"; - break; - case 'I': - result = "int"; - break; - case 'J': - result = "long"; - break; - case 'F': - result = "float"; - break; - case 'D': - result = "double"; - break; - default: - result = "unknown"; - break; - } + result = primitiveLetterToClassName(result.charAt(0)); } StringBuilder sb = new StringBuilder(result); @@ -962,10 +893,7 @@ public static T instantiateObject(final Class theClass, final String theS T result = null; try { - result = constructor.newInstance(new Object[] - { - theString - }); + result = constructor.newInstance(theString); } catch (java.lang.reflect.InvocationTargetException e) { @@ -1051,7 +979,7 @@ else if (theClass == Character.class || theClass == char.class) throw new IllegalArgumentException("not a character: " + theString); } - result = Character.valueOf(theString.charAt(0)); + result = theString.charAt(0); } else { @@ -1088,7 +1016,7 @@ else if (objectClass == Boolean.class) } else if (objectClass == Character.class) { - result = Character.valueOf('X'); + result = 'X'; } else if (classIsArray(objectClass)) { @@ -1123,12 +1051,12 @@ else if (classIsArray(inClass)) return result; } - final static String[] sJavaLangTypes = + static final String[] sJavaLangTypes = { "Character", "Boolean", "Byte", "Short", "Integer", "Long", "Float", "Double", "String", "Object" }; - final static int sNumBaseTypes = Array.getLength(sJavaLangTypes); + static final int sNumBaseTypes = Array.getLength(sJavaLangTypes); /** Expand an abbreviated classname into its true java name. @@ -1151,25 +1079,26 @@ public static String expandClassName(final String name) if (fullName == name) // no match so far { - if (name.equals("Number")) - { - fullName = "java.lang." + name; - } - else if (name.equals("BigDecimal") || name.equals("BigInteger")) - { - fullName = "java.math." + name; - } - else if (name.equals("URL") || name.equals("URI")) - { - fullName = "java.net." + name; - } - else if (name.equals("Date")) - { - fullName = "java.util." + name; - } - else if (name.equals("ObjectName")) - { - fullName = "javax.management." + name; + switch (name) { + case "Number": + fullName = "java.lang." + name; + break; + case "BigDecimal": + case "BigInteger": + fullName = "java.math." + name; + break; + case "URL": + case "URI": + fullName = "java.net." + name; + break; + case "Date": + fullName = "java.util." + name; + break; + case "ObjectName": + fullName = "javax.management." + name; + break; + default: + break; } } @@ -1277,8 +1206,6 @@ public static String stripPackagePrefix(final String classname) return result; } - ; - public static String getPackagePrefix(final String classname) { final int index = classname.lastIndexOf('.'); @@ -1292,12 +1219,4 @@ public static String getPackagePrefix(final String classname) return result; } - ; } - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CollectionUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CollectionUtil.java index c32e2d3ad86..8ef8084c2ab 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CollectionUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CollectionUtil.java @@ -37,10 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; -import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Collection; @@ -68,12 +68,8 @@ public static void addAll(Collection c, T[] items) /** @return a String */ - public static String toString( - final Collection c, - final String delim) - { + public static String toString(final Collection c, final String delim) { final String[] strings = toStringArray(c); - //Arrays.sort( strings ); return StringUtil.toString(delim, (Object[]) strings); } @@ -81,8 +77,7 @@ public static String toString( /** @return String[] */ - public static String[] toStringArray(final Collection c) - { + public static String[] toStringArray(final Collection c) { final String[] strings = new String[c.size()]; int i = 0; @@ -154,16 +149,3 @@ public static boolean isAllStrings(final Collection c) } } - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CompareUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CompareUtil.java index 7101409167b..3b603079296 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CompareUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/CompareUtil.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -54,22 +55,14 @@ public static boolean objectsEqual(Object o1, Object o2) { boolean equal = o1 == o2; - if (!equal) - { - if (o1 == null) - { + if (!equal) { + if (o1 == null) { // o1 is null, but o2 is not equal = false; - } - else - { + } else { equal = o1.equals(o2); - if (!equal) - { - if (ClassUtil.objectIsArray(o1)) - { - equal = ArrayUtil.arraysEqual(o1, o2); - } + if (!equal && ClassUtil.objectIsArray(o1)) { + equal = ArrayUtil.arraysEqual(o1, o2); } } } @@ -78,4 +71,3 @@ public static boolean objectsEqual(Object o1, Object o2) } } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOut.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOut.java index 11dd3997646..85cf24b937d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOut.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOut.java @@ -64,5 +64,3 @@ If getDebug() returns true, output the arguments public void debugMethod(final String methodName, final String msg, final Object... args); } - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOutImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOutImpl.java index 8d765dd65cc..ab458fcaa94 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOutImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugOutImpl.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -50,39 +51,36 @@ public class DebugOutImpl implements DebugOut private DebugSink mSink; - public DebugOutImpl( - final String id, - final boolean debug, - final DebugSink sink) - { + public DebugOutImpl(final String id, final boolean debug, final DebugSink sink) { mID = id; mDebug = debug; mSink = sink == null ? new DebugSinkImpl(System.out) : sink; } - public DebugOutImpl( - final String id, - final boolean debug) - { + public DebugOutImpl(final String id, final boolean debug) { this(id, debug, null); } + @Override public String getID() { return mID; } + @Override public boolean getDebug() { return mDebug; } + @Override public void print(final Object o) { mSink.print("" + o); } + @Override public void println(Object o) { mSink.println("" + o); @@ -98,31 +96,25 @@ public void setDebug(final boolean debug) mDebug = debug; } - public void debug(final Object... args) - { + @Override + public void debug(final Object... args) { if (getDebug()) { mSink.println(toString(args)); } } - public void debugMethod( - final String methodName, - final Object... args) - { + @Override + public void debugMethod(final String methodName, final Object... args) { if (getDebug()) { debug(methodString(methodName, args)); } } - public void debugMethod( - final String msg, - final String methodName, - final Object... args) - { - if (getDebug()) - { + @Override + public void debugMethod(final String msg, final String methodName, final Object... args) { + if (getDebug()) { debug(methodString(methodName, args) + ": " + msg); } } @@ -147,31 +139,3 @@ public static String methodString( } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugState.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugState.java index a6de1a5cd0c..4322d2cb66a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugState.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/DebugState.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -51,13 +52,12 @@ public static final class Impl implements DebugState { private final boolean mStatus; - public Impl(boolean status) - { + public Impl(boolean status){ mStatus = status; } - public boolean getDebug() - { + @Override + public boolean getDebug() { return (mStatus); } @@ -69,5 +69,3 @@ public boolean getDebug() public boolean getDebug(); } - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/EnumerationIterator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/EnumerationIterator.java index 172579f1c8a..cbe6421c794 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/EnumerationIterator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/EnumerationIterator.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -55,16 +56,19 @@ public EnumerationIterator(Enumeration enumIn) mEnum = enumIn; } + @Override public boolean hasNext() { return (mEnum.hasMoreElements()); } + @Override public Object next() { return (mEnum.nextElement()); } + @Override public void remove() { throw new UnsupportedOperationException(""); diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java index 8fb78c5bf42..4d17403c77d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java @@ -37,12 +37,10 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; -import org.glassfish.admin.amx.util.ExceptionUtil; - -import javax.management.MBeanServer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -85,21 +83,9 @@ public final class FeatureAvailability private final Map mLatches; - // private final AMXDebugHelper mDebug; - /** feature stating that the AdminContext is available. Result data is the AdminContext */ - //public static final String ADMIN_CONTEXT_FEATURE = "AdminContext"; - /** feature stating that the MBeanServer is available. Result data is the MBeanServer */ - //public static final String MBEAN_SERVER_FEATURE = "MBeanServer"; - /** feature stating that the SunoneInterceptor is active. Associated data should be ignored. */ - //public static final String SUN_ONE_INTERCEPTOR_FEATURE = "SunoneInterceptor"; - /** feature stating that the com.sun.appserv:category=config MBeans are available. - Result data should not be used */ - //public static final String COM_SUN_APPSERV_CONFIG_MBEANS_FEATURE = "com.sun.appserv:category=config"; /** feature stating that the AMX MBean Loader is available (but not AMX). Data should not be used */ public static final String AMX_LOADER_FEATURE = "AMXLoader"; - /** feature stating that the AMX BootUtil class is available. Data should not be used */ - //public static final String AMX_BOOT_UTIL_FEATURE = "AMXBootUtil"; /** feature stating that the AMX core is ready for use after having been started. Data should not be used. Other AMX subystems might still be in the process of initializing */ public static final String AMX_CORE_READY_FEATURE = "AMXCoreReady"; @@ -107,20 +93,10 @@ public final class FeatureAvailability /** feature stating that the AMX and all its subsystems are ready for use. Data is the ObjectName of the DomainRoot */ public static final String AMX_READY_FEATURE = "AMXReady"; - /** feature stating that the CallFlow feature is available. Data should not be used - Data is of type com.sun.enterprise.admin.monitor.callflow.Agent */ - //public static final String CALL_FLOW_FEATURE = "CallFlow"; - /** Feature stating that the server has started, meaning that the main initialization - code has been run; specific features could be initializing on separate threads, or - could be initialized lazily. No data is associated with this feature. */ - //public static final String SERVER_STARTED_FEATURE = "ServerStarted"; - private FeatureAvailability() - { + private FeatureAvailability() { mFeatures = new HashMap(); mLatches = new HashMap(); - //mDebug = new AMXDebugHelper( "--FeatureAvailability--" ); - //mDebug.setEchoToStdOut( true ); } public static FeatureAvailability getInstance() @@ -129,6 +105,8 @@ public static FeatureAvailability getInstance() } private static final boolean DEBUG_ENABLED = false; + + private static final AMXDebugHelper DEBUG_HELPER = new AMXDebugHelper(); /** Internal use, should be replaced with use of @@ -140,48 +118,17 @@ private void debug(final Object... args) if (DEBUG_ENABLED) { String msg = ""; + StringBuilder builder = new StringBuilder(); for (int i = 0; i < args.length - 1; ++i) { - msg = msg + args[i] + " "; + builder.append(args[i]).append(" "); } msg = msg + args[args.length - 1]; - System.out.println(msg); + DEBUG_HELPER.println(msg); } } - /** - MBeanServer is created very early and is available via this method exept for code - that executes prior to the JVM calling main(). As it is of interest in many areas, - an explicit method call is provided. -

- NON-BLOCKING--returns current value, can be null - @return the MBeanServer used by all AppServer MBeans - public MBeanServer - getMBeanServer() - { - return (MBeanServer)mFeatures.get( MBEAN_SERVER_FEATURE ); - } - */ - /** - MBeanServer is created very early and is available via this method exept for code - that executes prior to the JVM calling main(). As it is of interest in many areas, - an explicit method call is provided. - BLOCKING--returns onlyl when MBeansServer becomes available. - @return the MBeanServer used by all AppServer MBeans - public MBeanServer - waitForMBeanServer() - { - MBeanServer server = getMBeanServer(); - - if ( server == null ) - { - server = (MBeanServer)waitForFeature( MBEAN_SERVER_FEATURE, - "waitForMBeanServer from " + ExceptionUtil.getStackTrace() ); - } - return server; - } - */ /** Register a named feature as being ready for use. The data value can be a dummy value, or can be something useful to the caller of waitForFeature(). @@ -196,9 +143,7 @@ dummy value, or can be something useful to the caller of waitForFeature(). @param featureName arbitrary name for the feature, to be used by clients in {@link #waitForFeature} @param data arbitrary data of possible interest to clients */ - public synchronized void registerFeature(final String featureName, final Object data) - { - //debug( "FeatureAvailability.registerFeature: " + featureName + " in instance " + this); + public synchronized void registerFeature(final String featureName, final Object data) { if (mFeatures.get(featureName) != null) { throw new IllegalStateException("FeatureAvailability.addFeature: already added: " + featureName); @@ -208,13 +153,11 @@ public synchronized void registerFeature(final String featureName, final Object throw new IllegalArgumentException("FeatureAvailability.addFeature(): data is null for: " + featureName); } mFeatures.put(featureName, data); - //debug( "********** FeatureAvailability.addFeature: " + featureName + ", data = " + data + "**********"); if (mLatches.containsKey(featureName)) { final CountDownLatch latch = mLatches.remove(featureName); latch.countDown(); // let all blocked threads proceed - //debug( "addFeature: released latch for: " + featureName ); } } @@ -223,9 +166,7 @@ public synchronized void registerFeature(final String featureName, final Object @param featureName the name of the desired feature @param callerInfo arbitrary caller info for debugging purposes */ - public Object waitForFeature(final String featureName, final String callerInfo) - { - //debug( "FeatureAvailability.waitForFeature: " + featureName + " by " + callerInfo + " in instance " + this); + public Object waitForFeature(final String featureName, final String callerInfo) { CountDownLatch latch = null; Object data = null; @@ -248,13 +189,9 @@ public Object waitForFeature(final String featureName, final String callerInfo) assert ((data == null && latch != null) || (data != null && latch == null)); // if we had to create a CountDownLatch, calling thread must now await() - if (latch != null) - { - final long start = System.currentTimeMillis(); + if (latch != null) { - try - { - //debug( "waitForFeature: \"" + featureName + "\" by " + callerInfo ); + try { final long startNanos = System.nanoTime(); latch.await(); @@ -285,36 +222,3 @@ public synchronized void deRegisterFeatures() { } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileOutput.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileOutput.java index 2fd086923af..2bb33822193 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileOutput.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileOutput.java @@ -37,11 +37,13 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.io.PrintStream; /** @@ -78,11 +80,8 @@ private void lazyInit() { try { - if ((!mAppend) && mFile.exists()) - { - if (!mFile.delete()) { - throw new Exception("cannot delete file: " + mFile); - } + if ((!mAppend) && mFile.exists() && !mFile.delete()) { + throw new IOException("cannot delete file: " + mFile); } mOut = new PrintStream(new FileOutputStream(mFile, mAppend)); @@ -98,18 +97,21 @@ private void lazyInit() } } + @Override public void print(final Object o) { lazyInit(); mOut.print(o.toString()); } + @Override public void println(Object o) { lazyInit(); mOut.println(o.toString()); } + @Override public void printError(final Object o) { lazyInit(); @@ -122,12 +124,14 @@ public boolean getDebug() return (false); } + @Override public void printDebug(final Object o) { lazyInit(); println("DEBUG: " + o); } + @Override public void close() { if (mOut != null) @@ -143,6 +147,4 @@ public void close() } } -}; - - +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileUtils.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileUtils.java index 1ac17ba2dc6..66d72f7933b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileUtils.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FileUtils.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -55,15 +56,11 @@ private FileUtils() { } - public static String fileToString(final File src) - throws FileNotFoundException, IOException - { + public static String fileToString(final File src) throws FileNotFoundException, IOException { return fileToString(src, 32 * 1024); } - public static String fileToString(final File src, final int readBufferSize) - throws FileNotFoundException, IOException - { + public static String fileToString(final File src, final int readBufferSize) throws FileNotFoundException, IOException { final long length = src.length(); if (length > 1024 * 1024 * 1024) { @@ -73,11 +70,7 @@ public static String fileToString(final File src, final int readBufferSize) final char[] readBuffer = new char[readBufferSize]; final StringBuilder result = new StringBuilder((int) length); - FileReader in = null; - - try - { - in = new FileReader(src); + try (FileReader in = new FileReader(src)) { while (true) { final int numRead = in.read(readBuffer, 0, readBufferSize); @@ -89,31 +82,14 @@ public static String fileToString(final File src, final int readBufferSize) result.append(readBuffer, 0, numRead); } } - finally - { - if (in != null) { - in.close(); - } - } return (result.toString()); } - public static void stringToFile(final String s, final File dest) - throws IOException - { - final FileWriter out = new FileWriter(dest); - - try - { + public static void stringToFile(final String s, final File dest) throws IOException { + try (FileWriter out = new FileWriter(dest)) { out.write(s); } - finally - { - out.close(); - } } -}; - - +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/LineReaderImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/LineReaderImpl.java index 517c2b910c3..dda61a9a985 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/LineReaderImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/LineReaderImpl.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util; @@ -57,9 +57,8 @@ public LineReaderImpl(InputStream inputStream) mInputStreamReader = new InputStreamReader(inputStream); } - public String readLine(String prompt) - throws java.io.IOException - { + @Override + public String readLine(String prompt) throws java.io.IOException { final StringBuilder line = new StringBuilder(); if (prompt != null) @@ -93,7 +92,3 @@ public String readLine(String prompt) } } - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/MapUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/MapUtil.java index cd192923886..fa4dcb15942 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/MapUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/MapUtil.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util; @@ -80,41 +80,37 @@ public static Map newMap() /** Create a new Map consisting of a single key/value pair. */ - public static Map newMap( - final String key, - final V value) - { - final Map m = new HashMap<>(); + public static Map newMap(final String key, final V value) { + final Map map = new HashMap<>(); - m.put(key, value); + map.put(key, value); - return (m); + return (map); } /** - Create a new Map consisting of a single key/value pair. + * Create a new Map combined all entries of two other maps. + * If a key is is both maps then the value in map2 will be used. */ - public static Map newMap( - final Map m1, - final Map m2) + public static Map newMap(final Map m1, final Map m2) { - final Map m = new HashMap<>(); + final Map newMap = new HashMap<>(); if (m1 != null) { - m.putAll(m1); + newMap.putAll(m1); } if (m2 != null) { - m.putAll(m2); + newMap.putAll(m2); } - return (m); + return (newMap); } public static Map toMap(final Object[] params, final Class keyClass, final Class valueClass) { - final Map m = new HashMap<>(); + final Map map = new HashMap<>(); for (int i = 0; i < params.length; i += 2) { @@ -135,9 +131,9 @@ public static Map toMap(final Object[] params, final Class keyCl throw new IllegalArgumentException("Value of class " + value.getClass().getName() + " not assignable to " + valueClass.getName()); } - m.put(keyClass.cast(key), valueClass.cast(value)); + map.put(keyClass.cast(key), valueClass.cast(value)); } - return m; + return map; } /** @@ -174,49 +170,43 @@ public static Map newMap(final String... mappings) throw new IllegalArgumentException("mappings must have even length"); } - final Map m = new HashMap<>(); + final Map map = new HashMap<>(); for (int i = 0; i < mappings.length; i += 2) { - m.put(mappings[i], mappings[i + 1]); + map.put(mappings[i], mappings[i + 1]); } - return (m); + return (map); } /** Remove all entries keyed by 'keys' */ - public static void removeAll( - final Map m, - final T[] keys) - { + public static void removeAll(final Map map, final T[] keys) { for (T key : keys) { - m.remove(key); + map.remove(key); } } - public static boolean mapsEqual( - final Map m1, - final Map m2) - { - if (m1 == m2) + public static boolean mapsEqual(final Map map1, final Map map2) { + if (map1 == map2) { return (true); } boolean equal = false; - if (m1.size() == m2.size() && - m1.keySet().equals(m2.keySet())) + if (map1.size() == map2.size() && + map1.keySet().equals(map2.keySet())) { equal = true; - for (final Map.Entry me : m1.entrySet()) + for (final Map.Entry me : map1.entrySet()) { final Object key = me.getKey(); final Object value1 = me.getValue(); - final Object value2 = m2.get(key); + final Object value2 = map2.get(key); if (!CompareUtil.objectsEqual(value1, value2)) { @@ -229,11 +219,16 @@ public static boolean mapsEqual( return (equal); } - public static Map newMapNoNullValues(final Map m) - { + /** + * Creates a new map with all the old key/value pairs unless the value + * was null + * @param map the old map to convert + * @return a new map with no null values + */ + public static Map newMapNoNullValues(final Map map) { final Map result = new HashMap<>(); - for (final Map.Entry me : m.entrySet()) + for (final Map.Entry me : map.entrySet()) { final V value = me.getValue(); @@ -251,19 +246,19 @@ public static String toString(final Map m) return (toString(m, ",")); } - public static String toString(final Map m, final String separator) + public static String toString(final Map map, final String separator) { - if (m == null) + if (map == null) { return ("null"); } final StringBuilder buf = new StringBuilder(); - final String[] keyStrings = getKeyStrings(m); + final String[] keyStrings = getKeyStrings(map); for (final String key : keyStrings) { - final Object value = m.get(key); + final Object value = map.get(key); buf.append(key); buf.append("="); @@ -279,11 +274,13 @@ public static String toString(final Map m, final String separator) return (buf.toString()); } - public static Set getNullValueKeys(final Map m) - { + /** + * Gets all keys which map to a null value + */ + public static Set getNullValueKeys(final Map map) { final Set s = new HashSet<>(); - for (final Map.Entry me : m.entrySet()) + for (final Map.Entry me : map.entrySet()) { if (me.getValue() == null) { @@ -298,45 +295,48 @@ public static Map toMap(final Properties props, final Class kCla return TypeCast.checkMap(props, kClass, vClass); } - public static void removeAll(final Map m, final Set s) - { - for (final K key : s) + /** + * Removes all keys in a set from a map + * @param map the map to remove keys from + * @param keySet a set of keys to remove + */ + public static void removeAll(final Map map, final Set keySet) { + for (final K key : keySet) { - m.remove(key); + map.remove(key); } } /** @return true if non-null Map and all keys and values are of type java.lang.String */ - public static boolean isAllStrings(final Map m) - { - return m != null && CollectionUtil.isAllStrings(m.keySet()) && - CollectionUtil.isAllStrings(m.values()); + public static boolean isAllStrings(final Map map) { + return map != null && CollectionUtil.isAllStrings(map.keySet()) && + CollectionUtil.isAllStrings(map.values()); } /** Convert an arbitrary Map to one whose keys and values are both of type String. */ - public static Map toStringStringMap(final Map m) + public static Map toStringStringMap(final Map map) { - if (m == null) + if (map == null) { return null; } Map result; - if (isAllStrings(m)) + if (isAllStrings(map)) { - result = TypeCast.asMap(m); + result = TypeCast.asMap(map); } else { result = new HashMap<>(); - for (final Map.Entry me : m.entrySet()) + for (final Map.Entry me : map.entrySet()) { final Object key = me.getKey(); final Object value = me.getValue(); @@ -356,14 +356,3 @@ public static Map toStringStringMap(final Map m) } } - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/Output.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/Output.java index 132a13087d4..393670ac956 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/Output.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/Output.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -50,6 +51,7 @@ public interface Output extends DebugSink @param o the Object to output */ + @Override public void print(Object o); /** @@ -57,6 +59,7 @@ public interface Output extends DebugSink @param o the Object to output */ + @Override public void println(Object o); /** @@ -78,6 +81,4 @@ Output a debug error message if getDebug() is currently true. */ public void close(); -}; - - +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/OutputIgnore.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/OutputIgnore.java index 0976970f777..77fb2587a9d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/OutputIgnore.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/OutputIgnore.java @@ -37,29 +37,33 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; /** -Directs output to the "bit bucket". + * Directs output to the "bit bucket". */ public final class OutputIgnore implements Output { - public final static OutputIgnore INSTANCE = new OutputIgnore(); + public static final OutputIgnore INSTANCE = new OutputIgnore(); private OutputIgnore() { // no need for more than one, ever } + @Override public void print(Object o) { } + @Override public void println(Object o) { } + @Override public void printError(Object o) { } @@ -69,14 +73,14 @@ public boolean getDebug() return (false); } + @Override public void printDebug(Object o) { } + @Override public void close() { } -}; - - +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/RegexUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/RegexUtil.java index d4489382ab9..4d3a41e1d4c 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/RegexUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/RegexUtil.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util; @@ -53,7 +53,7 @@ private RegexUtil() // disallow instantiation } - private final static char BACKSLASH = '\\'; + private static final char BACKSLASH = '\\'; /** These characters will be escaped by wildcardToJavaRegex() @@ -119,7 +119,7 @@ else if (theChar == '*') else if (REGEX_SPECIALS.indexOf(theChar) >= 0) { // '[' begins a set of characters - buf.append("" + BACKSLASH + theChar); + buf.append("").append(BACKSLASH).append(theChar); } else { @@ -134,4 +134,3 @@ else if (REGEX_SPECIALS.indexOf(theChar) >= 0) } } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/SetUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/SetUtil.java index ab52701be80..e676536d3e9 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/SetUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/SetUtil.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -127,28 +128,7 @@ public static Set newSet( return (set); } - /* - public static Set - newSet( - final T m1, - final T m2, - final T m3 ) - { - final HashSet set = new HashSet(); - - set.add( m1 ); - set.add( m2 ); - set.add( m3 ); - - return( set ); - } - */ - public static Set newSet( - final T m1, - final T m2, - final T m3, - final T m4) - { + public static Set newSet(final T m1, final T m2, final T m3, final T m4) { final HashSet set = new HashSet(); set.add(m1); @@ -241,19 +221,6 @@ public static Set newUnmodifiableStringSet(final String... args) return Collections.unmodifiableSet(newStringSet(args)); } - /* - public static Set - newStringSet( final Object... args) - { - final Set set = new HashSet(); - - for( final Object o : args ) - { - set.add( o == null ? null : "" + o ); - } - return set; - } - */ public static Set newTypedSet(final T... args) { final Set set = new HashSet(); @@ -336,26 +303,3 @@ public static String findIgnoreCase(final Set candidates, final String t } } - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/StringUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/StringUtil.java index 168b67bd1af..b299ac403be 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/StringUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/StringUtil.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util; @@ -62,17 +62,16 @@ private StringUtil() { } - public final static char QUOTE_CHAR = '\"'; + public static final char QUOTE_CHAR = '\"'; - public final static String QUOTE = "" + QUOTE_CHAR; + public static final String QUOTE = "" + QUOTE_CHAR; /** Line separator as returned by System.getProperty() */ - public final static String LS = System.getProperty("line.separator", "\n"); + public static final String LS = System.getProperty("line.separator", "\n"); - public static String quote(Object o) - { + public static String quote(Object o) { return (quote(o, QUOTE_CHAR)); } @@ -83,24 +82,24 @@ public static String quote(Object o, char leftHandChar) char leftChar = leftHandChar; char rightChar = leftHandChar; - if (leftHandChar == '(') - { - rightChar = ')'; - } - else if (leftHandChar == '{') - { - rightChar = '}'; - } - else if (leftHandChar == '[') - { - rightChar = ']'; - } - else if (leftHandChar == '<') - { - rightChar = '>'; + switch (leftHandChar) { + case '(': + rightChar = ')'; + break; + case '{': + rightChar = '}'; + break; + case '[': + rightChar = ']'; + break; + case '<': + rightChar = '>'; + break; + default: + // same char on both left and right + break; } - // same char on both left and right - + return (leftChar + s + rightChar); } @@ -114,30 +113,21 @@ public static String toHexString(byte theByte) return (result); } - public static String toHexString(byte[] bytes) - { + public static String toHexString(byte[] bytes) { return (toHexString(bytes, null)); } - public static String toHexString(byte[] bytes, String delim) - { + public static String toHexString(byte[] bytes, String delim) { final StringBuilder buf = new StringBuilder(); - if (bytes.length == 0) - { + if (bytes.length == 0) { // nothing - } - else if (delim == null || delim.length() == 0) - { - for (int i = 0; i < bytes.length; ++i) - { + } else if (delim == null || delim.length() == 0) { + for (int i = 0; i < bytes.length; ++i) { buf.append(toHexString(bytes[i])); } - } - else - { - for (int i = 0; i < bytes.length; ++i) - { + } else { + for (int i = 0; i < bytes.length; ++i) { buf.append(toHexString(bytes[i])).append(delim); } @@ -150,12 +140,10 @@ else if (delim == null || delim.length() == 0) public static String stripSuffix( final String s, - final String suffix) - { + final String suffix) { String result = s; - if (s.endsWith(suffix)) - { + if (s.endsWith(suffix)) { result = s.substring(0, s.length() - suffix.length()); } @@ -165,10 +153,8 @@ public static String stripSuffix( public static String replaceSuffix( final String s, final String fromSuffix, - final String toSuffix) - { - if (!s.endsWith(fromSuffix)) - { + final String toSuffix) { + if (!s.endsWith(fromSuffix)) { throw new IllegalArgumentException(fromSuffix); } @@ -177,12 +163,10 @@ public static String replaceSuffix( public static String stripPrefix( final String s, - final String prefix) - { + final String prefix) { String result = s; - if (s.startsWith(prefix)) - { + if (s.startsWith(prefix)) { result = s.substring(prefix.length(), s.length()); } @@ -192,79 +176,52 @@ public static String stripPrefix( public static String stripPrefixAndSuffix( final String s, final String prefix, - final String suffix) - { + final String suffix) { return stripPrefix(stripSuffix(s, suffix), prefix); } - public static String upperCaseFirstLetter(final String s) - { + public static String upperCaseFirstLetter(final String s) { String result = s; - if (s.length() >= 1) - { + if (s.length() >= 1) { result = s.substring(0, 1).toUpperCase(Locale.ENGLISH) + s.substring(1, s.length()); } return (result); } - public static String toString(final Object o) - { + public static String toString(final Object o) { String s; - if (o instanceof String) - { + if (o instanceof String) { s = (String) o; - } - else if (o instanceof Throwable) - { + } else if (o instanceof Throwable) { s = ExceptionUtil.toString((Throwable) o); - } - /* - else if ( o instanceof ObjectName ) - { - s = JMXUtil.toString( (ObjectName)o ); - } - */ - else if (o instanceof Attribute) - { + } else if (o instanceof Attribute) { final Attribute a = (Attribute) o; s = a.getName() + "=" + toString(a.getValue()); - } - else if (o instanceof AttributeList) - { + } else if (o instanceof AttributeList) { final Map items = JMXUtil.attributeListToValueMap((AttributeList) o); s = "{" + MapUtil.toString(items) + "}"; - } - else if (o instanceof byte[]) - { + } else if (o instanceof byte[]) { final byte[] b = byte[].class.cast(o); s = "byte[] of length " + b.length; - } - else if (o == null) - { + } else if (o == null) { s = "null"; - } - else if (o instanceof Object[]) - { + } else if (o instanceof Object[]) { s = toString(", ", (Object[]) o); - } - else - { + } else { s = "" + o; } return s; } - public static String toString(final String[] args) - { + public static String toString(final String[] args) { return toString(", ", args); } - public static String toString(final String delim, final String... args) - { + public static String toString(final String delim, final String... args) { return toString(delim, (Object[]) args); } @@ -272,28 +229,19 @@ public static String toString(final String delim, final String... args) Turn an array (or varargs) set of Objects into a String using the specified delimiter. */ - public static String toString(final String delim, final Object... args) - { + public static String toString(final String delim, final Object... args) { String result; - if (args == null) - { + if (args == null) { result = "" + null; - } - else if (args.length == 0) - { + } else if (args.length == 0) { result = ""; - } - else if (args.length == 1) - { - result = toString(args[ 0]); - } - else - { + } else if (args.length == 1) { + result = toString(args[0]); + } else { final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < args.length - 1; ++i) - { + for (int i = 0; i < args.length - 1; ++i) { builder.append(toString(args[i])); builder.append(delim); } @@ -302,22 +250,16 @@ else if (args.length == 1) result = builder.toString(); } - return result; } /** @return the prefix found, or null if not found */ - public static String getPrefix( - final Set prefixes, - final String s) - { + public static String getPrefix(final Set prefixes, final String s) { String result = null; - for (final String prefix : prefixes) - { - if (s.startsWith(prefix)) - { + for (final String prefix : prefixes) { + if (s.startsWith(prefix)) { result = prefix; break; } @@ -331,40 +273,24 @@ public static String getPrefix( */ public static String findAndStripPrefix( final Set prefixes, - final String s) - { + final String s) { final String prefix = getPrefix(prefixes, s); - if (prefix == null) - { + if (prefix == null) { throw new IllegalArgumentException(s); } return stripPrefix(s, prefix); } - private static String NEWLINE_STR = null; - - public static String NEWLINE() - { - if (NEWLINE_STR == null) - { - NEWLINE_STR = System.getProperty("line.separator"); - } - return NEWLINE_STR; - } - - private static double micros(final long nanos) - { + private static double micros(final long nanos) { return (double) nanos / 1000; } - private static double millis(final long nanos) - { + private static double millis(final long nanos) { return (double) nanos / (1000 * 1000); } - private static double seconds(final long nanos) - { + private static double seconds(final long nanos) { return (double) nanos / (1000 * 1000 * (long) 1000); } @@ -372,8 +298,7 @@ private static double seconds(final long nanos) @param nanos elapsed nanoseconds @return a String describing the elapsed duration in seconds */ - public static String getSecondsString(final long nanos) - { + public static String getSecondsString(final long nanos) { return getTimingString(nanos, TimeUnit.SECONDS); } @@ -396,25 +321,26 @@ public static String getMillisString(final long nanos) public static String getTimingString( final long nanos, - final TimeUnit timeUnit) - { + final TimeUnit timeUnit) { String result = null; - if (timeUnit == TimeUnit.NANOSECONDS) - { - result = String.format(NANOS_FORMAT, nanos); - } - else if (timeUnit == TimeUnit.MICROSECONDS) - { - result = String.format(MICROS_FORMAT, micros(nanos)); - } - else if (timeUnit == TimeUnit.MILLISECONDS) - { - result = String.format(MILLIS_FORMAT, millis(nanos)); - } - else if (timeUnit == TimeUnit.SECONDS) - { - result = String.format(SECONDS_FORMAT, seconds(nanos)); + if (null != timeUnit) { + switch (timeUnit) { + case NANOSECONDS: + result = String.format(NANOS_FORMAT, nanos); + break; + case MICROSECONDS: + result = String.format(MICROS_FORMAT, micros(nanos)); + break; + case MILLISECONDS: + result = String.format(MILLIS_FORMAT, millis(nanos)); + break; + case SECONDS: + result = String.format(SECONDS_FORMAT, seconds(nanos)); + break; + default: + break; + } } return result; @@ -427,21 +353,15 @@ else if (timeUnit == TimeUnit.SECONDS) @param nanos elapsed nanoseconds @return a String describing the elapsed duration */ - public static String getTimingString(final long nanos) - { + public static String getTimingString(final long nanos) { String runTimeString; final long MICROSECOND = 1000; final long MILLISECOND = 1000 * MICROSECOND; - if (nanos < 10 * MICROSECOND) - { + if (nanos < 10 * MICROSECOND) { runTimeString = nanos + " nanoseconds"; - } - else if (nanos < 10 * MILLISECOND) - { + } else if (nanos < 10 * MILLISECOND) { runTimeString = (nanos / MICROSECOND) + " microseconds"; - } - else - { + } else { runTimeString = (nanos / MILLISECOND) + " milliseconds"; } @@ -482,18 +402,13 @@ public static String[] toStringArray(final Object[] items) /** @return a String */ - public static String toString( - final Collection c, - final String delim) - { + public static String toString(final Collection c, final String delim) { final String[] strings = toStringArray(c); - //Arrays.sort( strings ); return StringUtil.toString(delim, (Object[]) strings); } - public static String toString(final Collection c) - { + public static String toString(final Collection c) { return toString(c, ", "); } @@ -543,19 +458,3 @@ public static String toLines(final List items) } } - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ThrowableMapper.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ThrowableMapper.java index 55cbf28329d..e33a99b4620 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ThrowableMapper.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/ThrowableMapper.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -59,8 +60,7 @@ public final class ThrowableMapper By default, any Throwable whose package does not start with one of these packages must be mapped to something standard. */ - private final static Set OK_PACKAGES = - SetUtil.newUnmodifiableStringSet("java.", "javax."); + private static final Set OK_PACKAGES = SetUtil.newUnmodifiableStringSet("java.", "javax."); public ThrowableMapper(final Throwable t) { @@ -85,72 +85,51 @@ private static boolean shouldMap(final Throwable t) return (shouldMap); } - public static Throwable map(final Throwable t) - { + public static Throwable map(final Throwable t) { Throwable result = t; - if (t != null) - { + if (t != null) { final Throwable tCause = t.getCause(); final Throwable tCauseMapped = map(tCause); // if either this Exception or its cause needs/was mapped, // then we must form a new Exception - - if (shouldMap(t)) - { + if (shouldMap(t)) { + // the Throwable itself needs to be mapped final String msg = t.getMessage(); - if (t instanceof Error) - { + if (t instanceof Error) { result = new Error(msg, tCauseMapped); - } - else if (t instanceof RuntimeException) - { + } else if (t instanceof RuntimeException) { result = new RuntimeException(msg, tCauseMapped); - } - else if (t instanceof Exception) - { + } else if (t instanceof Exception) { result = new Exception(msg, tCauseMapped); - } - else - { + } else { result = new Throwable(msg, tCauseMapped); } result.setStackTrace(t.getStackTrace()); - } - else if (tCauseMapped != tCause) - { + } else if (tCauseMapped != tCause) { + // the Throwable doesn't need mapping, but its Cause does // create a Throwable of the same class, and insert its // cause and stack trace. - try - { - final Constructor c = - t.getClass().getConstructor(String.class, Throwable.class); - result = c.newInstance(t.getMessage(), tCauseMapped); - } - catch (final Throwable t1) - { - try - { - final Constructor c = - t.getClass().getConstructor(String.class); - result = c.newInstance(t.getMessage()); + try { + final Constructor constructor = t.getClass().getConstructor(String.class, Throwable.class); + result = constructor.newInstance(t.getMessage(), tCauseMapped); + } catch (final Throwable t1) { + try { + final Constructor constructor = t.getClass().getConstructor(String.class); + result = constructor.newInstance(t.getMessage()); result.initCause(tCauseMapped); - } - catch (final Throwable t2) - { + } catch (final Throwable t2) { result = new Throwable(t.getMessage(), tCauseMapped); } } result.setStackTrace(tCause.getStackTrace()); - } - else - { + } else { result = t; } } @@ -172,11 +151,3 @@ public Throwable map() } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TimingDelta.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TimingDelta.java index 843f15842af..abfc1b83c5f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TimingDelta.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TimingDelta.java @@ -37,14 +37,14 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; /** Central registry of timing values. Not intended for threaded use. */ -public final class TimingDelta -{ +public final class TimingDelta { private long mLastNanos; public TimingDelta() @@ -68,47 +68,12 @@ public long elapsedNanos() return elapsed; } - public long elapsedMicros() - { - return elapsed() / 1000; + public long elapsedMicros() { + return elapsedNanos() / 1000; } - public long elapsedMillis() - { - return elapsed() / (1000 * 1000); + public long elapsedMillis() { + return elapsedNanos() / (1000 * 1000); } } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java index 8c214c73396..964fdbd364d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util; @@ -543,19 +544,3 @@ public static Map checkedMap(final Map m, final Class keyC } } - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeChangeNotificationBuilder.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeChangeNotificationBuilder.java index 722a6f3cf5d..49de56d62a8 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeChangeNotificationBuilder.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeChangeNotificationBuilder.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -55,8 +56,8 @@ public AttributeChangeNotificationBuilder( super(AttributeChangeNotification.ATTRIBUTE_CHANGE, source); } - public final Notification buildNew() - { + @Override + public final Notification buildNew() { throw new IllegalArgumentException(); } @@ -99,8 +100,3 @@ public final AttributeChangeNotification buildAttributeChange( } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeComparator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeComparator.java index 787d304551a..9197cf5c71b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeComparator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeComparator.java @@ -71,7 +71,6 @@ public boolean equals(Object other) @Override public int hashCode() { - int hash = 7; - return hash; + return 7; } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeFilter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeFilter.java index 8b7f0985ac7..daddd51fcc1 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeFilter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/AttributeFilter.java @@ -52,9 +52,3 @@ public interface AttributeFilter public boolean filterAttribute(final MBeanAttributeInfo info); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java index 48a5afd2bcd..68c16139e3b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx; @@ -68,8 +68,7 @@ public static String toString(final ObjectName objectName) return "" + objectName; } - public final static String MBEAN_SERVER_DELEGATE = - "JMImplementation:type=MBeanServerDelegate"; + public static final String MBEAN_SERVER_DELEGATE = "JMImplementation:type=MBeanServerDelegate"; public static MBeanServerDelegateMBean getMBeanServerDelegateMBean(final MBeanServerConnection server) { @@ -89,30 +88,28 @@ public static T newProxyInstance(final MBeanServerConnection conn, final Obj return clazz.cast(MBeanServerInvocationHandler.newProxyInstance(conn, objectName, clazz, notificationBroadcaster)); } - public final static String MBEAN_SERVER_ID_ATTRIBUTE_NAME = - "MBeanServerId"; + public static final String MBEAN_SERVER_ID_ATTRIBUTE_NAME = "MBeanServerId"; /** The wilcard property at the end of an ObjectName which indicates that it's an ObjectName pattern. */ - public final static String WILD_PROP = ",*"; + public static final String WILD_PROP = ",*"; /** The wilcard property at the end of an ObjectName which indicates that all properties should be matched. */ - public final static String WILD_ALL = "*"; + public static final String WILD_ALL = "*"; - public static ObjectName getMBeanServerDelegateObjectName() - { + public static ObjectName getMBeanServerDelegateObjectName() { return (newObjectName("JMImplementation:type=MBeanServerDelegate")); } public static String getMBeanServerDelegateInfo(final MBeanServer server) { final MBeanServerDelegateMBean delegate = getMBeanServerDelegateMBean(server); - final String mbeanServerInfo = "MBeanServerDelegate: {" + + return "MBeanServerDelegate: {" + "MBeanServerId = " + delegate.getMBeanServerId() + ", ImplementationMame = " + delegate.getImplementationName() + ", ImplementationVendor = " + delegate.getImplementationVendor() + @@ -121,7 +118,6 @@ public static String getMBeanServerDelegateInfo(final MBeanServer server) ", SpecificationVendor = " + delegate.getSpecificationVendor() + ", SpecificationVersion = " + delegate.getSpecificationVersion() + " }"; - return mbeanServerInfo; } public static void listenToMBeanServerDelegate( @@ -266,7 +262,7 @@ public static ObjectName removeProperty( private JMXUtil() { - // disallow; + // disallow } public static final String GET = "get"; @@ -669,7 +665,7 @@ public static Map attributeListToStringMap(final AttributeList a final Attribute attr = (Attribute) attrs.get(i); final Object value = attr.getValue(); - final String s = (String) (value == null ? null : "" + value); + final String s = (value == null ? null : "" + value); map.put(attr.getName(), s); } @@ -814,16 +810,11 @@ private static AttributeList getAttributesSingly( final Object value = conn.getAttribute(objectName, name); attrs.add(new Attribute(name, value)); - } - catch (Exception e) - { + } catch (InstanceNotFoundException e) { // if the MBean disappeared while processing, just consider it gone // from the start, even if we got some Attributes - if (e instanceof InstanceNotFoundException) - { - throw (InstanceNotFoundException) e; - } - + throw e; + } catch (Exception e) { if (problemNames != null) { problemNames.add(name); @@ -889,85 +880,7 @@ public static AttributeList getAttributesRobust( return (attrs); } - - /** - Return true if the two MBeanAttributeInfo[] contain the same attributes - WARNING: arrays will be sorted to perform the comparison if they are the same length. - boolean - sameAttributes( MBeanAttributeInfo[] infos1, MBeanAttributeInfo[] infos2 ) - { - boolean equal = false; - - if( infos1.length == infos2.length ) - { - equal = ArrayUtil.arraysEqual( infos1, infos2 ); - if ( ! equal ) - { - // could still be equal, just in different order - Arrays.sort( infos1, MBeanAttributeInfoComparator.INSTANCE ); - Arrays.sort( infos2, MBeanAttributeInfoComparator.INSTANCE ); - - equal = true; // reset to false upon failure - for( int i = 0; i < infos1.length; ++i ) - { - if ( ! infos1[ i ].equals( infos2[ i ] ) ) - { - equal = false; - break; - } - } - } - else - { - equal = true; - } - } - return( equal ); - } - */ - /** - Return true if the two MBeanAttributeInfo[] contain the same operations - WARNING: arrays will be sorted to perform the comparison if they are the same length. - boolean - sameOperations( final MBeanOperationInfo[] infos1, final MBeanOperationInfo[] infos2 ) - { - boolean equal = false; - - if ( infos1.length == infos2.length ) - { - // if they're in identical order, this is the quickest test if they ultimately succeed - equal = ArrayUtil.arraysEqual( infos1, infos2 ); - if ( ! equal ) - { - // could still be equal, just in different order - Arrays.sort( infos1, MBeanOperationInfoComparator.INSTANCE ); - Arrays.sort( infos2, MBeanOperationInfoComparator.INSTANCE ); - - equal = true; // reset to false upon failure - for( int i = 0; i < infos1.length; ++i ) - { - if ( ! infos1[ i ].equals( infos2[ i ] ) ) - { - equal = false; - break; - } - } - } - } - return( equal ); - } - */ - /** - Return true if the MBeanInfos have the same interface (for Attributes and - operations). MBeanInfo.equals() is not sufficient as it will fail if the - infos are in different order, but are actually the same. - boolean - sameInterface( MBeanInfo info1, MBeanInfo info2 ) - { - return( sameAttributes( info1.getAttributes(), info2.getAttributes() ) && - sameOperations( info1.getOperations(), info2.getOperations() ) ); - } - */ + public static boolean isIs(final Method method) { return (method.getName().startsWith(IS) && method.getParameterTypes().length == 0); @@ -1047,19 +960,14 @@ public static boolean isIsOrGetter(Method method) return (isGetter(method) || isIs(method)); } - public static String getAttributeName(final Method method) - { + public static String getAttributeName(final Method method) { final String methodName = method.getName(); - String attrName = null; int prefixLength; - if (methodName.startsWith(GET) || methodName.startsWith(SET)) - { + if (methodName.startsWith(GET) || methodName.startsWith(SET)) { prefixLength = 3; - } - else - { + } else { prefixLength = 2; } @@ -1071,7 +979,7 @@ public static boolean isSetter(Method method) return (method.getName().startsWith(SET) && method.getParameterTypes().length == 1 && method.getParameterTypes()[ 0] != Attribute.class && - method.getReturnType().getName().equals("void")); + method.getReturnType().equals(Void.TYPE)); } public static boolean isGetAttribute(Method m) @@ -1261,28 +1169,6 @@ else if (isSetter(method)) } } - /* - java.util.Iterator iter = null; - trace( "-------------------- getterSetters -------------------" ); - iter = getterSetters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getName() + ", " ); - } - trace( "-------------------- getters -------------------" ); - iter = getters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getName() + ", " ); - } - trace( "-------------------- setters -------------------" ); - iter = setters.values().iterator(); - while ( iter.hasNext() ) - { - trace( ((Method)iter.next()).getName() + ", " ); - } - */ - final MBeanAttributeInfo[] attrInfos = generateMBeanAttributeInfos(getterSetters.values(), getters.values(), setters.values()); @@ -1466,39 +1352,7 @@ else if (infos2 == null) final MBeanConstructorInfo[] merged = new MBeanConstructorInfo[all.size()]; return all.toArray(merged); } - - /** - Merge two MBeanInfo. 'info1' takes priority in conflicts, name, etc. - - @param info1 - @param info2 - public static MBeanInfo - mergeMBeanInfos( - final MBeanInfo info1, - final MBeanInfo info2 ) - { - if ( info1 == null ) - { - return info2; - } - else if ( info2 == null ) - { - return( info1 ); - } - - return( new MBeanInfo( - info1.getClassName(), - info1.getDescription(), - mergeMBeanAttributeInfos( info1.getAttributes(), info2.getAttributes() ), - mergeMBeanConstructorInfos( info1.getConstructors(), info2.getConstructors() ), - mergeMBeanOperationInfos( info1.getOperations(), info2.getOperations() ), - mergeMBeanNotificationInfos( info1.getNotifications(), info2.getNotifications() ), - ) ); - - fix to merge descriptors! - - } - */ + /** Make a new MBeanInfo from an existing one, substituting MBeanAttributeInfo[] @@ -1574,36 +1428,25 @@ public static int findMBeanOperationInfo( return resultIdx; } - public static boolean domainMatches( - final String defaultDomain, - final ObjectName pattern, - final ObjectName candidate) - { + public static boolean domainMatches(final String defaultDomain, final ObjectName pattern, final ObjectName candidate) { boolean matches; final String candidateDomain = candidate.getDomain(); - if (pattern.isDomainPattern()) - { - final String regex = - RegexUtil.wildcardToJavaRegex(pattern.getDomain()); + if (pattern.isDomainPattern()) { + final String regex = RegexUtil.wildcardToJavaRegex(pattern.getDomain()); matches = Pattern.matches(regex, candidateDomain); - } - else - { + } else { // domain is not a pattern String patternDomain = pattern.getDomain(); - if (patternDomain.length() == 0) - { + if (patternDomain.length() == 0) { patternDomain = defaultDomain; } matches = patternDomain.equals(candidateDomain); } - //dm( "MBeanProxyMgrImpl.domainMatches: " + matches + " " + pattern + " vs " + candidate ); - return (matches); } @@ -1623,7 +1466,7 @@ public static boolean matchesPattern( // Since we used canonical form any match means the pattern props String // must be a substring of candidateProps - if (candidateProps.indexOf(patternProps) >= 0) + if (candidateProps.contains(patternProps)) { matches = true; } @@ -1725,7 +1568,7 @@ public static Set queryNames( { // ignore, can't happen. } - return null; + return Collections.emptySet(); } /** @@ -1789,11 +1632,6 @@ public static T remove(final List infos, final S return removed; } - private static String NL() - { - return StringUtil.NEWLINE(); - } - private static String title(final MBeanFeatureInfo info) { return info.getName() + ", \"" + info.getDescription() + "\""; @@ -1801,7 +1639,7 @@ private static String title(final MBeanFeatureInfo info) public static String toString(final Descriptor d, final int indent) { - final String NL = NL(); + final String NL = StringUtil.LS; final StringBuilder buf = new StringBuilder(); if (d != null && d.getFieldNames().length != 0) { @@ -1818,32 +1656,29 @@ public static String toString(final Descriptor d, final int indent) public static String impactStr(final int impact) { String s; - if (impact == MBeanOperationInfo.INFO) - { - s = "INFO"; - } - else if (impact == MBeanOperationInfo.ACTION) - { - s = "ACTION"; - } - else if (impact == MBeanOperationInfo.UNKNOWN) - { - s = "UNKNOWN"; - } - else if (impact == MBeanOperationInfo.ACTION_INFO) - { - s = "ACTION_INFO"; - } - else - { - s = "" + impact; + switch (impact) { + case MBeanOperationInfo.INFO: + s = "INFO"; + break; + case MBeanOperationInfo.ACTION: + s = "ACTION"; + break; + case MBeanOperationInfo.UNKNOWN: + s = "UNKNOWN"; + break; + case MBeanOperationInfo.ACTION_INFO: + s = "ACTION_INFO"; + break; + default: + s = "" + impact; + break; } return s; } public static String toString(final MBeanOperationInfo info, final int indent) { - final String NL = NL(); + final String NL = StringUtil.LS; final StringBuilder buf = new StringBuilder(); final String idt = idt(indent + 2); @@ -1864,7 +1699,7 @@ public static String toString(final MBeanOperationInfo info, final int indent) public static String toString(final MBeanAttributeInfo info, final int indent) { - final String NL = NL(); + final String NL = StringUtil.LS; final StringBuilder buf = new StringBuilder(); final String idt = idt(indent + 2); @@ -1912,7 +1747,7 @@ public static String toString(final MBeanAttributeInfo info, final int indent) public static String toString(final MBeanInfo info) { final StringBuilder buf = new StringBuilder(); - final String NL = NL(); + final String NL = StringUtil.LS; int indent = 2; buf.append("Classname: ").append(info.getClassName()).append(NL); @@ -1968,4 +1803,3 @@ private static String nvp(final String name, final Object value) } } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanAttributeInfoComparator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanAttributeInfoComparator.java index 5d03734696b..0c9b5ea7a69 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanAttributeInfoComparator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanAttributeInfoComparator.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -76,8 +77,7 @@ public boolean equals(Object other) @Override public int hashCode() { - int hash = 7; - return hash; + return 7; } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanInterfaceGenerator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanInterfaceGenerator.java index 19e11c37e7c..4eb802321a3 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanInterfaceGenerator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanInterfaceGenerator.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundationa and/or affiliates] package org.glassfish.admin.amx.util.jmx; @@ -65,22 +65,20 @@ public class MBeanInterfaceGenerator Map mCounts; - public MBeanInterfaceGenerator() - { + public MBeanInterfaceGenerator() { mCounts = null; mEmitComments = true; } - //private final static String INDENT = "\t"; - private final static String INDENT = " "; + private static final String INDENT = " "; - private final static String NEWLINE = "\n"; + private static final String NEWLINE = "\n"; - private final static String PARAM_DELIM = ", "; + private static final String PARAM_DELIM = ", "; - public final static String FINAL_PREFIX = "final "; + public static final String FINAL_PREFIX = "final "; - public final static int IMPORT_THRESHOLD = 1; + public static final int IMPORT_THRESHOLD = 1; private static final String BRACKETS = "[]"; @@ -96,18 +94,14 @@ static String stripBrackets(String name) return (result); } - private static void countType(Map counts, String typeIn) - { + private static void countType(Map counts, String typeIn) { final String type = stripBrackets(ClassUtil.getFriendlyClassname(typeIn)); Integer count = counts.get(type); - if (count == null) - { - count = Integer.valueOf(1); - } - else - { - count = Integer.valueOf(count.intValue() + 1); + if (count == null) { + count = 1; + } else { + count++; } counts.put(type, count); @@ -141,28 +135,24 @@ private static void countTypes(Map counts, MBeanOperationInfo[] } } - String - getCodeClassname( final String classnameIn ) - { - final String name = ClassUtil.getFriendlyClassname( classnameIn ); + String getCodeClassname(final String classnameIn) { + final String name = ClassUtil.getFriendlyClassname(classnameIn); String base = name; String extra = ""; final int idx = name.indexOf('['); - if ( idx > 0 ) - { - base = name.substring(0, idx); + if (idx > 0) { + base = name.substring(0, idx); extra = name.substring(idx); } - if ( typeMayBeAbbreviated( base ) ) - { - base = ClassUtil.stripPackagePrefix( base ); - } + if (typeMayBeAbbreviated(base)) { + base = ClassUtil.stripPackagePrefix(base); + } - return base + extra; - } + return base + extra; + } private Map countAllTypes(MBeanInfo info) { @@ -244,36 +234,27 @@ public String generate(final MBeanInfo info, boolean emitComments) final MBeanAttributeInfo[] attrInfos = info.getAttributes(); final MBeanOperationInfo[] operationInfos = info.getOperations(); - if (attrInfos != null) - { + if (attrInfos != null) { Arrays.sort(attrInfos, MBeanAttributeInfoComparator.INSTANCE); - final List readOnlyAttrInfos = new ArrayList(); - final List writebleAttrInfos = new ArrayList(); - for( final MBeanAttributeInfo ai : attrInfos ) - { - if ( ai.isWritable() ) - { + final List readOnlyAttrInfos = new ArrayList(); + final List writebleAttrInfos = new ArrayList(); + for (final MBeanAttributeInfo ai : attrInfos) { + if (ai.isWritable()) { writebleAttrInfos.add(ai); - } - else - { + } else { readOnlyAttrInfos.add(ai); } } - buf.append( generateAttributes( readOnlyAttrInfos ) ); - buf.append( generateAttributes( writebleAttrInfos ) ); + buf.append(generateAttributes(readOnlyAttrInfos)); + buf.append(generateAttributes(writebleAttrInfos)); } - if (operationInfos != null) - { - if (operationInfos.length != 0) - { + if (operationInfos != null && operationInfos.length != 0) { Arrays.sort(operationInfos, MBeanOperationInfoComparator.INSTANCE); buf.append(NEWLINE + "// -------------------- Operations --------------------" + NEWLINE); buf.append(generateOperations(operationInfos)); - } } @@ -291,7 +272,7 @@ protected String indent(String contents, String prefix) for (int i = 0; i < lines.length; ++i) { - buf.append(prefix + lines[i] + NEWLINE); + buf.append(prefix).append(lines[i]).append(NEWLINE); } if (buf.length() != 0) @@ -339,11 +320,9 @@ protected String formMethod(String returnType, String name, String[] params, Str final StringBuilder buf = new StringBuilder(); buf.append(" "); - for (int i = 0; i < params.length; ++i) - { - //buf.append(FINAL_PREFIX); + for (int i = 0; i < params.length; ++i) { buf.append(getCodeClassname(params[i])); - buf.append(" " + names[i]); + buf.append(" ").append(names[i]); buf.append(PARAM_DELIM); } @@ -406,7 +385,7 @@ protected String generateAttributes( final List infos) comment = getGetterComment(info, javaName); if (comment.length() != 0) { - buf.append(indent(comment) + NEWLINE); + buf.append(indent(comment)).append(NEWLINE); } } buf.append(indent(formMethod(type, "get" + javaName, null, null))); @@ -420,12 +399,12 @@ protected String generateAttributes( final List infos) comment = getSetterComment(info, javaName); if (comment.length() != 0) { - buf.append(indent(comment) + NEWLINE); + buf.append(indent(comment)).append(NEWLINE); } } - typeTemp[ 0] = type; - nameTemp[ 0] = "value"; + typeTemp[0] = type; + nameTemp[0] = "value"; buf.append(indent(formMethod("void", "set" + javaName, typeTemp, nameTemp))); buf.append( NEWLINE ); @@ -479,9 +458,9 @@ protected boolean isBoilerplateDescription(final String description) final String trimmed = description.trim(); return trimmed.length() == 0 || - trimmed.indexOf("Attribute exposed for management") >= 0 || - trimmed.indexOf("Operation exposed for management") >= 0 || - trimmed.indexOf("No Description was available") >= 0 || + trimmed.contains("Attribute exposed for management") || + trimmed.contains("Operation exposed for management") || + trimmed.contains("No Description was available") || trimmed.equals("n/a"); } @@ -540,18 +519,12 @@ public static String toString(final Descriptor d) { final String NL = NEWLINE; final StringBuilder buf = new StringBuilder(); - if (d != null && d.getFieldNames().length != 0) - { - //buf.append( idt(indent) + "Descriptor = " + NL ); + if (d != null && d.getFieldNames().length != 0) { for (final String fieldName : d.getFieldNames()) { buf.append(nvp(fieldName, d.getFieldValue(fieldName))).append(NL); } } - else - { - //buf.append( idt(indent) + "Descriptor = n/a" + NL ); - } return buf.toString(); } @@ -636,9 +609,3 @@ public String getExceptions(final MBeanOperationInfo info) } } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanOperationInfoComparator.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanOperationInfoComparator.java index 24af7dbd3ce..cea5d6591bd 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanOperationInfoComparator.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanOperationInfoComparator.java @@ -37,22 +37,18 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; import java.io.Serializable; import javax.management.MBeanOperationInfo; -import org.glassfish.admin.amx.util.jmx.stringifier.MBeanFeatureInfoStringifierOptions; import org.glassfish.admin.amx.util.jmx.stringifier.MBeanOperationInfoStringifier; /** Caution: this Comparator may be inconsistent with equals() because it ignores the description. */ -public final class MBeanOperationInfoComparator - implements java.util.Comparator, Serializable -{ - private static final MBeanOperationInfoStringifier OPERATION_INFO_STRINGIFIER = - new MBeanOperationInfoStringifier(new MBeanFeatureInfoStringifierOptions(false, ",")); +public final class MBeanOperationInfoComparator implements java.util.Comparator, Serializable { public static final MBeanOperationInfoComparator INSTANCE = new MBeanOperationInfoComparator(); @@ -74,8 +70,7 @@ public int compare(final MBeanOperationInfo info1, final MBeanOperationInfo info if (c == 0) { // names the same, subsort on signature, first by number of params - c = MBeanOperationInfoStringifier.getSignature(info1).compareTo( - MBeanOperationInfoStringifier.getSignature(info2)); + c = MBeanOperationInfoStringifier.getSignature(info1).compareTo(MBeanOperationInfoStringifier.getSignature(info2)); } } @@ -84,15 +79,13 @@ public int compare(final MBeanOperationInfo info1, final MBeanOperationInfo info } @Override - public boolean equals(Object other) - { + public boolean equals(Object other) { return (other instanceof MBeanOperationInfoComparator); } @Override public int hashCode() { - int hash = 3; - return hash; + return 3; } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanProxyHandler.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanProxyHandler.java index f75afa0c084..324e77a426b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanProxyHandler.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanProxyHandler.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -44,7 +45,6 @@ import org.glassfish.admin.amx.util.ObjectUtil; import org.glassfish.admin.amx.util.Output; import org.glassfish.admin.amx.util.StringUtil; -import org.glassfish.admin.amx.util.ClassUtil; import javax.management.*; import java.io.IOException; @@ -60,15 +60,15 @@ */ public class MBeanProxyHandler extends MBeanServerInvocationHandler { - protected final static String GET = "get"; + protected static final String GET = "get"; - protected final static String SET = "set"; + protected static final String SET = "set"; - protected final static String IS = "is"; + protected static final String IS = "is"; - protected final static int GET_PREFIX_LENGTH = GET.length(); + protected static final int GET_PREFIX_LENGTH = GET.length(); - protected final static int IS_PREFIX_LENGTH = IS.length(); + protected static final int IS_PREFIX_LENGTH = IS.length(); /** MBeanInfo we first obtained */ protected final MBeanInfo mInitialMBeanInfo; @@ -135,7 +135,6 @@ public MBeanProxyHandler( super(conn, objectName); mDebug = AMXDebug.getInstance().getOutput(getClass().getName()); - //debugMethod( "MBeanProxyHandler", objectName ); mTargetValid = true; if (mbeanInfo != null) @@ -157,46 +156,35 @@ public MBeanProxyHandler( mHashCode = this.hashCode(); } - public boolean isInvariantMBeanInfo() - { + public boolean isInvariantMBeanInfo() { final Object value = mInitialMBeanInfo.getDescriptor().getFieldValue("immutableInfo"); return Boolean.parseBoolean("" + value); } - public String interfaceName() - { - final String value = (String) getMBeanInfo().getDescriptor().getFieldValue("interfaceName"); - return value; + public String interfaceName() { + return (String) getMBeanInfo().getDescriptor().getFieldValue("interfaceName"); } - public final void targetUnregistered() - { + public final void targetUnregistered() { debugMethod(getObjectName().toString(), "targetUnregistered"); mTargetValid = false; } - public final void connectionBad() - { + public final void connectionBad() { debugMethod("connectionBad"); mTargetValid = false; } /** return true if the MBean is local (in process) */ - public boolean isLocal() - { + public boolean isLocal() { return getMBeanServerConnection() instanceof MBeanServer; } - public final boolean isValid() - { - if (mTargetValid) - { - try - { + public final boolean isValid() { + if (mTargetValid) { + try { mTargetValid = getMBeanServerConnection().isRegistered(getObjectName()); - } - catch (Exception e) - { + } catch (Exception e) { debug("checkValid: connection failed"); mTargetValid = false; } @@ -204,8 +192,7 @@ public final boolean isValid() return (mTargetValid); } - public synchronized Logger getProxyLogger() - { + public synchronized Logger getProxyLogger() { return Logger.getLogger(this.getClass().getName()); } @@ -232,14 +219,10 @@ private synchronized MBeanInfo _getMBeanInfo() return info; } - public MBeanInfo getMBeanInfo() - { - try - { + public MBeanInfo getMBeanInfo() { + try { return (_getMBeanInfo()); - } - catch (Exception e) - { + } catch (Exception e) { throw new RuntimeException(e); } } @@ -309,29 +292,19 @@ public AttributeList setAttributes(final AttributeList requested) return (results); } - - private final String LOG_LEVEL_NAME = "LogLevel"; - - protected void postGetAttributeHook( - final String name, - final Object value) - { + + protected void postGetAttributeHook(final String name, final Object value) + { //no-op for overridng in subclasses } - protected void postGetAttributesHook( - final String[] requested, - final AttributeList actual) - { + protected void postGetAttributesHook(final String[] requested, final AttributeList actual) { //no-op for overridng in subclasses } - protected void postSetAttributeHook(final Attribute attr) - { + protected void postSetAttributeHook(final Attribute attr){ } - protected void postSetAttributesHook( - final AttributeList requested, - final AttributeList actual) - { + protected void postSetAttributesHook(final AttributeList requested, final AttributeList actual) { + //no-op for overridng in subclasses } /** JMX direct invoke */ @@ -349,12 +322,8 @@ public Object invoke(String methodName, Object[] params, String[] signature)

For anything else, the behavior of MBeanServerInvocationHandler is used. */ - public Object invoke( - Object proxy, - Method method, - Object[] args) - throws java.lang.Throwable - { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws java.lang.Throwable { final String methodName = method.getName(); final int numArgs = args == null ? 0 : args.length; @@ -367,70 +336,52 @@ public Object invoke( boolean handled = false; - if (methodName.equals("getObjectName")) - { + if (methodName.equals("getObjectName")) { + handled = true; result = getObjectName(); - } - else if (methodName.equals("getMBeanInfo") && numArgs == 0) - { + } else if (methodName.equals("getMBeanInfo") && numArgs == 0) { + handled = true; result = getMBeanInfo(); - } - else if ((isGetter || isSetter)) - { + } else if ((isGetter || isSetter)) { + handled = true; final String javaName = extractAttributeNameFromMethod(methodName); String attributeName = javaName; - //trace( "MBeanProxyHandler.invoke: mapped attribute: " + javaName + " => " + attributeName ); - - if (isGetter) - { + if (isGetter) { result = getAttribute(attributeName); - } - else - { - final Attribute attr = new Attribute(attributeName, args[ 0]); + } else { + final Attribute attr = new Attribute(attributeName, args[0]); setAttribute(attr); } - } - else if (methodName.indexOf("etAttribute") == 1) - { + } else if (methodName.indexOf("etAttribute") == 1) { + handled = true; // likely one of getAttribute(), getAttributes(), setAttribute(), setAttributes() - - //p( "MBeanProxyHandler.invoke: " + method.getName() + " " + numArgs + " args." ); - if (JMXUtil.isGetAttribute(method)) - { - final String attrName = (String) args[ 0]; + if (JMXUtil.isGetAttribute(method)) { + + final String attrName = (String) args[0]; result = getAttribute(attrName); - } - else if (JMXUtil.isGetAttributes(method)) - { - final String[] attrNames = (String[]) args[ 0]; + } else if (JMXUtil.isGetAttributes(method)) { + final String[] attrNames = (String[]) args[0]; result = getAttributes(attrNames); - } - else if (JMXUtil.isSetAttribute(method)) - { - final Attribute attr = (Attribute) args[ 0]; + } else if (JMXUtil.isSetAttribute(method)) { + final Attribute attr = (Attribute) args[0]; setAttribute(attr); - } - else if (JMXUtil.isSetAttributes(method)) - { - final AttributeList requested = (AttributeList) args[ 0]; + } else if (JMXUtil.isSetAttributes(method)) { + final AttributeList requested = (AttributeList) args[0]; result = setAttributes(requested); - } - else - { + } else { handled = false; } - } - else if (methodName.equals("hashCode")) - { + + } else if (methodName.equals("hashCode")) { + /* java.lang.reflect.Proxy will route all calls through invoke(), even hashCode(). To avoid newing up an Integer every time, @@ -440,20 +391,15 @@ when proxies are inserted into Sets or Maps. toString() and */ result = mHashCode; handled = true; - } - else if (methodName.equals("toString")) - { + } else if (methodName.equals("toString")) { result = "proxy to " + getObjectName(); handled = true; - } - else if (methodName.equals("equals") && numArgs == 1) - { - result = this.equals(args[ 0]); + } else if (methodName.equals("equals") && numArgs == 1) { + result = this.equals(args[0]); handled = true; } - if (!handled) - { + if (!handled) { debugMethod(getObjectName().toString(), "super.invoke", method.getName(), args); @@ -501,8 +447,3 @@ protected void debug(final Object o) } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanRegistrationListener.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanRegistrationListener.java index dba65cb0a92..183e4245871 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanRegistrationListener.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/MBeanRegistrationListener.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -101,10 +102,9 @@ protected MBeanRegistrationListener( protected abstract void mbeanUnregistered(final ObjectName objectName); - public void handleNotification(final Notification notifIn, final Object handback) - { - if (!(notifIn instanceof MBeanServerNotification)) - { + @Override + public void handleNotification(final Notification notifIn, final Object handback) { + if (!(notifIn instanceof MBeanServerNotification)) { throw new IllegalArgumentException(notifIn.toString()); } @@ -129,7 +129,3 @@ else if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) } } - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationBuilder.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationBuilder.java index 5892223c11d..16df2a78093 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationBuilder.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationBuilder.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] PAyara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -62,55 +63,37 @@ public class NotificationBuilder private final Object mSource; - protected synchronized long nextSequenceNumber() - { + protected synchronized long nextSequenceNumber() { return (mSequenceNumber++); } - public NotificationBuilder( - final String notificationType, - final Object source) - { + public NotificationBuilder(final String notificationType, final Object source) { mNotificationType = notificationType; mSource = source; } - public final String getNotificationType() - { + public final String getNotificationType() { return (mNotificationType); } - public final Object getSource() - { + public final Object getSource() { return (mSource); } - protected final long now() - { + protected final long now() { return (System.currentTimeMillis()); } /** Build a new Notification with an existing Map. */ - public Notification buildNewWithMap( - final String message, - final Map userDataMap) - { - final Notification notif = new Notification( - mNotificationType, - mSource, - nextSequenceNumber(), - now(), - message); - - if (userDataMap != null) - { + public Notification buildNewWithMap(final String message, final Map userDataMap) { + final Notification notif = new Notification(mNotificationType, mSource, nextSequenceNumber(), now(), message); + + if (userDataMap != null) { notif.setUserData(userDataMap); - } - else - { - notif.setUserData(new HashMap()); + } else { + notif.setUserData(new HashMap<>()); } return (notif); @@ -134,56 +117,11 @@ public Notification buildNew(final String message) return buildNewWithMap(message, null); } - /** - Build a new Notification with one key/value for the Map. - public Notification - buildNew( - final String key, - final Serializable value ) - { - if ( value instanceof Map ) - { - throw new IllegalArgumentException("use buildNewWithMap" ); - } - - final Notification notif = buildNew(); - - if ( key != null ) - { - putMapData( notif, key, value ); - } - - return( notif ); - } - */ - /** - Build a new Notification with one key/value for the Map. - public Notification - buildNew( - final String key, - final Serializable value, - final String message ) - { - final Notification notif = buildNew( message ); - - if ( key != null ) - { - putMapData( notif, key, value ); - } - - return( notif ); - } - */ /** Put a single key/value pair into the user data Map. */ - public static final void putMapData( - final Notification notif, - final String keyToInsert, - final Serializable valueToInsert) - { - final Map userData = - JMXUtil.getUserDataMapString_Serializable(notif); + public static final void putMapData(final Notification notif, final String keyToInsert, final Serializable valueToInsert) { + final Map userData = JMXUtil.getUserDataMapString_Serializable(notif); userData.put(keyToInsert, valueToInsert); } @@ -191,19 +129,10 @@ public static final void putMapData( /** Put all key/value pairs into the user data Map. */ - public static final void putAllMapData( - final Notification notif, - final Map additionalUserData) - { - final Map userData = - JMXUtil.getUserDataMapString_Serializable(notif); + public static final void putAllMapData(final Notification notif, final Map additionalUserData) { + final Map userData = JMXUtil.getUserDataMapString_Serializable(notif); userData.putAll(additionalUserData); } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationEmitterSupport.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationEmitterSupport.java index ab74c5dcadf..0611f471e1e 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationEmitterSupport.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationEmitterSupport.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -70,9 +71,7 @@

For async use, a shared sender thread is used for all Notifications. */ -public final class NotificationEmitterSupport - extends NotificationBroadcasterSupport -{ +public final class NotificationEmitterSupport extends NotificationBroadcasterSupport { private final boolean mAsyncDelivery; private static volatile SenderThread sSenderThread = null; @@ -81,9 +80,7 @@ public final class NotificationEmitterSupport private final NotificationListenerTracking mListeners; - public NotificationEmitterSupport( - final boolean asyncDelivery) - { + public NotificationEmitterSupport(final boolean asyncDelivery) { mAsyncDelivery = asyncDelivery; mListenerTypeCounts = Collections.synchronizedMap(new HashMap()); @@ -91,16 +88,8 @@ public NotificationEmitterSupport( mListeners = new NotificationListenerTracking(true); } - public void cleanup() - { + public void cleanup() { // NO-OP with the shared SenderThread - /* - if ( mSenderThread != null ) - { - mSenderThread.quit(); - mSenderThread = null; - } - */ } /** @@ -145,8 +134,6 @@ public int getNotificationTypeListenerCount(final String type) return (resultCount); } - private static final String[] NO_TYPES = new String[0]; - private static final String WILDCARD_TYPE = "***"; private static final String[] ALL_TYPES = new String[] @@ -165,7 +152,7 @@ public int getNotificationTypeListenerCount(final String type) MBeanServerNotification.UNREGISTRATION_NOTIFICATION, }; - private final Integer COUNT_1 = Integer.valueOf(1); + private final Integer COUNT_1 = 1; private void incrementListenerCountForType(final String type) { @@ -173,7 +160,7 @@ private void incrementListenerCountForType(final String type) { final Integer count = mListenerTypeCounts.get(type); - final Integer newCount = (count == null) ? COUNT_1 : Integer.valueOf(count.intValue() + 1); + final Integer newCount = (count == null) ? COUNT_1 : count + 1; mListenerTypeCounts.put(type, newCount); } @@ -189,14 +176,11 @@ private void decrementListenerCountForType(final String type) throw new IllegalArgumentException(type); } - final int oldValue = count.intValue(); - if (oldValue == 1) - { + final int oldValue = count; + if (oldValue == 1) { mListenerTypeCounts.remove(type); - } - else - { - mListenerTypeCounts.put(type, Integer.valueOf(oldValue - 1)); + } else { + mListenerTypeCounts.put(type, oldValue - 1); } } } @@ -455,11 +439,3 @@ public void run() } } - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerBase.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerBase.java index bc339f41cdd..1d46b2993d9 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerBase.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerBase.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -67,9 +68,7 @@ a listener is maintained on the MBeanServer delegate. */ -public abstract class NotificationListenerBase - implements NotificationListener -{ +public abstract class NotificationListenerBase implements NotificationListener { private final MBeanServerConnection mConn; /** actual MBean ObjectNames, not patterns */ @@ -89,12 +88,7 @@ Calls this( conn, listenTo, null, null ).

Instantiating code must call setupListening() in order to initiate listening */ - protected NotificationListenerBase( - final String name, - final MBeanServerConnection conn, - final ObjectName pattern) - throws IOException - { + protected NotificationListenerBase(final String name, final MBeanServerConnection conn, final ObjectName pattern) throws IOException { this(name, conn, pattern, null); } @@ -129,12 +123,6 @@ protected NotificationListenerBase( } } - /** - Subclass should implement this routine. - */ - @Override - public abstract void handleNotification(final Notification notif, final Object handback); - protected synchronized void listenToMBean(final ObjectName objectName) throws InstanceNotFoundException, IOException { @@ -211,11 +199,7 @@ protected synchronized void listenToIfMatch(final ObjectName objectName) tracks coming and going of MBeans being listened to which match our patterns. */ - private final class RegistrationListener implements NotificationListener - { - public RegistrationListener() - { - } + private final class RegistrationListener implements NotificationListener { @Override public void handleNotification( @@ -344,9 +328,3 @@ public boolean isAlive() } } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerTracking.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerTracking.java index ef0278028c5..22ee186f497 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerTracking.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationListenerTracking.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -49,46 +50,31 @@ /** */ -public class NotificationListenerTracking -{ +public class NotificationListenerTracking { // NotificationListeners are not unique, so we can't use a Map private final List mInfos; - public NotificationListenerTracking(boolean synchronize) - { - final List infos = - new ArrayList(); + public NotificationListenerTracking(boolean synchronize) { + final List infos = new ArrayList(); mInfos = synchronize ? Collections.synchronizedList(infos) : infos; } - public void addNotificationListener( - NotificationListener listener, - NotificationFilter filter, - Object handback) - { - final NotificationListenerInfo info = - new NotificationListenerInfo(listener, filter, handback); + public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) { + final NotificationListenerInfo info = new NotificationListenerInfo(listener, filter, handback); mInfos.add(info); } - public int getListenerCount() - { + public int getListenerCount() { return mInfos.size(); } - private final boolean listenersEqual( - final NotificationListener listener1, - final NotificationListener listener2) - { + private boolean listenersEqual(final NotificationListener listener1, final NotificationListener listener2) { return (listener1 == listener2); } - private final boolean handbacksEqual( - final Object handback1, - final Object handback2) - { + private boolean handbacksEqual(final Object handback1, final Object handback2) { return (handback1 == handback2); } @@ -100,19 +86,15 @@ private final boolean handbacksEqual( @return list of NotificationListenerInfo */ - public List removeNotificationListener(final NotificationListener listener) - { + public List removeNotificationListener(final NotificationListener listener) { final Iterator iter = mInfos.iterator(); final List results = new ArrayList(); - while (iter.hasNext()) - { - final NotificationListenerInfo info = - (NotificationListenerInfo) iter.next(); + while (iter.hasNext()) { + final NotificationListenerInfo info = (NotificationListenerInfo) iter.next(); - if (listenersEqual(listener, info.getListener())) - { + if (listenersEqual(listener, info.getListener())) { iter.remove(); results.add(info); } @@ -129,22 +111,14 @@ public List removeNotificationListener(final Notificat @return list of NotificationListenerInfo */ - public NotificationListenerInfo removeNotificationListener( - final NotificationListener listener, - final NotificationFilter filter, - final Object handback) - { + public NotificationListenerInfo removeNotificationListener(final NotificationListener listener, final NotificationFilter filter, final Object handback) { final Iterator iter = mInfos.iterator(); NotificationListenerInfo result = null; - while (iter.hasNext()) - { - final NotificationListenerInfo info = - (NotificationListenerInfo) iter.next(); + while (iter.hasNext()) { + final NotificationListenerInfo info = (NotificationListenerInfo) iter.next(); - if (listenersEqual(listener, info.getListener()) && - handbacksEqual(handback, info.getHandback())) - { + if (listenersEqual(listener, info.getListener()) && handbacksEqual(handback, info.getHandback())) { iter.remove(); result = info; break; @@ -155,27 +129,3 @@ public NotificationListenerInfo removeNotificationListener( } } - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationSender.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationSender.java index 2acce0bdc9b..7c9aaa2fadc 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationSender.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/NotificationSender.java @@ -49,8 +49,3 @@ public interface NotificationSender public void sendNotification(final Notification notif); } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQuery.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQuery.java index f1cdc8d842d..c13a3c16f67 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQuery.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQuery.java @@ -87,9 +87,3 @@ public interface ObjectNameQuery Set matchAny(Set startingSet, String[] regexNames, String[] regexValues); } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQueryImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQueryImpl.java index e360806862b..b0a7612aa2f 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQueryImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ObjectNameQueryImpl.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -49,11 +50,7 @@ import java.util.Set; import java.util.regex.Pattern; -public class ObjectNameQueryImpl implements ObjectNameQuery -{ - public ObjectNameQueryImpl() - { - } +public class ObjectNameQueryImpl implements ObjectNameQuery { /** Return true if one (or more) of the properties match the regular expressions @@ -149,14 +146,11 @@ boolean matchAny(ObjectName name, return (matches); } - Pattern[] createPatterns(final String[] patternStrings, int numItems) - { + Pattern[] createPatterns(final String[] patternStrings, int numItems) { final Pattern[] patterns = new Pattern[numItems]; - if (patternStrings == null) - { - for (int i = 0; i < numItems; ++i) - { + if (patternStrings == null) { + for (int i = 0; i < numItems; ++i) { patterns[i] = null; } @@ -164,16 +158,12 @@ Pattern[] createPatterns(final String[] patternStrings, int numItems) } - for (int i = 0; i < numItems; ++i) - { + for (int i = 0; i < numItems; ++i) { // consider null to match anything - if (patternStrings[i] == null) - { + if (patternStrings[i] == null) { patterns[i] = null; - } - else - { + } else { patterns[i] = Pattern.compile(patternStrings[i]); } } @@ -181,18 +171,13 @@ Pattern[] createPatterns(final String[] patternStrings, int numItems) return (patterns); } - private interface Matcher - { + private interface Matcher { boolean match(ObjectName name, Pattern[] names, Pattern[] values); - } - private class MatchAnyMatcher implements Matcher - { - public MatchAnyMatcher() - { - } + private class MatchAnyMatcher implements Matcher { + @Override public boolean match(ObjectName name, Pattern[] names, Pattern[] values) { return (matchAny(name, names, values)); @@ -200,27 +185,17 @@ public boolean match(ObjectName name, Pattern[] names, Pattern[] values) } - private class MatchAllMatcher implements Matcher - { - public MatchAllMatcher() - { - } + private class MatchAllMatcher implements Matcher { - public boolean match(ObjectName name, Pattern[] names, Pattern[] values) - { + @Override + public boolean match(ObjectName name, Pattern[] names, Pattern[] values) { return (matchAll(name, names, values)); } } - Set matchEither( - Matcher matcher, - Set startingSet, - String[] regexNames, - String[] regexValues) - { - if (regexNames == null && regexValues == null) - { + Set matchEither(Matcher matcher, Set startingSet, String[] regexNames, String[] regexValues) { + if (regexNames == null && regexValues == null) { // both null => matches entire original set return (startingSet); } @@ -228,22 +203,17 @@ Set matchEither( final Set results = new HashSet(); int numMatches = 0; - if (regexNames != null) - { + if (regexNames != null) { numMatches = regexNames.length; - } - else - { + } else { numMatches = regexValues.length; } final Pattern[] namePatterns = createPatterns(regexNames, numMatches); final Pattern[] valuePatterns = createPatterns(regexValues, numMatches); - for (final ObjectName name : startingSet) - { - if (matcher.match(name, namePatterns, valuePatterns)) - { + for (final ObjectName name : startingSet) { + if (matcher.match(name, namePatterns, valuePatterns)) { results.add(name); } } @@ -251,20 +221,16 @@ Set matchEither( return (results); } + @Override public Set matchAll(Set startingSet, String[] regexNames, String[] regexValues) { return (matchEither(new MatchAllMatcher(), startingSet, regexNames, regexValues)); } + @Override public Set matchAny(Set startingSet, String[] regexNames, String[] regexValues) { return (matchEither(new MatchAnyMatcher(), startingSet, regexNames, regexValues)); } } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/OpenMBeanUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/OpenMBeanUtil.java index 5e7e4935961..e46e050968d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/OpenMBeanUtil.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/OpenMBeanUtil.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; @@ -107,18 +108,13 @@ private static Map, SimpleType> getSimpleTypesMap() /** Get the SimpleType for a class which can be so-represented. */ - static public SimpleType getSimpleType(final Class c) - { + public static SimpleType getSimpleType(final Class c) { final SimpleType type = getSimpleTypesMap().get(c); return (type); } - private static final String[] EMPTY_STRING_ARRAY = new String[0]; - - private static final OpenType[] EMPTY_OPENTYPES = new OpenType[0]; - /** Get any non-null array element from the array. */ @@ -185,11 +181,8 @@ public static ArrayType newArrayType(final int numItems, final OpenType type) /** Get the OpenType of an Object, which must conform to OpenType requirements. */ - static public OpenType getOpenType(final Object o) - throws InvalidOpenTypeException, OpenDataException - { - if (o == null) - { + public static OpenType getOpenType(final Object o) throws InvalidOpenTypeException, OpenDataException { + if (o == null) { // no OpenType for a null throw new IllegalArgumentException(); } @@ -299,32 +292,23 @@ public static Map convertTypes(final Map map, - CompositeTypeFromNameCallback callback) - throws OpenDataException - { + public static CompositeType mapToCompositeType(final String typeName, final String description, final Map map, + CompositeTypeFromNameCallback callback) throws OpenDataException { final String[] itemNames = new String[map.keySet().size()]; map.keySet().toArray(itemNames); final String[] itemDescriptions = new String[itemNames.length]; final OpenType[] itemTypes = new OpenType[itemNames.length]; - for (int i = 0; i < itemNames.length; ++i) - { + for (int i = 0; i < itemNames.length; ++i) { final String name = itemNames[i]; final Object value = map.get(name); itemDescriptions[i] = "value " + name; - if (value == null) - { + if (value == null) { // force nulls to type String itemTypes[i] = callback.getOpenTypeFromName(name); - } - else - { + } else { itemTypes[i] = getOpenType(value); } } @@ -433,9 +417,9 @@ public static OpenType getThrowableOpenType(final Throwable t) final OpenType[] openTypes = new OpenType[itemNames.length]; - openTypes[ 0] = SimpleType.STRING; - openTypes[ 1] = t.getCause() == null ? SimpleType.VOID : getThrowableOpenType(t.getCause()); - openTypes[ 2] = newArrayType(t.getStackTrace().length, + openTypes[0] = SimpleType.STRING; + openTypes[1] = t.getCause() == null ? SimpleType.VOID : getThrowableOpenType(t.getCause()); + openTypes[2] = newArrayType(t.getStackTrace().length, getStackTraceElementOpenType()); @@ -448,9 +432,3 @@ public static OpenType getThrowableOpenType(final Throwable t) } } - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ReadWriteAttributeFilter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ReadWriteAttributeFilter.java index 2d8747ec840..25ffcee45b9 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ReadWriteAttributeFilter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/ReadWriteAttributeFilter.java @@ -37,83 +37,67 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx; import javax.management.MBeanAttributeInfo; /** - This class contains various filters based on read/write status of - an Attribute. + * This class contains various filters based on read/write status of an Attribute. */ -public class ReadWriteAttributeFilter implements AttributeFilter -{ - protected ReadWriteAttributeFilter( ) {} - - /** - */ - public boolean - filterAttribute( final MBeanAttributeInfo info ) - { - throw new RuntimeException( "Can't get here" ); - } - - public static final ReadWriteAttributeFilter READ_ONLY_FILTER = new ReadWriteAttributeFilter( ) - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( info.isReadable() && ! info.isWritable() ); - } - }; - - public static final ReadWriteAttributeFilter READABLE_FILTER = - new ReadWriteAttributeFilter( ) - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( info.isReadable() ); - } - }; - - public static final ReadWriteAttributeFilter WRITE_ONLY_FILTER = - new ReadWriteAttributeFilter() - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( info.isWritable() && ! info.isReadable() ); - } - }; - - public static final ReadWriteAttributeFilter WRITEABLE_FILTER = - new ReadWriteAttributeFilter() - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( info.isWritable() ); - } - }; - - public static final ReadWriteAttributeFilter READ_WRITE_FILTER = - new ReadWriteAttributeFilter() - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( info.isWritable() && info.isReadable() ); - } - }; - - public static final ReadWriteAttributeFilter ALL_FILTER = - new ReadWriteAttributeFilter() - { - public boolean filterAttribute( final MBeanAttributeInfo info ) - { - return( true ); - } - }; -} +public class ReadWriteAttributeFilter implements AttributeFilter { + + protected ReadWriteAttributeFilter() { + } + /** + */ + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + throw new RuntimeException("Can't get here"); + } + public static final ReadWriteAttributeFilter READ_ONLY_FILTER = new ReadWriteAttributeFilter() { + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (info.isReadable() && !info.isWritable()); + } + }; + public static final ReadWriteAttributeFilter READABLE_FILTER = new ReadWriteAttributeFilter() { + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (info.isReadable()); + } + }; + public static final ReadWriteAttributeFilter WRITE_ONLY_FILTER = new ReadWriteAttributeFilter() { + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (info.isWritable() && !info.isReadable()); + } + }; + public static final ReadWriteAttributeFilter WRITEABLE_FILTER = new ReadWriteAttributeFilter() { + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (info.isWritable()); + } + }; + public static final ReadWriteAttributeFilter READ_WRITE_FILTER = new ReadWriteAttributeFilter() { + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (info.isWritable() && info.isReadable()); + } + }; + + public static final ReadWriteAttributeFilter ALL_FILTER = new ReadWriteAttributeFilter() { + + @Override + public boolean filterAttribute(final MBeanAttributeInfo info) { + return (true); + } + }; +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeChangeNotificationStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeChangeNotificationStringifier.java index 01693d0c768..0b73ff766cf 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeChangeNotificationStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeChangeNotificationStringifier.java @@ -37,31 +37,31 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; import javax.management.AttributeChangeNotification; import org.glassfish.admin.amx.util.stringifier.SmartStringifier; -public class AttributeChangeNotificationStringifier - extends NotificationStringifier -{ - public static final AttributeChangeNotificationStringifier DEFAULT = - new AttributeChangeNotificationStringifier(); +/** + * Creates a String representation of an {@link AttributeChangeNotification} + * @see Object#toString() + */ +public class AttributeChangeNotificationStringifier extends NotificationStringifier { + + public static final AttributeChangeNotificationStringifier DEFAULT = new AttributeChangeNotificationStringifier(); - public AttributeChangeNotificationStringifier() - { + public AttributeChangeNotificationStringifier() { super(); } - public AttributeChangeNotificationStringifier(Options options) - { + public AttributeChangeNotificationStringifier(Options options) { super(options); } - public String stringify(Object o) - { + @Override + public String stringify(Object o) { final AttributeChangeNotification notif = (AttributeChangeNotification) o; final StringBuilder b = super._stringify(notif); @@ -77,22 +77,3 @@ public String stringify(Object o) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeListStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeListStringifier.java index 211c46a0e98..026c0acfb93 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeListStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeListStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx.stringifier; @@ -46,11 +47,15 @@ import javax.management.AttributeList; import java.util.Iterator; +/** + * Creates a String representation of an {@link AttributeList} + * @see Object#toString() + */ public final class AttributeListStringifier implements Stringifier { final String mDelim; - public final static AttributeListStringifier DEFAULT = new AttributeListStringifier(); + public static final AttributeListStringifier DEFAULT = new AttributeListStringifier(); public AttributeListStringifier() { @@ -63,8 +68,8 @@ public AttributeListStringifier(String delim) } - public String stringify(Object o) - { + @Override + public String stringify(Object o) { final AttributeList attrList = (AttributeList) o; final Iterator iter = attrList.iterator(); diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeStringifier.java index 64c28effc2b..655352ee72a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/AttributeStringifier.java @@ -37,13 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates -/* - * $Header: /cvs/glassfish/appserv-api/src/java/com/sun/appserv/management/util/jmx/stringifier/AttributeStringifier.java,v 1.2 2007/05/05 05:31:04 tcfujii Exp $ - * $Revision: 1.2 $ - * $Date: 2007/05/05 05:31:04 $ - */ - package org.glassfish.admin.amx.util.jmx.stringifier; import org.glassfish.admin.amx.util.stringifier.SmartStringifier; @@ -51,25 +46,25 @@ import javax.management.Attribute; +/** + * Creates a String representation of an {@link Attribute} + * @see Object#toString() + * @since 2007/05/05 05:31:04 + * @version 1.2 + * @author tcfujii + */ +public final class AttributeStringifier implements Stringifier { + + public static final AttributeStringifier DEFAULT = new AttributeStringifier(); + + @Override + public String stringify(Object o) { + final Attribute attr = (Attribute) o; + + final String prefix = attr.getName() + "="; + final String stringValue = SmartStringifier.toString(attr.getValue()); -public final class AttributeStringifier implements Stringifier -{ - public final static AttributeStringifier DEFAULT = new AttributeStringifier(); - - public - AttributeStringifier() - { - } - public String - stringify( Object o ) - { - final Attribute attr = (Attribute)o; - - final String prefix = attr.getName() + "="; - - final String stringValue = SmartStringifier.toString( attr.getValue() ); - - return( prefix + stringValue ); - } + return (prefix + stringValue); + } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/CompositeDataStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/CompositeDataStringifier.java index 909633b103b..1adde9e4926 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/CompositeDataStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/CompositeDataStringifier.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -48,14 +48,14 @@ import javax.management.openmbean.CompositeType; import java.util.Set; -public class CompositeDataStringifier implements Stringifier -{ +/** + * Creates a String representation of an {@link CompositeData} + * @see Object#toString() + */ +public class CompositeDataStringifier implements Stringifier { public static final CompositeDataStringifier DEFAULT = new CompositeDataStringifier(); - public CompositeDataStringifier() - { - } - + @Override public String stringify(Object o) { final StringBuilder buf = new StringBuilder(); @@ -77,22 +77,3 @@ public String stringify(Object o) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanAttributeInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanAttributeInfoStringifier.java index 80291598f26..1f85ebbac69 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanAttributeInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanAttributeInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx.stringifier; @@ -44,10 +45,13 @@ import javax.management.MBeanAttributeInfo; +/** + * Creates a String representation of an {@link MBeanAttributeInfo} + * @see Object#toString() + */ public class MBeanAttributeInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { - public final static MBeanAttributeInfoStringifier DEFAULT = - new MBeanAttributeInfoStringifier(); + public static final MBeanAttributeInfoStringifier DEFAULT = new MBeanAttributeInfoStringifier(); public MBeanAttributeInfoStringifier() { @@ -59,6 +63,7 @@ public MBeanAttributeInfoStringifier(MBeanFeatureInfoStringifierOptions options) super(options); } + @Override public String stringify(Object o) { MBeanAttributeInfo attr = (MBeanAttributeInfo) o; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanConstructorInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanConstructorInfoStringifier.java index 07dbee5c7c5..cb506e864f7 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanConstructorInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanConstructorInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -44,10 +45,12 @@ import javax.management.MBeanConstructorInfo; -public class MBeanConstructorInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier -{ - public static final MBeanConstructorInfoStringifier DEFAULT = - new MBeanConstructorInfoStringifier(); +/** + * Creates a String representation of an {@link MBeanConstructorInfo} + * @see Object#toString() + */ +public class MBeanConstructorInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { + public static final MBeanConstructorInfoStringifier DEFAULT = new MBeanConstructorInfoStringifier(); public MBeanConstructorInfoStringifier() { @@ -59,6 +62,7 @@ public MBeanConstructorInfoStringifier(MBeanFeatureInfoStringifierOptions option super(options); } + @Override public String stringify(Object o) { final MBeanConstructorInfo constructor = (MBeanConstructorInfo) o; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanFeatureInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanFeatureInfoStringifier.java index 89c855bb08b..3e3ef62815a 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanFeatureInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanFeatureInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -45,14 +46,12 @@ import org.glassfish.admin.amx.util.ClassUtil; import org.glassfish.admin.amx.util.stringifier.ArrayStringifier; -public class MBeanFeatureInfoStringifier -{ +public class MBeanFeatureInfoStringifier { final MBeanFeatureInfoStringifierOptions mOptions; - public static final MBeanFeatureInfoStringifierOptions DEFAULT = - new MBeanFeatureInfoStringifierOptions(true, ","); + public static final MBeanFeatureInfoStringifierOptions DEFAULT = new MBeanFeatureInfoStringifierOptions(true, ","); - static final String sOperationDelimiter = ","; + static final String OPERATION_DELIMITER = ","; MBeanFeatureInfoStringifier() { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanInfoStringifier.java index 33483022dd8..235db793d49 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx.stringifier; @@ -49,6 +50,10 @@ import javax.management.MBeanNotificationInfo; import javax.management.MBeanOperationInfo; +/** + * Creates a String representation of an {@link MBeanInfo} + * @see Object#toString() + */ public class MBeanInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { public static final MBeanInfoStringifier DEFAULT = new MBeanInfoStringifier(); @@ -98,9 +103,9 @@ MBeanNotificationInfoStringifier getMBeanNotificationInfoStringifier(MBeanFeatur return (new MBeanNotificationInfoStringifier(options)); } + @Override public String stringify(Object o) { - String result = ""; final MBeanInfo info = (MBeanInfo) o; final MBeanOperationInfo[] operations = info.getOperations(); @@ -109,7 +114,7 @@ public String stringify(Object o) final MBeanNotificationInfo[] notifications = info.getNotifications(); final String description = info.getDescription(); - result = "Summary: " + + String result = "Summary: " + operations.length + " operations, " + attributes.length + " attributes, " + constructors.length + " constructors, " + @@ -138,8 +143,3 @@ public String stringify(Object o) } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanNotificationInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanNotificationInfoStringifier.java index cd319dc9037..47e63c5e2be 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanNotificationInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanNotificationInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx.stringifier; @@ -45,9 +46,12 @@ import javax.management.MBeanNotificationInfo; -public class MBeanNotificationInfoStringifier - extends MBeanFeatureInfoStringifier implements Stringifier -{ +/** + * Creates a String representation of an {@link MBeanNotificationInfo} + * @see Object#toString() + */ +public class MBeanNotificationInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { + public final static MBeanNotificationInfoStringifier DEFAULT = new MBeanNotificationInfoStringifier(); public MBeanNotificationInfoStringifier() @@ -65,6 +69,7 @@ public static String toString( final MBeanNotificationInfo info ) return DEFAULT.stringify(info); } + @Override public String stringify(Object o) { final MBeanNotificationInfo notif = (MBeanNotificationInfo) o; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanOperationInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanOperationInfoStringifier.java index 532671e4c43..9baa80cf397 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanOperationInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanOperationInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.jmx.stringifier; @@ -44,18 +45,18 @@ import javax.management.MBeanOperationInfo; -public class MBeanOperationInfoStringifier - extends MBeanFeatureInfoStringifier implements Stringifier -{ +/** + * Creates a String representation of an {@link MBeanOperationInfo} + * @see Object#toString() + */ +public class MBeanOperationInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { public static final MBeanOperationInfoStringifier DEFAULT = new MBeanOperationInfoStringifier(); - public MBeanOperationInfoStringifier() - { + public MBeanOperationInfoStringifier() { super(); } - public MBeanOperationInfoStringifier(MBeanFeatureInfoStringifierOptions options) - { + public MBeanOperationInfoStringifier(MBeanFeatureInfoStringifierOptions options) { super(options); } @@ -94,9 +95,10 @@ public static String getSignature(MBeanOperationInfo info, MBeanFeatureInfoStrin public static String getDescription(MBeanOperationInfo info) { - return (sOperationDelimiter + "\"" + info.getDescription() + "\""); + return (OPERATION_DELIMITER + "\"" + info.getDescription() + "\""); } + @Override public String stringify(Object o) { assert (o != null); @@ -109,7 +111,7 @@ public String stringify(Object o) String impactStr = getImpact(op); - result = result + sOperationDelimiter + "impact=" + impactStr; + result = result + OPERATION_DELIMITER + "impact=" + impactStr; if (mOptions.mIncludeDescription) { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanParameterInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanParameterInfoStringifier.java index ed2ed61c5fe..34a365f4e06 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanParameterInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanParameterInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -44,11 +45,13 @@ import javax.management.MBeanParameterInfo; -public final class MBeanParameterInfoStringifier - extends MBeanFeatureInfoStringifier implements Stringifier -{ - public static final MBeanParameterInfoStringifier DEFAULT = - new MBeanParameterInfoStringifier(); +/** + * Creates a String representation of an {@link MBeanParameterInfo} + * @see Object#toString() + */ +public final class MBeanParameterInfoStringifier extends MBeanFeatureInfoStringifier implements Stringifier { + + public static final MBeanParameterInfoStringifier DEFAULT = new MBeanParameterInfoStringifier(); public MBeanParameterInfoStringifier() { @@ -60,6 +63,7 @@ public MBeanParameterInfoStringifier(MBeanFeatureInfoStringifierOptions options) super(options); } + @Override public String stringify(Object o) { final MBeanParameterInfo info = (MBeanParameterInfo) o; diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanServerNotificationStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanServerNotificationStringifier.java index 02ca68df736..79e91bd1e0d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanServerNotificationStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MBeanServerNotificationStringifier.java @@ -37,17 +37,18 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; import javax.management.MBeanServerNotification; -public class MBeanServerNotificationStringifier - extends NotificationStringifier -{ - public static final MBeanServerNotificationStringifier DEFAULT = - new MBeanServerNotificationStringifier(); +/** + * Creates a String representation of an {@link MBeanServerNotification} + * @see Object#toString() + */ +public class MBeanServerNotificationStringifier extends NotificationStringifier { + public static final MBeanServerNotificationStringifier DEFAULT = new MBeanServerNotificationStringifier(); public MBeanServerNotificationStringifier() { @@ -73,22 +74,3 @@ public String stringify(Object o) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanAttributeInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanAttributeInfoStringifier.java index cc6cf998523..7a5d5d8bcff 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanAttributeInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanAttributeInfoStringifier.java @@ -37,19 +37,18 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] -/* - * $Header: /cvs/glassfish/appserv-api/src/java/com/sun/appserv/management/util/jmx/stringifier/ModelMBeanAttributeInfoStringifier.java,v 1.2 2007/05/05 05:31:05 tcfujii Exp $ - * $Revision: 1.2 $ - * $Date: 2007/05/05 05:31:05 $ - */ package org.glassfish.admin.amx.util.jmx.stringifier; -public class ModelMBeanAttributeInfoStringifier - extends MBeanAttributeInfoStringifier -{ - public final static ModelMBeanAttributeInfoStringifier DEFAULT = - new ModelMBeanAttributeInfoStringifier(); +/** + * Creates a String representation of an {@link MBeanAttributeInfo} + * @author tcfujii + * @since 2007/05/05 + * @version 1.2 + */ +public class ModelMBeanAttributeInfoStringifier extends MBeanAttributeInfoStringifier { + public static final ModelMBeanAttributeInfoStringifier DEFAULT = new ModelMBeanAttributeInfoStringifier(); public ModelMBeanAttributeInfoStringifier() { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanInfoStringifier.java index 70b01ff8f7b..6482d5e120b 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanInfoStringifier.java @@ -83,8 +83,3 @@ MBeanNotificationInfoStringifier getMBeanNotificationInfoStringifier(MBeanFeatur } } - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanNotificationInfoStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanNotificationInfoStringifier.java index 996af2b868b..140cb6c0339 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanNotificationInfoStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ModelMBeanNotificationInfoStringifier.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] /* * $Header: /cvs/glassfish/appserv-api/src/java/com/sun/appserv/management/util/jmx/stringifier/ModelMBeanNotificationInfoStringifier.java,v 1.2 2007/05/05 05:31:05 tcfujii Exp $ @@ -45,10 +46,14 @@ */ package org.glassfish.admin.amx.util.jmx.stringifier; -public final class ModelMBeanNotificationInfoStringifier - extends MBeanNotificationInfoStringifier -{ - public final static MBeanNotificationInfoStringifier DEFAULT = new MBeanNotificationInfoStringifier(); +/** + * Creates a String representation of an {@link MBeanNotificationInfo} + * @author tcfujii + * @since 2007/05/05 + * @version 1.2 + */ +public final class ModelMBeanNotificationInfoStringifier extends MBeanNotificationInfoStringifier { + public static final MBeanNotificationInfoStringifier DEFAULT = new MBeanNotificationInfoStringifier(); public ModelMBeanNotificationInfoStringifier() { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MonitorNotificationStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MonitorNotificationStringifier.java index 55bcbc5cf6c..9d13527f8c0 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MonitorNotificationStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/MonitorNotificationStringifier.java @@ -37,16 +37,18 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; import javax.management.monitor.MonitorNotification; -public class MonitorNotificationStringifier extends NotificationStringifier -{ - public static final MonitorNotificationStringifier DEFAULT = - new MonitorNotificationStringifier(); +/** + * Creates a String representation of an {@link MonitorNotification} + * @see Object#toString() + */ +public class MonitorNotificationStringifier extends NotificationStringifier { + public static final MonitorNotificationStringifier DEFAULT = new MonitorNotificationStringifier(); public MonitorNotificationStringifier() { @@ -75,22 +77,3 @@ public String stringify(Object o) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/NotificationStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/NotificationStringifier.java index b0c80ed6020..d378c0c40ec 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/NotificationStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/NotificationStringifier.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -49,13 +49,16 @@ import javax.management.Notification; import java.util.Date; -public class NotificationStringifier implements Stringifier -{ +/** + * Creates a String representation of an {@link Notification} + * @see Object#toString() + */ +public class NotificationStringifier implements Stringifier { public static final NotificationStringifier DEFAULT = new NotificationStringifier(); protected Options mOptions; - public final static class Options + public static final class Options { // don't make 'final' fields; allow changes after instantiation public boolean mIncludeObjectName; @@ -102,8 +105,8 @@ protected void append(StringBuilder b, Object o) b.append(SmartStringifier.toString(o)); } - public String stringify(Object o) - { + @Override + public String stringify(Object o) { final Notification notif = (Notification) o; return (_stringify(notif).toString()); @@ -155,22 +158,3 @@ protected StringBuilder _stringify(Notification notif) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ObjectNameStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ObjectNameStringifier.java index 3dc14aa0802..05fc536b169 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ObjectNameStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/ObjectNameStringifier.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -56,16 +56,15 @@ import java.util.Set; /** -Stringifier for an ObjectName which sorts the properties in the ObjectName -for more consistent and readable output. + * Stringifier for an {@link ObjectName} which sorts the properties in the ObjectName + * for more consistent and readable output. */ -public final class ObjectNameStringifier implements Stringifier -{ - public final static ObjectNameStringifier DEFAULT = new ObjectNameStringifier(); +public final class ObjectNameStringifier implements Stringifier { + public static final ObjectNameStringifier DEFAULT = new ObjectNameStringifier(); private static List PROPS = null; - private synchronized static List getPROPS() + private static synchronized List getPROPS() { if (PROPS == null) { @@ -127,9 +126,9 @@ private String makeProp(final String name, final String value) { return (name + "=" + value); } - - public String stringify(Object o) - { + + @Override + public String stringify(Object o) { if (o == null) { return ("null"); @@ -199,27 +198,3 @@ public void setOmitDomain(final boolean omit) } } - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/StringifierRegistryIniter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/StringifierRegistryIniter.java index 5fcdefb2e7a..df20b2dc871 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/StringifierRegistryIniter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/StringifierRegistryIniter.java @@ -95,6 +95,3 @@ public StringifierRegistryIniter(StringifierRegistry registry) } } - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/TabularDataStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/TabularDataStringifier.java index a70802c63a3..e9c3331f7b2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/TabularDataStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/stringifier/TabularDataStringifier.java @@ -37,7 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.jmx.stringifier; @@ -45,14 +45,13 @@ import javax.management.openmbean.TabularData; import org.glassfish.admin.amx.util.stringifier.Stringifier; -public class TabularDataStringifier implements Stringifier -{ +/** + * Creates a String representation of an {@link TabularData} + * @see Object#toString() + */ +public class TabularDataStringifier implements Stringifier { public static final TabularDataStringifier DEFAULT = new TabularDataStringifier(); - public TabularDataStringifier() - { - } - @Override public String stringify(Object o) { @@ -78,22 +77,3 @@ public String stringify(Object o) } } - - - - - - - - - - - - - - - - - - - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ArrayStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ArrayStringifier.java index 0a99295027c..dca5f75af98 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ArrayStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ArrayStringifier.java @@ -37,111 +37,90 @@ * only if the new code is made subject to such option by the copyright * holder. */ - +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; import java.util.Arrays; import java.util.Iterator; /** - Stringifies an array, using an optional array element Stringifier + * Stringifies an array, using an optional array element Stringifier */ - -public final class ArrayStringifier implements Stringifier -{ - final String mDelim; - final Stringifier mElementStringifier; - boolean mAddBraces; - - static final char LEFT_BRACE = '{'; - static final char RIGHT_BRACE = '}'; - static final String DEFAULT_DELIM=", "; - - public - ArrayStringifier() - { - this( SmartStringifier.DEFAULT ); - mAddBraces = false; - } - public - ArrayStringifier( boolean addBraces ) - { - this( DEFAULT_DELIM, SmartStringifier.DEFAULT, addBraces ); - } - - public - ArrayStringifier( String delim ) - { - this( delim, false ); - } - - public - ArrayStringifier( String delim, boolean addBraces) - { - this( delim, SmartStringifier.DEFAULT, addBraces ); - } - - public - ArrayStringifier( Stringifier elementStringifier ) - { - this( DEFAULT_DELIM, elementStringifier ); - } - - public - ArrayStringifier( String delim, Stringifier elementStringifier ) - { - this( delim, elementStringifier, false ); - } - - public - ArrayStringifier( String delim, Stringifier elementStringifier, boolean addBraces) - { - mDelim = delim; - mElementStringifier = elementStringifier; - mAddBraces = addBraces; - } - - static String - addBraces( boolean add, String s ) - { - String out = s; - if ( add ) - { - out = LEFT_BRACE + s + RIGHT_BRACE; - } - return( out ); - } - - public String - stringify( Object o ) - { - final String s = this.stringify( (Object [])o, mDelim, mElementStringifier ); - - return( addBraces( mAddBraces, s ) ); - } - - /** - Static variant when direct call will suffice. - */ - public static String - stringify( Object [] o, String delim, Stringifier stringifier ) - { - final Iterator iter = Arrays.asList( o ).iterator(); - final IteratorStringifier iterStringifier = new IteratorStringifier( delim, stringifier ); - - final String s = iterStringifier.stringify( iter ); - return( s ); - } - - /** - Static variant when direct call will suffice. - */ - public static String - stringify( Object [] o, String delim ) - { - return( stringify( o, delim, SmartStringifier.DEFAULT ) ); - } - - public final static ArrayStringifier DEFAULT = new ArrayStringifier( "," ); -} +public final class ArrayStringifier implements Stringifier { + + final String mDelim; + final Stringifier mElementStringifier; + boolean mAddBraces; + + static final char LEFT_BRACE = '{'; + static final char RIGHT_BRACE = '}'; + static final String DEFAULT_DELIM = ", "; + + public static final ArrayStringifier DEFAULT = new ArrayStringifier(","); + + public ArrayStringifier() { + this(SmartStringifier.DEFAULT); + mAddBraces = false; + } + + public ArrayStringifier(boolean addBraces) { + this(DEFAULT_DELIM, SmartStringifier.DEFAULT, addBraces); + } + + public ArrayStringifier(String delim) { + this(delim, false); + } + + public ArrayStringifier(String delim, boolean addBraces) { + this(delim, SmartStringifier.DEFAULT, addBraces); + } + + public ArrayStringifier(Stringifier elementStringifier) { + this(DEFAULT_DELIM, elementStringifier); + } + public ArrayStringifier(String delim, Stringifier elementStringifier) { + this(delim, elementStringifier, false); + } + + public ArrayStringifier(String delim, Stringifier elementStringifier, boolean addBraces) { + mDelim = delim; + mElementStringifier = elementStringifier; + mAddBraces = addBraces; + } + + static String + addBraces(boolean add, String s) { + String out = s; + if (add) { + out = LEFT_BRACE + s + RIGHT_BRACE; + } + return (out); + } + + @Override + public String stringify(Object o) { + final String s = this.stringify((Object[]) o, mDelim, mElementStringifier); + + return (addBraces(mAddBraces, s)); + } + + /** + * Static variant when direct call will suffice. + */ + public static String stringify(Object[] o, String delim, Stringifier stringifier) { + final Iterator iter = Arrays.asList(o).iterator(); + final IteratorStringifier iterStringifier = new IteratorStringifier(delim, stringifier); + + final String s = iterStringifier.stringify(iter); + return (s); + } + + /** + * Static variant when direct call will suffice. + */ + public static String stringify(Object[] o, String delim) { + return (stringify(o, delim, SmartStringifier.DEFAULT)); + } + +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ClassNameStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ClassNameStringifier.java index 442eecdc81e..c7764f9a679 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ClassNameStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ClassNameStringifier.java @@ -37,18 +37,17 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; import org.glassfish.admin.amx.util.ClassUtil; -public class ClassNameStringifier implements Stringifier -{ - public String - stringify( Object o ) - { - final String className = (String)o; - - return( ClassUtil.getFriendlyClassname( className ) ); - } +public class ClassNameStringifier implements Stringifier { + @Override + public String stringify(Object o) { + final String className = (String) o; + + return (ClassUtil.getFriendlyClassname(className)); + } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/CollectionStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/CollectionStringifier.java index f0abbd2c7c1..9a0df9411b3 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/CollectionStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/CollectionStringifier.java @@ -37,58 +37,52 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; import java.util.Collection; import java.util.Iterator; -public class CollectionStringifier implements Stringifier -{ - public final static CollectionStringifier DEFAULT = new CollectionStringifier( "," ); - - public final String mDelim; - public final Stringifier mElementStringifier; - - public - CollectionStringifier( String delim ) - { - this( delim, SmartStringifier.DEFAULT ); - } - - public - CollectionStringifier( Stringifier elementStringifier ) - { - this( ",", elementStringifier ); - } - - public - CollectionStringifier( String delim, Stringifier elementStringifier ) - { - mDelim = delim; - mElementStringifier = elementStringifier; - } - - public String - stringify( Object o ) - { - final Collection c = (Collection)o; - final Iterator iter = c.iterator(); - - String result = IteratorStringifier.DEFAULT.stringify( iter, mDelim, mElementStringifier); - - return( result ); - } - +/** + * Creates a String representation of an {@link Collection} + * @see Object#toString() + */ +public class CollectionStringifier implements Stringifier { + public static final CollectionStringifier DEFAULT = new CollectionStringifier( "," ); - public static String - toString( final Object o, final String delim ) - { - final Collection c = (Collection)o; - final Iterator iter = c.iterator(); - - String result = IteratorStringifier.DEFAULT.stringify( iter, delim ); - - return( result ); - } + public final String mDelim; + public final Stringifier mElementStringifier; + + public CollectionStringifier(String delim) { + this(delim, SmartStringifier.DEFAULT); + } + + public CollectionStringifier(Stringifier elementStringifier) { + this(",", elementStringifier); + } + + public CollectionStringifier(String delim, Stringifier elementStringifier) { + mDelim = delim; + mElementStringifier = elementStringifier; + } + + @Override + public String stringify(Object o) { + final Collection c = (Collection) o; + final Iterator iter = c.iterator(); + + String result = IteratorStringifier.DEFAULT.stringify(iter, mDelim, mElementStringifier); + + return (result); + } + + public static String toString(final Object o, final String delim) { + final Collection c = (Collection) o; + final Iterator iter = c.iterator(); + + String result = IteratorStringifier.stringify(iter, delim); + + return (result); + } } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifier.java index c0ee582f24d..0cc768202d6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifier.java @@ -37,73 +37,52 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; import java.util.Iterator; - /** - Stringifies an Iterator, using an optional element Stringifier + * Stringifies an {@link Iterator}, using an optional element Stringifier */ +public final class IteratorStringifier extends IteratorStringifierBase { -public final class IteratorStringifier extends IteratorStringifierBase -{ - public - IteratorStringifier() - { - super(); - } - - public - IteratorStringifier( String delim ) - { - super( delim ); - } + public static final IteratorStringifier DEFAULT = new IteratorStringifier(","); + + public IteratorStringifier() { + super(); + } - public - IteratorStringifier( Stringifier elementStringifier ) - { - super( elementStringifier ); - } + public IteratorStringifier(String delim) { + super(delim); + } - public - IteratorStringifier( String delim, Stringifier elementStringifier ) - { - super( delim, elementStringifier ); - } + public IteratorStringifier(Stringifier elementStringifier) { + super(elementStringifier); + } + public IteratorStringifier(String delim, Stringifier elementStringifier) { + super(delim, elementStringifier); + } - public void - stringifyElement( - Object elem, - String delim, - StringBuilder buf) - { - if ( elem == null ) - { - buf.append( "null" ); - } - else - { - buf.append( mElementStringifier.stringify( elem ) ); - } - } + @Override + public void stringifyElement(Object elem, String delim, StringBuilder buf) { + if (elem == null) { + buf.append("null"); + } else { + buf.append(mElementStringifier.stringify(elem)); + } + } - /* - Static variant when direct call will suffice. - */ - public static String - stringify( Iterator iter, String delim ) - { - final IteratorStringifier stringifier = new IteratorStringifier( delim ); + /* + * Static variant when direct call will suffice. + */ + public static String stringify(Iterator iter, String delim) { + final IteratorStringifier stringifier = new IteratorStringifier(delim); - return( stringifier.stringify( iter, delim, SmartStringifier.DEFAULT ) ); - } + return (stringifier.stringify(iter, delim, SmartStringifier.DEFAULT)); + } - - public final static IteratorStringifier DEFAULT = new IteratorStringifier( "," ); } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifierBase.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifierBase.java index e32b71d2e0d..2af7416c9e2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifierBase.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/IteratorStringifierBase.java @@ -37,95 +37,72 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] - +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; import java.util.Iterator; - /** - Stringifies an Iterator, using an optional element Stringifier. - - Must be subclassed to provide Stringification of an element. + * Stringifies an {@link Iterator}, using an optional element Stringifier. + * + * Must be subclassed to provide Stringification of an element. */ +public abstract class IteratorStringifierBase implements Stringifier { -public abstract class IteratorStringifierBase implements Stringifier -{ - public final String mDelim; - public final Stringifier mElementStringifier; - - public - IteratorStringifierBase() - { - this( ObjectStringifier.DEFAULT ); - } - - public - IteratorStringifierBase( String delim ) - { - this( delim, new SmartStringifier( delim ) ); - } - - public - IteratorStringifierBase( Stringifier elementStringifier ) - { - this( ",", elementStringifier ); - } - - public - IteratorStringifierBase( String delim, Stringifier elementStringifier ) - { - mDelim = delim; - mElementStringifier = elementStringifier; - } - - public String - stringify( Object o ) - { - assert( o != null ); - Iterator iter = (Iterator)o; - - return( this.stringify( iter, mDelim, mElementStringifier ) ); - } - - - /* - Subclass may choose to override this. - */ - protected abstract void - stringifyElement( - Object elem, - String delim, - StringBuilder buf); - - - - public String - stringify( Iterator iter, String delim, Stringifier stringifier ) - { - assert( iter != null ); - - StringBuilder buf = new StringBuilder(); - - while ( iter.hasNext() ) - { - final Object elem = iter.next(); - - stringifyElement( elem, delim, buf ); - buf.append( delim ); - } - - // strip trailing delimiter - final int length = buf.length(); - if ( length != 0 ) - { - buf.setLength( length - delim.length() ); - } - - return( buf.toString() ); - } - - public final static IteratorStringifier DEFAULT = new IteratorStringifier( "," ); -} + public static final IteratorStringifier DEFAULT = new IteratorStringifier(","); + + public final String mDelim; + public final Stringifier mElementStringifier; + + public IteratorStringifierBase() { + this(ObjectStringifier.DEFAULT); + } + + public IteratorStringifierBase(String delim) { + this(delim, new SmartStringifier(delim)); + } + + public IteratorStringifierBase(Stringifier elementStringifier) { + this(",", elementStringifier); + } + + public IteratorStringifierBase(String delim, Stringifier elementStringifier) { + mDelim = delim; + mElementStringifier = elementStringifier; + } + + @Override + public String stringify(Object o) { + assert (o != null); + Iterator iter = (Iterator) o; + return (this.stringify(iter, mDelim, mElementStringifier)); + } + + + /* + * Subclass may choose to override this. + */ + protected abstract void stringifyElement(Object elem, String delim, StringBuilder buf); + + public String stringify(Iterator iter, String delim, Stringifier stringifier) { + assert (iter != null); + + StringBuilder buf = new StringBuilder(); + + while (iter.hasNext()) { + final Object elem = iter.next(); + + stringifyElement(elem, delim, buf); + buf.append(delim); + } + + // strip trailing delimiter + final int length = buf.length(); + if (length != 0) { + buf.setLength(length - delim.length()); + } + + return (buf.toString()); + } +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ObjectStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ObjectStringifier.java index b55bb80222a..a44d6e846d6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ObjectStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ObjectStringifier.java @@ -37,20 +37,20 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; /** - Useful as a default Stringifier even though it does nothing more than - call toString(). + * Useful as a default Stringifier even though it does nothing more than + * call toString(). */ -public final class ObjectStringifier implements Stringifier -{ - public String - stringify( Object o ) - { - return( o.toString() ); - } - - public final static ObjectStringifier DEFAULT = new ObjectStringifier(); +public final class ObjectStringifier implements Stringifier { + + @Override + public String stringify(Object o) { + return (o.toString()); + } + + public final static ObjectStringifier DEFAULT = new ObjectStringifier(); } diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ProviderStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ProviderStringifier.java index 75d27d29c20..ef2a76eb7a6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ProviderStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/ProviderStringifier.java @@ -37,40 +37,31 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] +//Portions Copyright [2018] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; import java.security.Provider; /** - Stringifies a java.security.Provider. + * Stringifies a java.security.Provider. */ +public final class ProviderStringifier implements Stringifier { -public final class ProviderStringifier implements Stringifier -{ - public final static ProviderStringifier DEFAULT = new ProviderStringifier(); + public static final ProviderStringifier DEFAULT = new ProviderStringifier(); - public - ProviderStringifier() - { - } + @Override + public String stringify(Object object) { + final Provider provider = (Provider) object; + final StringBuilder buf = new StringBuilder(); - public String - stringify( Object object ) - { - final Provider provider = (Provider)object; + buf.append(provider.getInfo()); - final StringBuilder buf = new StringBuilder(); + for (Object o : provider.entrySet()) { + buf.append(o.toString()).append("\n"); + } - buf.append( provider.getInfo() ); - - for (Object o : provider.entrySet()) { - buf.append(o.toString()).append("\n"); - } - - return( buf.toString() ); - } + return (buf.toString()); + } } - diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/SmartStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/SmartStringifier.java index 5d6ef4f5d8c..23431222296 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/SmartStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/SmartStringifier.java @@ -37,6 +37,8 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates + package org.glassfish.admin.amx.util.stringifier; import java.util.Collection; @@ -77,7 +79,7 @@ public SmartStringifier(StringifierRegistry registry, String multiDelim, boolean public void setRegistry(StringifierRegistry registry) { mRegistry = registry; } - private final static Class[] STRINGIFIER_REGISTRY_LOOKUPS = { + private static final Class[] STRINGIFIER_REGISTRY_LOOKUPS = { Iterator.class, Collection.class, HashMap.class @@ -110,7 +112,7 @@ private Stringifier getStringifier(final Object target) { } if (stringifier == null) { - // see if there is a Stringifier for any superclass; + // see if there is a Stringifier for any superclass Class tempClass = targetClass; while (tempClass != Object.class) { stringifier = mRegistry.lookup(tempClass); diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistry.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistry.java index 8399cad1a69..e6be903e7fe 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistry.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistry.java @@ -37,35 +37,28 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; - - /** - A registry for mapping classes to Stringifiers + * A registry for mapping classes to Stringifiers */ -public interface StringifierRegistry -{ - /** - Add a mapping from a Class to a Stringifier - - @param theClass the Class to which the Stringifier should be associated - @param stringifier the Stringifier for the class - */ - public void - add( Class theClass, Stringifier stringifier ); - - - /** - Lookup a Stringifier from a Class. - - @param theClass the Class - @return the Stringifier, or null if not found - */ - public Stringifier - lookup( Class theClass ); -} - +public interface StringifierRegistry { + /** + * Add a mapping from a Class to a Stringifier + * + * @param theClass the Class to which the Stringifier should be associated + * @param stringifier the Stringifier for the class + */ + public void add(Class theClass, Stringifier stringifier); + /** + * Lookup a Stringifier from a Class. + * + * @param theClass the Class + * @return the Stringifier, or null if not found + */ + public Stringifier lookup(Class theClass); +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryImpl.java index 3876e2b41c2..6ca3081d4bc 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryImpl.java @@ -37,75 +37,60 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.util.stringifier; import java.util.HashMap; import java.util.Map; - - /** - Holds a lookup table for Stringifiers. Certain Stringifier classes - may use this registry to aid them in producing suitable output. + * Holds a lookup table for Stringifiers. Certain Stringifier classes may use this registry to aid them in producing suitable output. */ -public class StringifierRegistryImpl implements StringifierRegistry -{ - public static final StringifierRegistry DEFAULT = new StringifierRegistryImpl(); - - private final Map,Stringifier> mLookup; - private final StringifierRegistry mNextRegistry; - - /** - Create a new registry with no next registry. - */ - public - StringifierRegistryImpl() - { - this( null ); - } - - /** - Create a new registry which is chained to an existing registry. - - When lookup() is called, if it cannot be found in this registry, then - the chainee is used. - - @param registry the registry to use if this registry fails to find a Stringifier - */ - public - StringifierRegistryImpl( final StringifierRegistry registry ) - { - mLookup = new HashMap,Stringifier>(); - mNextRegistry = registry; - } - - public void - add( final Class theClass, final Stringifier stringifier ) - { - if ( lookup( theClass ) != null ) - { - throw new IllegalArgumentException( "Stringifier already registered for: " + theClass.getName() ); - } - - mLookup.remove( theClass ); - mLookup.put( theClass, stringifier ); - } - - - public Stringifier - lookup( final Class theClass ) - { - Stringifier stringifier = mLookup.get( theClass ); - - if ( stringifier == null && mNextRegistry != null ) - { - stringifier = mNextRegistry.lookup( theClass ); - } - - return( stringifier ); - } -} +public class StringifierRegistryImpl implements StringifierRegistry { + + public static final StringifierRegistry DEFAULT = new StringifierRegistryImpl(); + + private final Map, Stringifier> mLookup; + private final StringifierRegistry mNextRegistry; + /** + * Create a new registry with no next registry. + */ + public StringifierRegistryImpl() { + this(null); + } + /** + * Create a new registry which is chained to an existing registry. + * + * When lookup() is called, if it cannot be found in this registry, then the chainee is used. + * + * @param registry the registry to use if this registry fails to find a Stringifier + */ + public StringifierRegistryImpl(final StringifierRegistry registry) { + mLookup = new HashMap, Stringifier>(); + mNextRegistry = registry; + } + @Override + public void add(final Class theClass, final Stringifier stringifier) { + if (lookup(theClass) != null) { + throw new IllegalArgumentException("Stringifier already registered for: " + theClass.getName()); + } + + mLookup.remove(theClass); + mLookup.put(theClass, stringifier); + } + + @Override + public Stringifier lookup(final Class theClass) { + Stringifier stringifier = mLookup.get(theClass); + + if (stringifier == null && mNextRegistry != null) { + stringifier = mNextRegistry.lookup(theClass); + } + + return (stringifier); + } +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniter.java index 0a735950341..05bbb2deb6e 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniter.java @@ -37,24 +37,22 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; /** - Interface for adding a Stringifier. + * Interface for adding a Stringifier. */ -public interface StringifierRegistryIniter -{ - /** - Add a mapping from the class to its Stringifier - */ - public void add( Class theClass, Stringifier theStringifier ); - - /** - Get the registry in use by this Stringifier - */ - public StringifierRegistry getRegistry(); -} - +public interface StringifierRegistryIniter { + /** + * Add a mapping from the class to its Stringifier + */ + public void add(Class theClass, Stringifier theStringifier); + /** + * Get the registry in use by this Stringifier + */ + public StringifierRegistry getRegistry(); +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniterImpl.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniterImpl.java index fcfbe52ab19..cb4d162109e 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniterImpl.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/StringifierRegistryIniterImpl.java @@ -37,55 +37,44 @@ * only if the new code is made subject to such option by the copyright * holder. */ +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; import java.util.Collection; import java.util.Iterator; - /** - Registers all standard Stringifiers. + * Registers all standard Stringifiers. */ -public class StringifierRegistryIniterImpl implements StringifierRegistryIniter -{ - private final StringifierRegistry mRegistry; - - public - StringifierRegistryIniterImpl( StringifierRegistry registry ) - { - mRegistry = registry; - - registerTypes(); - } - - void - registerTypes() - { - if ( mRegistry.lookup( Iterator.class ) == null ) - { - add( Iterator.class, IteratorStringifier.DEFAULT ); - add( Collection.class, CollectionStringifier.DEFAULT ); - add( Object.class, SmartStringifier.DEFAULT ); - - add( java.security.Provider.class, ProviderStringifier.DEFAULT ); - } - } +public class StringifierRegistryIniterImpl implements StringifierRegistryIniter { - - public void - add( Class theClass, Stringifier theStringifier ) - { - mRegistry.add( theClass, theStringifier ); - } - - public StringifierRegistry - getRegistry() - { - return( mRegistry ); - } - -} + private final StringifierRegistry mRegistry; + + public StringifierRegistryIniterImpl(StringifierRegistry registry) { + mRegistry = registry; + + registerTypes(); + } + void registerTypes() { + if (mRegistry.lookup(Iterator.class) == null) { + add(Iterator.class, IteratorStringifier.DEFAULT); + add(Collection.class, CollectionStringifier.DEFAULT); + add(Object.class, SmartStringifier.DEFAULT); + add(java.security.Provider.class, ProviderStringifier.DEFAULT); + } + } + @Override + public void add(Class theClass, Stringifier theStringifier) { + mRegistry.add(theClass, theStringifier); + } + + @Override + public StringifierRegistry getRegistry() { + return (mRegistry); + } + +} diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/X509CertificateStringifier.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/X509CertificateStringifier.java index 6c7dd1fc7ae..ae6b0703bab 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/X509CertificateStringifier.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/stringifier/X509CertificateStringifier.java @@ -37,8 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ -//Portions Copyright [2018] [Payara Foundation] - +//Portions Copyright [2018-2019] [Payara Foundation and/or affiliates] package org.glassfish.admin.amx.util.stringifier; import com.sun.enterprise.security.auth.realm.certificate.CertificateRealm; @@ -49,76 +48,57 @@ import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; - /** - Stringifies an X509CertificateStringifier. + * Stringifies an {@link X509Certificate}. */ - -public final class X509CertificateStringifier implements Stringifier -{ - public final static X509CertificateStringifier DEFAULT = new X509CertificateStringifier(); - - public - X509CertificateStringifier() - { - } - - - private static byte[] - getFingerprint( byte[] signature, String alg ) - { - byte[] result = null; - - try - { - final MessageDigest md = MessageDigest.getInstance( alg ); - - result = md.digest( signature ); - } - catch ( NoSuchAlgorithmException e ) - { - result = signature; - e.printStackTrace(); - } - - return( result ); - } - - /** - Static variant when direct call will suffice. - */ - public static String - stringify( final X509Certificate cert ) - { - final StringBuilder buf = new StringBuilder(); - final String NL = "\n"; - - buf.append("Issuer: ").append(cert.getIssuerX500Principal() - .getName(X500Principal.RFC2253, CertificateRealm.OID_MAP)).append(NL); - buf.append("Issued to: ").append(cert.getSubjectX500Principal() - .getName(X500Principal.RFC2253, CertificateRealm.OID_MAP)).append(NL); - buf.append("Version: ").append(cert.getVersion()).append(NL); - buf.append("Not valid before: ").append(cert.getNotBefore()).append(NL); - buf.append("Not valid after: ").append(cert.getNotAfter()).append(NL); - buf.append("Serial number: ").append(cert.getSerialNumber()).append(NL); - buf.append("Signature algorithm: ").append(cert.getSigAlgName()).append(NL); - buf.append("Signature algorithm OID: ").append(cert.getSigAlgOID()).append(NL); - - buf.append( "Signature fingerprint (MD5): " ); - byte[] fingerprint = getFingerprint( cert.getSignature(), "MD5" ); - buf.append(StringUtil.toHexString(fingerprint, ":")).append(NL); - - buf.append( "Signature fingerprint (SHA1): " ); - fingerprint = getFingerprint( cert.getSignature(), "SHA1" ); - buf.append(StringUtil.toHexString(fingerprint, ":")).append(NL); - - return( buf.toString() ); - } - - public String - stringify( Object object ) - { - return( stringify( (X509Certificate)object ) ); - } +public final class X509CertificateStringifier implements Stringifier { + + public final static X509CertificateStringifier DEFAULT = new X509CertificateStringifier(); + + private static byte[] getFingerprint(byte[] signature, String alg) { + byte[] result = null; + + try { + final MessageDigest md = MessageDigest.getInstance(alg); + + result = md.digest(signature); + } catch (NoSuchAlgorithmException e) { + result = signature; + e.printStackTrace(); + } + + return (result); + } + + /** + * Static variant when direct call will suffice. + */ + public static String stringify(final X509Certificate cert) { + final StringBuilder buf = new StringBuilder(); + final String NL = "\n"; + + buf.append("Issuer: ").append(cert.getIssuerDN().getName()).append(NL); + buf.append("Issued to: ").append(cert.getSubjectDN().getName()).append(NL); + buf.append("Version: ").append(cert.getVersion()).append(NL); + buf.append("Not valid before: ").append(cert.getNotBefore()).append(NL); + buf.append("Not valid after: ").append(cert.getNotAfter()).append(NL); + buf.append("Serial number: ").append(cert.getSerialNumber()).append(NL); + buf.append("Signature algorithm: ").append(cert.getSigAlgName()).append(NL); + buf.append("Signature algorithm OID: ").append(cert.getSigAlgOID()).append(NL); + + buf.append("Signature fingerprint (MD5): "); + byte[] fingerprint = getFingerprint(cert.getSignature(), "MD5"); + buf.append(StringUtil.toHexString(fingerprint, ":")).append(NL); + + buf.append("Signature fingerprint (SHA1): "); + fingerprint = getFingerprint(cert.getSignature(), "SHA1"); + buf.append(StringUtil.toHexString(fingerprint, ":")).append(NL); + + return (buf.toString()); + } + + @Override + public String stringify(Object object) { + return (stringify((X509Certificate) object)); + } } - diff --git a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/AMXConfigTest.java b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/AMXConfigTest.java index 69dd301e9c7..44b58c73443 100644 --- a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/AMXConfigTest.java +++ b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/AMXConfigTest.java @@ -77,9 +77,3 @@ public void testDomConvertName() { _testConvertName( "IsConnectionValidationRequired", "is-connection-validation-required" ); } } - - - - - - diff --git a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/ObjectNamesTest.java b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/ObjectNamesTest.java index 7872d59acde..73ab669fa6e 100644 --- a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/ObjectNamesTest.java +++ b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/ObjectNamesTest.java @@ -37,6 +37,7 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.test; @@ -48,8 +49,7 @@ import java.lang.management.ManagementFactory; -public final class ObjectNamesTest extends TestBase -{ +public final class ObjectNamesTest extends TestBase { public ObjectNamesTest() { } @@ -59,6 +59,7 @@ private ObjectNameBuilder get() { } @Before + @Override public void setUp() { initBootUtil(); } @@ -78,9 +79,3 @@ public void testMisc() { get().getJMXDomain(); } } - - - - - - diff --git a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/SingletonEnforcerTest.java b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/SingletonEnforcerTest.java index 7fb9fc00c61..3309ab3d820 100644 --- a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/SingletonEnforcerTest.java +++ b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/SingletonEnforcerTest.java @@ -37,19 +37,16 @@ * only if the new code is made subject to such option by the copyright * holder. */ +// Portions Copyright [2019] Payara Foundation and/or affiliates package org.glassfish.admin.amx.test; import org.glassfish.admin.amx.impl.util.SingletonEnforcer; -import static org.junit.Assert.assertTrue; import org.junit.Test; -public final class SingletonEnforcerTest extends TestBase -{ - public SingletonEnforcerTest() { - } +public final class SingletonEnforcerTest extends TestBase { private static final class Dummy {} @@ -69,14 +66,6 @@ public void testVariety() { SingletonEnforcer.register( Integer.class, new Integer(0) ); assertNotNull( SingletonEnforcer.get( Integer.class ) ); } - - /* - @Test(expected=IllegalArgumentException.class) - public void testForBrokenJUnit() { - throw new IllegalArgumentException( "expected" ); - } - */ - private static final class Dummy2 {} @Test @@ -89,9 +78,3 @@ public void testForDuplicates() { catch( IllegalArgumentException e) { /*OK*/ } } } - - - - - - diff --git a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/TestBase.java b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/TestBase.java index bde3317d5f2..ec53e2a9d43 100644 --- a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/TestBase.java +++ b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/TestBase.java @@ -67,9 +67,3 @@ public TestBase() { checkAssertsOn(); } } - - - - - - diff --git a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/UtilTest.java b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/UtilTest.java index f6d16070db1..644f3b2ceac 100644 --- a/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/UtilTest.java +++ b/nucleus/common/amx-core/src/test/java/org/glassfish/admin/amx/test/UtilTest.java @@ -65,9 +65,3 @@ public void testTypes() { assert Util.deduceType(DomainRoot.class).equals( "domain-root" ); } } - - - - - -