KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > modeler > modules > MbeansSource


1 package org.apache.commons.modeler.modules;
2
3 import java.io.FileNotFoundException JavaDoc;
4 import java.io.FileOutputStream JavaDoc;
5 import java.io.InputStream JavaDoc;
6 import java.net.URL JavaDoc;
7 import java.util.ArrayList JavaDoc;
8 import java.util.HashMap JavaDoc;
9 import java.util.List JavaDoc;
10
11 import javax.management.Attribute JavaDoc;
12 import javax.management.MBeanServer JavaDoc;
13 import javax.management.ObjectName JavaDoc;
14 import javax.management.loading.MLet JavaDoc;
15 import javax.xml.transform.TransformerException JavaDoc;
16
17 import org.apache.commons.logging.Log;
18 import org.apache.commons.logging.LogFactory;
19 import org.apache.commons.modeler.AttributeInfo;
20 import org.apache.commons.modeler.BaseModelMBean;
21 import org.apache.commons.modeler.ManagedBean;
22 import org.apache.commons.modeler.Registry;
23 import org.apache.commons.modeler.util.DomUtil;
24 import org.w3c.dom.Document JavaDoc;
25 import org.w3c.dom.Node JavaDoc;
26
27
28 /** This will create mbeans based on a config file.
29  * The format is an extended version of MLET.
30  *
31  * Classloading. We don't support any explicit classloader tag.
32  * A ClassLoader is just an mbean ( it can be the standard MLetMBean or
33  * a custom one ).
34  *
35  * XXX add a special attribute to reference the loader mbean,
36  * XXX figure out how to deal with private loaders
37  */

38 public class MbeansSource extends ModelerSource implements MbeansSourceMBean
39 {
40     private static Log log = LogFactory.getLog(MbeansSource.class);
41     Registry registry;
42     String JavaDoc type;
43
44     // true if we are during the original loading
45
boolean loading=true;
46     List JavaDoc mbeans=new ArrayList JavaDoc();
47     static boolean loaderLoaded=false;
48     private Document JavaDoc document;
49     private HashMap JavaDoc object2Node = new HashMap JavaDoc();
50
51     long lastUpdate;
52     long updateInterval=10000; // 10s
53

54     public void setRegistry(Registry reg) {
55         this.registry=reg;
56     }
57
58     public void setLocation( String JavaDoc loc ) {
59         this.location=loc;
60     }
61
62     /** Used if a single component is loaded
63      *
64      * @param type
65      */

66     public void setType( String JavaDoc type ) {
67        this.type=type;
68     }
69
70     public void setSource( Object JavaDoc source ) {
71         this.source=source;
72     }
73
74     public Object JavaDoc getSource() {
75         return source;
76     }
77
78     public String JavaDoc getLocation() {
79         return location;
80     }
81     
82     /** Return the list of mbeans created by this source.
83      * It can be used to implement runtime services.
84      */

85     public List JavaDoc getMBeans() {
86         return mbeans;
87     }
88
89     public List JavaDoc loadDescriptors( Registry registry, String JavaDoc location,
90                                  String JavaDoc type, Object JavaDoc source)
91             throws Exception JavaDoc
92     {
93         setRegistry(registry);
94         setLocation(location);
95         setType(type);
96         setSource(source);
97         execute();
98         return mbeans;
99     }
100     
101     public void start() throws Exception JavaDoc {
102         registry.invoke(mbeans, "start", false);
103     }
104
105     public void stop() throws Exception JavaDoc {
106         registry.invoke(mbeans, "stop", false);
107     }
108     
109     public void init() throws Exception JavaDoc {
110         if( mbeans==null) execute();
111         if( registry==null ) registry=Registry.getRegistry();
112         
113         registry.invoke(mbeans, "init", false);
114     }
115     
116     public void destroy() throws Exception JavaDoc {
117         registry.invoke(mbeans, "destroy", false);
118     }
119     
120     public void load() throws Exception JavaDoc {
121         execute(); // backward compat
122
}
123
124     public void execute() throws Exception JavaDoc {
125         if( registry==null ) registry=Registry.getRegistry();
126         try {
127             InputStream JavaDoc stream=getInputStream();
128             long t1=System.currentTimeMillis();
129             document = DomUtil.readXml(stream);
130
131             // We don't care what the root node is.
132
Node JavaDoc descriptorsN=document.getDocumentElement();
133
134             if( descriptorsN == null ) {
135                 log.error("No descriptors found");
136                 return;
137             }
138
139             Node JavaDoc firstMbeanN=DomUtil.getChild(descriptorsN, null);
140
141             if( firstMbeanN==null ) {
142                 // maybe we have a single mlet
143
if( log.isDebugEnabled() )
144                     log.debug("No child " + descriptorsN);
145                 firstMbeanN=descriptorsN;
146             }
147
148             MBeanServer JavaDoc server=(MBeanServer JavaDoc)Registry.getServer();
149
150             // XXX Not very clean... Just a workaround
151
if( ! loaderLoaded ) {
152                 // Register a loader that will be find ant classes.
153
ObjectName JavaDoc defaultLoader= new ObjectName JavaDoc("modeler",
154                         "loader", "modeler");
155                 MLet JavaDoc mlet=new MLet JavaDoc( new URL JavaDoc[0], this.getClass().getClassLoader());
156                 server.registerMBean(mlet, defaultLoader);
157                 loaderLoaded=true;
158             }
159         
160             // Process nodes
161
for (Node JavaDoc mbeanN = firstMbeanN; mbeanN != null;
162                  mbeanN= DomUtil.getNext(mbeanN, null, Node.ELEMENT_NODE))
163             {
164                 String JavaDoc nodeName=mbeanN.getNodeName();
165
166                 // mbean is the "official" name
167
if( "mbean".equals(nodeName) || "MLET".equals(nodeName) )
168                 {
169                     String JavaDoc code=DomUtil.getAttribute( mbeanN, "code" );
170                     String JavaDoc objectName=DomUtil.getAttribute( mbeanN, "objectName" );
171                     if( objectName==null ) {
172                         objectName=DomUtil.getAttribute( mbeanN, "name" );
173                     }
174                     
175                     if( log.isDebugEnabled())
176                         log.debug( "Processing mbean objectName=" + objectName +
177                                 " code=" + code);
178
179                     // args can be grouped in constructor or direct childs
180
Node JavaDoc constructorN=DomUtil.getChild(mbeanN, "constructor");
181                     if( constructorN == null ) constructorN=mbeanN;
182
183                     processArg(constructorN);
184
185                     try {
186                         ObjectName JavaDoc oname=new ObjectName JavaDoc(objectName);
187                         if( ! server.isRegistered( oname )) {
188                             // We wrap everything in a model mbean.
189
// XXX need to support "StandardMBeanDescriptorsSource"
190
String JavaDoc modelMBean=BaseModelMBean.class.getName();
191                             server.createMBean(modelMBean, oname,
192                                     new Object JavaDoc[] { code, this},
193                                     new String JavaDoc[] { String JavaDoc.class.getName(),
194                                                   ModelerSource.class.getName() }
195                                     );
196                             mbeans.add(oname);
197                         }
198                         object2Node.put( oname, mbeanN );
199                         // XXX Arguments, loader !!!
200
} catch( Exception JavaDoc ex ) {
201                         log.error( "Error creating mbean " + objectName, ex);
202                     }
203
204                     Node JavaDoc firstAttN=DomUtil.getChild(mbeanN, "attribute");
205                     for (Node JavaDoc descN = firstAttN; descN != null;
206                          descN = DomUtil.getNext( descN ))
207                     {
208                         processAttribute(server, descN, objectName);
209                     }
210                 } else if("jmx-operation".equals(nodeName) ) {
211                     String JavaDoc name=DomUtil.getAttribute(mbeanN, "objectName");
212                     if( name==null )
213                         name=DomUtil.getAttribute(mbeanN, "name");
214
215                     String JavaDoc operation=DomUtil.getAttribute(mbeanN, "operation");
216
217                     if( log.isDebugEnabled())
218                         log.debug( "Processing invoke objectName=" + name +
219                                 " code=" + operation);
220                     try {
221                         ObjectName JavaDoc oname=new ObjectName JavaDoc(name);
222
223                         processArg( mbeanN );
224                         server.invoke( oname, operation, null, null);
225                     } catch (Exception JavaDoc e) {
226                         log.error( "Error in invoke " + name + " " + operation);
227                     }
228                 }
229
230                 ManagedBean managed=new ManagedBean();
231                 DomUtil.setAttributes(managed, mbeanN);
232                 Node JavaDoc firstN;
233
234                 // process attribute info
235
firstN=DomUtil.getChild( mbeanN, "attribute");
236                 for (Node JavaDoc descN = firstN; descN != null;
237                      descN = DomUtil.getNext( descN ))
238                 {
239                     AttributeInfo ci=new AttributeInfo();
240                     DomUtil.setAttributes(ci, descN);
241                     managed.addAttribute( ci );
242                 }
243
244             }
245
246             long t2=System.currentTimeMillis();
247             log.info( "Reading mbeans " + (t2-t1));
248             loading=false;
249         } catch( Exception JavaDoc ex ) {
250             log.error( "Error reading mbeans ", ex);
251         }
252     }
253     
254     public void updateField( ObjectName JavaDoc oname, String JavaDoc name,
255                              Object JavaDoc value )
256     {
257         if( loading ) return;
258         // nothing by default
259
//log.info( "XXX UpdateField " + oname + " " + name + " " + value);
260
Node JavaDoc n=(Node JavaDoc)object2Node.get( oname );
261         if( n == null ) {
262             log.info( "Node not found " + oname );
263             return;
264         }
265         Node JavaDoc attNode=DomUtil.findChildWithAtt(n, "attribute", "name", name);
266         if( attNode == null ) {
267             // found no existing attribute with this name
268
attNode=n.getOwnerDocument().createElement("attribute");
269             DomUtil.setAttribute(attNode, "name", name);
270             n.appendChild(attNode);
271         }
272         String JavaDoc oldValue=DomUtil.getAttribute(attNode, "value");
273         if( oldValue != null ) {
274             // we'll convert all values to text content
275
DomUtil.removeAttribute( attNode, "value");
276         }
277         DomUtil.setText(attNode, value.toString());
278
279         //store();
280
}
281     
282     /** Store the mbeans.
283      * XXX add a background thread to store it periodically
284      */

285     public void save() {
286         // XXX customize no often than ( based on standard descriptor ), etc.
287
// It doesn't work very well if we call this on each set att -
288
// the triger will work for the first att, but all others will be delayed
289
long time=System.currentTimeMillis();
290         if( location!=null &&
291                 time - lastUpdate > updateInterval ) {
292             lastUpdate=time;
293             try {
294                 FileOutputStream JavaDoc fos=new FileOutputStream JavaDoc(location);
295                 DomUtil.writeXml(document, fos);
296             } catch (TransformerException JavaDoc e) {
297                 log.error( "Error writing");
298             } catch (FileNotFoundException JavaDoc e) {
299                 log.error( "Error writing" ,e );
300             }
301         }
302     }
303
304     private void processAttribute(MBeanServer JavaDoc server,
305                                   Node JavaDoc descN, String JavaDoc objectName ) {
306         String JavaDoc attName=DomUtil.getAttribute(descN, "name");
307         String JavaDoc value=DomUtil.getAttribute(descN, "value");
308         String JavaDoc type=null; // DomUtil.getAttribute(descN, "type");
309
if( value==null ) {
310             // The value may be specified as CDATA
311
value=DomUtil.getContent(descN);
312         }
313         try {
314             if( log.isDebugEnabled())
315                 log.debug("Set attribute " + objectName + " " + attName +
316                         " " + value);
317             ObjectName JavaDoc oname=new ObjectName JavaDoc(objectName);
318             // find the type
319
if( type==null )
320                 type=registry.getType( oname, attName );
321
322             if( type==null ) {
323                 log.info("Can't find attribute " + objectName + " " + attName );
324
325             } else {
326                 Object JavaDoc valueO=registry.convertValue( type, value);
327                 server.setAttribute(oname, new Attribute JavaDoc(attName, valueO));
328             }
329         } catch( Exception JavaDoc ex) {
330             log.error("Error processing attribute " + objectName + " " +
331                     attName + " " + value, ex);
332         }
333
334     }
335
336     private void processArg(Node JavaDoc mbeanN) {
337         Node JavaDoc firstArgN=DomUtil.getChild(mbeanN, "arg" );
338         // process all args
339
for (Node JavaDoc argN = firstArgN; argN != null;
340              argN = DomUtil.getNext( argN ))
341         {
342             String JavaDoc type=DomUtil.getAttribute(argN, "type");
343             String JavaDoc value=DomUtil.getAttribute(argN, "value");
344             if( value==null ) {
345                 // The value may be specified as CDATA
346
value=DomUtil.getContent(argN);
347             }
348         }
349     }
350 }
351
Popular Tags