View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstarts.mbeanhelloworld.mbean;
18  
19  import java.lang.management.ManagementFactory;
20  import java.util.logging.Logger;
21  
22  import javax.annotation.PostConstruct;
23  import javax.annotation.PreDestroy;
24  import javax.management.MBeanServer;
25  import javax.management.ObjectName;
26  
27  /**
28   * Abstract component class to register it as mbean.
29   * 
30   * @author Jeremie Lagarde
31   * 
32   */
33  public abstract class AbstractComponentMBean {
34      
35      private static final Logger log = Logger.getLogger(AbstractComponentMBean.class.getName());
36      
37      private final String domain;
38      private String name;
39      private MBeanServer mbeanServer;
40      private ObjectName objectName = null;
41  
42      public AbstractComponentMBean(String domain) {
43          super();
44          this.domain = domain;
45      }
46  
47      @PostConstruct
48      protected void startup() {
49          this.name = this.getClass().getSimpleName();
50          try {
51              objectName = new ObjectName(domain, "type", name);
52              mbeanServer = ManagementFactory.getPlatformMBeanServer();
53              mbeanServer.registerMBean(this, objectName);            
54          } catch (Exception e) {
55              throw new IllegalStateException("Error during registration of "
56                  + name + " into JMX:" + e, e);
57          }
58      }
59  
60      @PreDestroy
61      protected void destroy() {
62          log.info("# << -- Destroy : " + this.name);
63          try {
64              mbeanServer.unregisterMBean(this.objectName);
65          } catch (Exception e) {
66              throw new IllegalStateException("Error during unregistration of "
67                  + name + " into JMX:" + e, e);
68          }
69      }
70  
71  }