KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log4j > jmx > HierarchyDynamicMBean


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.log4j.jmx;
18
19
20 import java.lang.reflect.Constructor JavaDoc;
21 import org.apache.log4j.*;
22
23 import org.apache.log4j.spi.HierarchyEventListener;
24 import org.apache.log4j.spi.LoggerRepository;
25 import org.apache.log4j.helpers.OptionConverter;
26
27 import java.util.Vector JavaDoc;
28 import javax.management.MBeanAttributeInfo JavaDoc;
29 import javax.management.MBeanConstructorInfo JavaDoc;
30 import javax.management.MBeanNotificationInfo JavaDoc;
31 import javax.management.MBeanOperationInfo JavaDoc;
32 import javax.management.MBeanParameterInfo JavaDoc;
33
34 import javax.management.ObjectName JavaDoc;
35 import javax.management.MBeanInfo JavaDoc;
36 import javax.management.Attribute JavaDoc;
37
38 import javax.management.MBeanException JavaDoc;
39 import javax.management.AttributeNotFoundException JavaDoc;
40 import javax.management.RuntimeOperationsException JavaDoc;
41 import javax.management.ReflectionException JavaDoc;
42 import javax.management.InvalidAttributeValueException JavaDoc;
43 import javax.management.NotificationBroadcasterSupport JavaDoc;
44 import javax.management.NotificationBroadcaster JavaDoc;
45 import javax.management.Notification JavaDoc;
46 import javax.management.NotificationListener JavaDoc;
47 import javax.management.NotificationFilter JavaDoc;
48 import javax.management.NotificationFilterSupport JavaDoc;
49 import javax.management.ListenerNotFoundException JavaDoc;
50
51 public class HierarchyDynamicMBean extends AbstractDynamicMBean
52                                    implements HierarchyEventListener,
53                                               NotificationBroadcaster JavaDoc {
54
55   static final String JavaDoc ADD_APPENDER = "addAppender.";
56   static final String JavaDoc THRESHOLD = "threshold";
57
58   private MBeanConstructorInfo JavaDoc[] dConstructors = new MBeanConstructorInfo JavaDoc[1];
59   private MBeanOperationInfo JavaDoc[] dOperations = new MBeanOperationInfo JavaDoc[1];
60
61   private Vector JavaDoc vAttributes = new Vector JavaDoc();
62   private String JavaDoc dClassName = this.getClass().getName();
63   private String JavaDoc dDescription =
64      "This MBean acts as a management facade for org.apache.log4j.Hierarchy.";
65
66   private NotificationBroadcasterSupport JavaDoc nbs = new NotificationBroadcasterSupport JavaDoc();
67
68
69   private LoggerRepository hierarchy;
70
71   private static Logger log = Logger.getLogger(HierarchyDynamicMBean.class);
72
73   public HierarchyDynamicMBean() {
74     hierarchy = LogManager.getLoggerRepository();
75     buildDynamicMBeanInfo();
76   }
77
78   private
79   void buildDynamicMBeanInfo() {
80     Constructor JavaDoc[] constructors = this.getClass().getConstructors();
81     dConstructors[0] = new MBeanConstructorInfo JavaDoc(
82          "HierarchyDynamicMBean(): Constructs a HierarchyDynamicMBean instance",
83      constructors[0]);
84
85     vAttributes.add(new MBeanAttributeInfo JavaDoc(THRESHOLD,
86                        "java.lang.String",
87                        "The \"threshold\" state of the hiearchy.",
88                        true,
89                        true,
90                        false));
91
92     MBeanParameterInfo JavaDoc[] params = new MBeanParameterInfo JavaDoc[1];
93     params[0] = new MBeanParameterInfo JavaDoc("name", "java.lang.String",
94                        "Create a logger MBean" );
95     dOperations[0] = new MBeanOperationInfo JavaDoc("addLoggerMBean",
96                     "addLoggerMBean(): add a loggerMBean",
97                     params ,
98                     "javax.management.ObjectName",
99                     MBeanOperationInfo.ACTION);
100   }
101
102
103   public
104   ObjectName JavaDoc addLoggerMBean(String JavaDoc name) {
105     Logger cat = LogManager.exists(name);
106
107     if(cat != null) {
108       return addLoggerMBean(cat);
109     } else {
110       return null;
111     }
112   }
113
114   ObjectName JavaDoc addLoggerMBean(Logger logger) {
115     String JavaDoc name = logger.getName();
116     ObjectName JavaDoc objectName = null;
117     try {
118       LoggerDynamicMBean loggerMBean = new LoggerDynamicMBean(logger);
119       objectName = new ObjectName JavaDoc("log4j", "logger", name);
120       server.registerMBean(loggerMBean, objectName);
121
122       NotificationFilterSupport JavaDoc nfs = new NotificationFilterSupport JavaDoc();
123       nfs.enableType(ADD_APPENDER+logger.getName());
124
125       log.debug("---Adding logger ["+name+"] as listener.");
126
127       nbs.addNotificationListener(loggerMBean, nfs, null);
128
129
130       vAttributes.add(new MBeanAttributeInfo JavaDoc("logger="+name,
131                          "javax.management.ObjectName",
132                          "The "+name+" logger.",
133                          true,
134                          true, // this makes the object
135
// clickable
136
false));
137
138     } catch(Exception JavaDoc e) {
139       log.error("Couls not add loggerMBean for ["+name+"].");
140     }
141     return objectName;
142   }
143
144   public
145   void addNotificationListener(NotificationListener JavaDoc listener,
146                    NotificationFilter JavaDoc filter,
147                    java.lang.Object JavaDoc handback) {
148     nbs.addNotificationListener(listener, filter, handback);
149   }
150
151   protected
152   Logger getLogger() {
153     return log;
154   }
155
156   public
157   MBeanInfo JavaDoc getMBeanInfo() {
158     //cat.debug("getMBeanInfo called.");
159

160     MBeanAttributeInfo JavaDoc[] attribs = new MBeanAttributeInfo JavaDoc[vAttributes.size()];
161     vAttributes.toArray(attribs);
162
163     return new MBeanInfo JavaDoc(dClassName,
164              dDescription,
165              attribs,
166              dConstructors,
167              dOperations,
168              new MBeanNotificationInfo JavaDoc[0]);
169   }
170
171   public
172   MBeanNotificationInfo JavaDoc[] getNotificationInfo(){
173     return nbs.getNotificationInfo();
174   }
175
176   public
177   Object JavaDoc invoke(String JavaDoc operationName,
178         Object JavaDoc params[],
179         String JavaDoc signature[]) throws MBeanException JavaDoc,
180                                            ReflectionException JavaDoc {
181
182     if (operationName == null) {
183       throw new RuntimeOperationsException JavaDoc(
184         new IllegalArgumentException JavaDoc("Operation name cannot be null"),
185     "Cannot invoke a null operation in " + dClassName);
186     }
187     // Check for a recognized operation name and call the corresponding operation
188

189     if(operationName.equals("addLoggerMBean")) {
190       return addLoggerMBean((String JavaDoc)params[0]);
191     } else {
192       throw new ReflectionException JavaDoc(
193         new NoSuchMethodException JavaDoc(operationName),
194         "Cannot find the operation " + operationName + " in " + dClassName);
195     }
196
197   }
198
199
200   public
201   Object JavaDoc getAttribute(String JavaDoc attributeName) throws AttributeNotFoundException JavaDoc,
202                                                     MBeanException JavaDoc,
203                                                     ReflectionException JavaDoc {
204
205     // Check attributeName is not null to avoid NullPointerException later on
206
if (attributeName == null) {
207       throw new RuntimeOperationsException JavaDoc(new IllegalArgumentException JavaDoc(
208             "Attribute name cannot be null"),
209        "Cannot invoke a getter of " + dClassName + " with null attribute name");
210     }
211
212     log.debug("Called getAttribute with ["+attributeName+"].");
213
214     // Check for a recognized attributeName and call the corresponding getter
215
if (attributeName.equals(THRESHOLD)) {
216       return hierarchy.getThreshold();
217     } else if(attributeName.startsWith("logger")) {
218       int k = attributeName.indexOf("%3D");
219       String JavaDoc val = attributeName;
220       if(k > 0) {
221     val = attributeName.substring(0, k)+'='+ attributeName.substring(k+3);
222       }
223       try {
224     return new ObjectName JavaDoc("log4j:"+val);
225       } catch(Exception JavaDoc e) {
226     log.error("Could not create ObjectName" + val);
227       }
228     }
229
230
231
232     // If attributeName has not been recognized throw an AttributeNotFoundException
233
throw(new AttributeNotFoundException JavaDoc("Cannot find " + attributeName +
234                      " attribute in " + dClassName));
235
236   }
237
238
239   public
240   void addAppenderEvent(Category logger, Appender appender) {
241     log.debug("addAppenderEvent called: logger="+logger.getName()+
242           ", appender="+appender.getName());
243     Notification JavaDoc n = new Notification JavaDoc(ADD_APPENDER+logger.getName(), this, 0);
244     n.setUserData(appender);
245     log.debug("sending notification.");
246     nbs.sendNotification(n);
247   }
248
249  public
250   void removeAppenderEvent(Category cat, Appender appender) {
251     log.debug("removeAppenderCalled: logger="+cat.getName()+
252           ", appender="+appender.getName());
253   }
254
255   public
256   void postRegister(java.lang.Boolean JavaDoc registrationDone) {
257     log.debug("postRegister is called.");
258     hierarchy.addHierarchyEventListener(this);
259     Logger root = hierarchy.getRootLogger();
260     addLoggerMBean(root);
261   }
262
263   public
264   void removeNotificationListener(NotificationListener JavaDoc listener)
265                                          throws ListenerNotFoundException JavaDoc {
266     nbs.removeNotificationListener(listener);
267   }
268
269   public
270   void setAttribute(Attribute JavaDoc attribute) throws AttributeNotFoundException JavaDoc,
271                                                 InvalidAttributeValueException JavaDoc,
272                                                 MBeanException JavaDoc,
273                                                 ReflectionException JavaDoc {
274
275     // Check attribute is not null to avoid NullPointerException later on
276
if (attribute == null) {
277       throw new RuntimeOperationsException JavaDoc(
278                   new IllegalArgumentException JavaDoc("Attribute cannot be null"),
279       "Cannot invoke a setter of "+dClassName+" with null attribute");
280     }
281     String JavaDoc name = attribute.getName();
282     Object JavaDoc value = attribute.getValue();
283
284     if (name == null) {
285       throw new RuntimeOperationsException JavaDoc(
286                new IllegalArgumentException JavaDoc("Attribute name cannot be null"),
287            "Cannot invoke the setter of "+dClassName+
288            " with null attribute name");
289     }
290
291     if(name.equals(THRESHOLD)) {
292       Level l = OptionConverter.toLevel((String JavaDoc) value,
293                        hierarchy.getThreshold());
294       hierarchy.setThreshold(l);
295     }
296
297
298   }
299 }
300
Popular Tags