1
17
18 package org.apache.tomcat.dbcp.dbcp2;
19
20 import java.lang.management.ManagementFactory;
21 import java.util.Objects;
22
23 import javax.management.MBeanServer;
24 import javax.management.MalformedObjectNameException;
25 import javax.management.ObjectName;
26
27 import org.apache.juli.logging.Log;
28 import org.apache.juli.logging.LogFactory;
29
30
35 class ObjectNameWrapper {
36
37 private static final Log log = LogFactory.getLog(ObjectNameWrapper.class);
38
39 private static MBeanServer MBEAN_SERVER = getPlatformMBeanServer();
40
41 private static MBeanServer getPlatformMBeanServer() {
42 try {
43 return ManagementFactory.getPlatformMBeanServer();
44 } catch (LinkageError | Exception e) {
45
46 log.debug("Failed to get platform MBeanServer", e);
47 return null;
48 }
49 }
50
51 public static ObjectName unwrap(final ObjectNameWrapper wrapper) {
52 return wrapper == null ? null : wrapper.unwrap();
53 }
54
55 public static ObjectNameWrapper wrap(final ObjectName objectName) {
56 return new ObjectNameWrapper(objectName);
57 }
58
59 public static ObjectNameWrapper wrap(final String name) throws MalformedObjectNameException {
60 return wrap(new ObjectName(name));
61 }
62
63 private final ObjectName objectName;
64
65 public ObjectNameWrapper(final ObjectName objectName) {
66 this.objectName = objectName;
67 }
68
69 public void registerMBean(final Object object) {
70 if (MBEAN_SERVER == null || objectName == null) {
71 return;
72 }
73 try {
74 MBEAN_SERVER.registerMBean(object, objectName);
75 } catch (LinkageError | Exception e) {
76 log.warn("Failed to complete JMX registration for " + objectName, e);
77 }
78 }
79
80
83 @Override
84 public String toString() {
85 return Objects.toString(objectName);
86 }
87
88 public void unregisterMBean() {
89 if (MBEAN_SERVER == null || objectName == null) {
90 return;
91 }
92 if (MBEAN_SERVER.isRegistered(objectName)) {
93 try {
94 MBEAN_SERVER.unregisterMBean(objectName);
95 } catch (LinkageError | Exception e) {
96 log.warn("Failed to complete JMX unregistration for " + objectName, e);
97 }
98 }
99 }
100
101 public ObjectName unwrap() {
102 return objectName;
103 }
104
105 }
106