summaryrefslogtreecommitdiff
path: root/libjava/classpath/javax/management/MBeanServerFactory.java
blob: f9bd4566f37cb1bcffb545e09cefc2acb6772a32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* MBeanServerFactory.java -- Manages server instances.
   Copyright (C) 2006 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package javax.management;

import gnu.classpath.SystemProperties;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.management.loading.ClassLoaderRepository;

/**
 * <p>
 * Creates and maintains a set of {@link MBeanServer} instances.
 * Server instances, as of JMX 1.2, are created using a subclass
 * of {@link MBeanServerBuilder}.  The exact class used is controlled
 * by the property <code>javax.management.builder.initial</code>,
 * and allows the instances created by {@link MBeanServerBuilder}
 * to be wrapped, thus providing additional functionality.
 * </p>
 * <p>
 * The property is used as follows:
 * </p>
 * <ol>
 * <li>If the property has no value, then an instance of
 * {@link MBeanServerBuilder} is used.</li>
 * <li>If a value is given, then:
 * <ol>
 * <li>The class is loaded using
 * <code>Thread.currentThread().getContextClassLoader()</code>, or,
 * if this is <code>null</code>, by <code>Class.forName()</code>.</li>
 * <li><code>Class.newInstance()</code> is used to create an instance
 * of the class.  The class must be public and have a public empty
 * constructor.  If an exception is thrown, it is propogated as
 * a {@link JMRuntimeException} and no new server instances may be
 * created until the property is set to a valid value.</li>
 * </ol></li>
 * <li>The value is checked on each successive request for a server.
 * If it differs from the class of the existing instance of
 * {@link MBeanServerBuilder}, then the value is used to create
 * a new instance.</li>
 * </ol>
 */
public class MBeanServerFactory
{

  /**
   * The last builder instance.
   */
  private static MBeanServerBuilder builder;

  /**
   * The map of registered servers (identifiers to servers).
   */
  private static final Map<Object,MBeanServer> servers =
    new HashMap<Object,MBeanServer>();

  /**
   * Private constructor to prevent instance creation.
   */
  private MBeanServerFactory() {}

  /**
   * Returns a server implementation using the default domain name
   * of <code>"DefaultDomain"</code>.  The default domain name is
   * used when the domain name specified by the user is <code>null</code.
   * A reference to the created server is retained, so that it can
   * be retrieved at a later date using {@link #findMBeanServer}.
   * Calling this method is equivalent to calling
   * {@link createMBeanServer(String)} with a <code>null</code> value.
   *
   * @return a new {@link MBeanServer} instance.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("createMBeanServer")
   * @throws JMRuntimeException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which either can not be
   *                     instantiated or provides an implementation that returns
   *                     <code>null</code> from either
   *                     {@link MBeanServerBuilder#newMBeanServerDelegate()}
   *                     or {@link MBeanServerBuilder#newMBeanServer()}
   * @throws ClassCastException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which is not a subclass
   *                     of {@link MBeanServerBuilder}.
   * @see #createMBeanServer(String)
   */
  public static MBeanServer createMBeanServer()
  {
    return createMBeanServer(null);
  }

  /**
   * Returns a server implementation using the default domain name
   * given, or <code>"DefaultDomain"</code> if this is <code>null</code>.
   * The default domain name is used when the domain name specified by
   * the user is <code>null</code.  A reference to the created server is
   * retained, so that it can be retrieved at a later date using
   * {@link #findMBeanServer}.
   *
   * @param domain the default domain name of the server.
   * @return a new {@link MBeanServer} instance.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("createMBeanServer")
   * @throws JMRuntimeException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which either can not be
   *                     instantiated or provides an implementation that returns
   *                     <code>null</code> from either
   *                     {@link MBeanServerBuilder#newMBeanServerDelegate()}
   *                     or {@link MBeanServerBuilder#newMBeanServer()}
   * @throws ClassCastException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which is not a subclass
   *                     of {@link MBeanServerBuilder}.
   */
  public static MBeanServer createMBeanServer(String domain)
  {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkPermission(new MBeanServerPermission("createMBeanServer"));
    MBeanServer server = createServer(domain);
    try
      {
        ObjectName dn = new
          ObjectName("JMImplementation:type=MBeanServerDelegate");
        servers.put(server.getAttribute(dn, "MBeanServerId"), server);
      }
    catch (MalformedObjectNameException e)
      {
        throw (Error)
          (new InternalError("Malformed delegate bean name.").initCause(e));
      }
    catch (MBeanException e)
      {
        throw (Error)
          (new InternalError("Exception in getMBeanServerId().").initCause(e));
      }
    catch (AttributeNotFoundException e)
      {
        throw (Error)
          (new InternalError("Could not find MBeanServerId attribute.").initCause(e));
      }
    catch (InstanceNotFoundException e)
      {
        throw (Error)
          (new InternalError("Could not find the delegate bean.").initCause(e));
      }
    catch (ReflectionException e)
      {
        throw (Error)
          (new InternalError("Could not call getMBeanServerId().").initCause(e));
      }
    return server;
  }

  /**
   * Returns the specified server, or, if <code>id</code> is <code>null</code>,
   * a list of all registered servers.  A registered server is one that
   * was created using {@link #createMBeanServer()} or
   * {@link #createMBeanServer(String)} and has not yet been released
   * using {@link releaseMBeanServer(MBeanServer)}.
   *
   * @param id the id of the server to retrieve, or <code>null</code>
   *           to return all servers.
   * @return a list of {@link MBeanServer}s.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("findMBeanServer")
   */
  public static ArrayList<MBeanServer> findMBeanServer(String id)
  {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkPermission(new MBeanServerPermission("findMBeanServer"));
    if (id == null)
      return new ArrayList<MBeanServer>(servers.values());
    ArrayList<MBeanServer> list = new ArrayList<MBeanServer>();
    MBeanServer server = servers.get(id);
    if (server != null)
      list.add(servers.get(id));
    return list;
  }

  /**
   * Returns the class loader repository used by the specified server.
   * This is equivalent to calling {@link MBeanServer#getClassLoaderRepository()}
   * on the given server.
   *
   * @param server the server whose class loader repository should be
   *               retrieved.
   * @throws NullPointerException if <code>server</code> is <code>null</code>.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanPermission(String,String,ObjectName,String)
   *                           <code>MBeanPermission(null, null, null,
   *                           "getClassLoaderRepository")</code>
   */
  public static ClassLoaderRepository getClassLoaderRepository(MBeanServer server)
  {
    return server.getClassLoaderRepository();
  }

  /**
   * Returns a server implementation using the default domain name
   * of <code>"DefaultDomain"</code>.  The default domain name is
   * used when the domain name specified by the user is <code>null</code.
   * No reference to the created server is retained, so the server is
   * garbage collected when it is no longer used, but it can not be
   * retrieved at a later date using {@link #findMBeanServer}.
   * Calling this method is equivalent to calling
   * {@link newMBeanServer(String)} with a <code>null</code> value.
   *
   * @return a new {@link MBeanServer} instance.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("newMBeanServer")
   * @throws JMRuntimeException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which either can not be
   *                     instantiated or provides an implementation that returns
   *                     <code>null</code> from either
   *                     {@link MBeanServerBuilder#newMBeanServerDelegate()}
   *                     or {@link MBeanServerBuilder#newMBeanServer()}
   * @throws ClassCastException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which is not a subclass
   *                     of {@link MBeanServerBuilder}.
   * @see #newMBeanServer(String)
   */
  public static MBeanServer newMBeanServer()
  {
    return newMBeanServer(null);
  }

  /**
   * Returns a server implementation using the default domain name
   * given, or <code>"DefaultDomain"</code> if this is <code>null</code>.
   * The default domain name is used when the domain name specified by
   * the user is <code>null</code.  No reference to the created server is
   * retained, so the server is garbage collected when it is no longer
   * used, but it can not be retrieved at a later date using
   * {@link #findMBeanServer}.
   *
   * @param domain the default domain name of the server.
   * @return a new {@link MBeanServer} instance.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("newMBeanServer")
   * @throws JMRuntimeException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which either can not be
   *                     instantiated or provides an implementation that returns
   *                     <code>null</code> from either
   *                     {@link MBeanServerBuilder#newMBeanServerDelegate()}
   *                     or {@link MBeanServerBuilder#newMBeanServer()}
   * @throws ClassCastException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which is not a subclass
   *                     of {@link MBeanServerBuilder}.
   */
  public static MBeanServer newMBeanServer(String domain)
  {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkPermission(new MBeanServerPermission("newMBeanServer"));
    return createServer(domain);
  }

  /**
   * Common method to create a server for the {@link #createMBeanServer(String)}
   * and {@link #newMBeanServer(String)} methods above.
   *
   * @param domain the default domain name of the server.
   * @throws JMRuntimeException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which either can not be
   *                     instantiated or provides an implementation that returns
   *                     <code>null</code> from either
   *                     {@link MBeanServerBuilder#newMBeanServerDelegate()}
   *                     or {@link MBeanServerBuilder#newMBeanServer()}
   * @throws ClassCastException if the property
   *                     <code>javax.management.builder.initial</code>
   *                     exists but names a class which is not a subclass
   *                     of {@link MBeanServerBuilder}.
   */
  private static MBeanServer createServer(String domain)
    {
    if (domain == null)
      domain = "DefaultDomain";
    String builderClass =
      SystemProperties.getProperty("javax.management.builder.initial");
    if (builderClass == null)
      {
        if (builder == null ||
            builder.getClass() != MBeanServerBuilder.class)
          builder = new MBeanServerBuilder();
      }
    else if (!(builder != null &&
               builderClass.equals(builder.getClass().getName())))
      {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
          cl = MBeanServerFactory.class.getClassLoader();
        try
          {
            Class<?> bClass = Class.forName(builderClass, true, cl);
            builder = (MBeanServerBuilder) bClass.newInstance();
          }
        catch (ClassNotFoundException e)
          {
            throw (JMRuntimeException) (new JMRuntimeException("The builder class, "
                                                               + builderClass +
                                                               ", could not be found."))
              .initCause(e);
          }
        catch (InstantiationException e)
          {
            throw (JMRuntimeException) (new JMRuntimeException("The builder class, "
                                                               + builderClass +
                                                               ", could not be instantiated."))
              .initCause(e);
          }
        catch (IllegalAccessException e)
          {
            throw (JMRuntimeException) (new JMRuntimeException("The builder class, "
                                                               + builderClass +
                                                               ", could not be accessed."))
              .initCause(e);
          }
      }
    MBeanServerDelegate delegate = builder.newMBeanServerDelegate();
    if (delegate == null)
      throw new JMRuntimeException("A delegate could not be created.");
    MBeanServer server = builder.newMBeanServer(domain, null, delegate);
    if (server == null)
      throw new JMRuntimeException("A server could not be created.");
    return server;
  }

  /**
   * Removes the reference to the specified server, thus allowing it to
   * be garbage collected.
   *
   * @param server the server to remove.
   * @throws IllegalArgumentException if a reference to the server is not
   *                                  held (i.e. it wasn't created by
   *                                  {@link #createMBeanServer(String)}
   *                                  or this method has already been called
   *                                  on it.
   * @throws SecurityException if a security manager exists and the
   *                           caller's permissions don't imply {@link
   *                           MBeanServerPermission(String)}("releaseMBeanServer")
   */
  public static void releaseMBeanServer(MBeanServer server)
  {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkPermission(new MBeanServerPermission("releaseMBeanServer"));
    Iterator<MBeanServer> i = servers.values().iterator();
    while (i.hasNext())
      {
        MBeanServer s = i.next();
        if (server == s)
          {
            i.remove();
            return;
          }
      }
    throw new IllegalArgumentException("The server given is not referenced.");
  }


}