1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.eclipse.jetty.monitor.jmx;
15
16 import java.io.IOException;
17 import java.lang.management.ManagementFactory;
18
19 import javax.management.MBeanServer;
20 import javax.management.MBeanServerConnection;
21 import javax.management.remote.JMXConnector;
22 import javax.management.remote.JMXConnectorFactory;
23 import javax.management.remote.JMXConnectorServer;
24 import javax.management.remote.JMXConnectorServerFactory;
25 import javax.management.remote.JMXServiceURL;
26
27 import org.eclipse.jetty.util.log.Log;
28 import org.eclipse.jetty.util.log.Logger;
29
30
31
32
33
34
35
36
37
38 public class ServiceConnection
39 {
40 private static final Logger LOG = Log.getLogger(ServiceConnection.class);
41
42 private String _serviceUrl;
43 private MBeanServer _server;
44 private JMXConnectorServer _connectorServer;
45 private JMXConnector _serverConnector;
46 private MBeanServerConnection _serviceConnection;
47
48
49
50
51
52
53
54 public ServiceConnection()
55 throws IOException
56 {
57 this(null);
58 }
59
60
61
62
63
64
65
66
67 public ServiceConnection(String url)
68 throws IOException
69 {
70 _serviceUrl = url;
71 }
72
73
74
75
76
77
78 public String getServiceUrl()
79 {
80 return _serviceUrl;
81 }
82
83
84
85
86
87
88
89 public MBeanServerConnection getConnection()
90 {
91 return _serviceConnection;
92 }
93
94 public void connect()
95 throws IOException
96 {
97 if (_serviceConnection == null)
98 {
99 if (_serviceUrl == null)
100 openLoopbackConnection();
101 else
102 openServerConnection(_serviceUrl);
103 }
104 }
105
106
107
108
109
110
111 private void openLoopbackConnection()
112 throws IOException
113 {
114 _server = ManagementFactory.getPlatformMBeanServer();
115
116 JMXServiceURL serviceUrl = new JMXServiceURL("service:jmx:rmi://");
117 _connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, null, _server);
118 _connectorServer.start();
119
120 _serviceUrl = _connectorServer.getAddress().toString();
121
122 _serverConnector = JMXConnectorFactory.connect(_connectorServer.getAddress());
123 _serviceConnection = _serverConnector.getMBeanServerConnection();
124 }
125
126
127
128
129
130
131
132
133 private void openServerConnection(String url)
134 throws IOException
135 {
136 _serviceUrl = url;
137
138 JMXServiceURL serviceUrl = new JMXServiceURL(_serviceUrl);
139 _serverConnector = JMXConnectorFactory.connect(serviceUrl);
140 _serviceConnection = _serverConnector.getMBeanServerConnection();
141 }
142
143
144
145
146
147 public void disconnect()
148 {
149 try
150 {
151 if (_serverConnector != null)
152 {
153 _serverConnector.close();
154 _serviceConnection = null;
155 }
156 if (_connectorServer != null)
157 {
158 _connectorServer.stop();
159 _connectorServer = null;
160 }
161 }
162 catch (Exception ex)
163 {
164 LOG.debug(ex);
165 }
166 }
167 }