KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > system > controller > legacy > OldServiceCreator


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2005, JBoss Inc., and individual contributors as indicated
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.test.system.controller.legacy;
23
24 import java.beans.PropertyEditor JavaDoc;
25 import java.beans.PropertyEditorManager JavaDoc;
26 import java.lang.reflect.Constructor JavaDoc;
27 import java.lang.reflect.UndeclaredThrowableException JavaDoc;
28 import java.net.URL JavaDoc;
29
30 import javax.management.MBeanServer JavaDoc;
31 import javax.management.ObjectInstance JavaDoc;
32 import javax.management.ObjectName JavaDoc;
33
34 import org.jboss.deployment.DeploymentException;
35 import org.jboss.logging.Logger;
36 import org.jboss.mx.service.ServiceConstants;
37 import org.jboss.mx.util.JMXExceptionDecoder;
38 import org.jboss.system.ConfigurationException;
39 import org.jboss.util.Classes;
40 import org.jboss.util.StringPropertyReplacer;
41 import org.w3c.dom.Attr JavaDoc;
42 import org.w3c.dom.Element JavaDoc;
43 import org.w3c.dom.NodeList JavaDoc;
44
45 /**
46  * A helper class for the controller.
47  *
48  * @see org.jboss.system.Service
49  *
50  * @author <a HREF="mailto:marc.fleury@jboss.org">Marc Fleury</a>
51  * @author <a HREF="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
52  * @version $Revision: 1.22 $
53  */

54 public class OldServiceCreator
55 {
56    // Static --------------------------------------------------------
57

58    /** The default XMBean class, when one is not specified */
59    private static final String JavaDoc XMBEAN_CODE = "org.jboss.mx.modelmbean.XMBean";
60    
61    /** Instance logger. */
62    private static final Logger log = Logger.getLogger(OldServiceCreator.class);
63
64    // Attributes ----------------------------------------------------
65

66    /** The server */
67    private MBeanServer JavaDoc server;
68
69    // Constructors --------------------------------------------------
70

71    /**
72     * CTOR
73     *
74     * @param server the MBeanServer
75     */

76    public OldServiceCreator(final MBeanServer JavaDoc server)
77    {
78       this.server = server;
79    }
80
81    // Public --------------------------------------------------------
82

83    /**
84     * Clean shutdown
85     */

86    public void shutdown()
87    {
88       this.server = null;
89    }
90    
91    /**
92     * Parses the given configuration document and creates MBean
93     * instances in the current MBean server.
94     *
95     * @param mbeanName the object name
96     * @param loaderName the classloader
97     * @param mbeanElement the config
98     * @return the created object instance
99     * @throws Exception for any error
100     */

101    public ObjectInstance JavaDoc install(ObjectName JavaDoc mbeanName, ObjectName JavaDoc loaderName,
102       Element JavaDoc mbeanElement) throws Exception JavaDoc
103    {
104       if (server.isRegistered(mbeanName))
105       {
106          throw new DeploymentException("Trying to install an already registered mbean: " + mbeanName);
107       }
108       // If class is given, instantiate it
109
String JavaDoc code = mbeanElement.getAttribute("code");
110       if ( code == null || "".equals(code))
111       {
112          throw new ConfigurationException("missing 'code' attribute");
113       }
114
115       // get the constructor params/sig to use
116
ConstructorInfo constructor = ConstructorInfo.create(mbeanElement);
117
118       // Check for xmbean specific attributes
119
String JavaDoc xmbeandd = null;
120       Attr JavaDoc xmbeanddAttr = mbeanElement.getAttributeNode("xmbean-dd");
121       if( xmbeanddAttr != null )
122          xmbeandd = xmbeanddAttr.getValue();
123       String JavaDoc xmbeanCode = mbeanElement.getAttribute("xmbean-code");
124       if( xmbeanCode.length() == 0 )
125          xmbeanCode = XMBEAN_CODE;
126
127       // Create the mbean instance
128
ObjectInstance JavaDoc instance = null;
129       try
130       {
131          if ( xmbeandd == null )
132          {
133             // Check for the explicit management interface in case of a standard MBean
134
Attr JavaDoc itfAttr = mbeanElement.getAttributeNode("interface");
135             if (itfAttr != null)
136             {
137                // Get the good class loader
138
ClassLoader JavaDoc classLoader = server.getClassLoader(loaderName);
139
140                // Load interface class
141
String JavaDoc itf = itfAttr.getValue();
142                Class JavaDoc itfClass = classLoader.loadClass(itf);
143                log.debug("About to create bean resource: " + mbeanName + " with code: " + code);
144                Object JavaDoc resource = server.instantiate(code,
145                                                     loaderName,
146                                                     constructor.params,
147                                                     constructor.signature);
148                //
149
log.debug("About to register StandardMBean : " + mbeanName);
150                instance = server.createMBean("javax.management.StandardMBean",
151                                              mbeanName,
152                                              loaderName,
153                                              new Object JavaDoc[]{resource,itfClass},
154                                              new String JavaDoc[]{Object JavaDoc.class.getName(),Class JavaDoc.class.getName()});
155             }
156             else
157             {
158                // This is a standard or dynamic mbean
159
log.debug("About to create bean: " + mbeanName + " with code: " + code);
160                instance = server.createMBean(code,
161                                              mbeanName,
162                                              loaderName,
163                                              constructor.params,
164                                              constructor.signature);
165             }
166          } // end of if ()
167
else if( xmbeandd.length() == 0 )
168          {
169             // This is an xmbean with an embedded mbean descriptor
170
log.debug("About to create xmbean object: " + mbeanName
171                + " with code: " + code + " with embedded descriptor");
172             //xmbean: construct object first.
173
Object JavaDoc resource = server.instantiate(code, loaderName,
174                   constructor.params, constructor.signature);
175
176             NodeList JavaDoc mbeans = mbeanElement.getElementsByTagName("xmbean");
177             if( mbeans.getLength() == 0 )
178                throw new ConfigurationException("No nested mbean element given for xmbean");
179             Element JavaDoc mbeanDescriptor = (Element JavaDoc) mbeans.item(0);
180             Object JavaDoc[] args = {resource, mbeanDescriptor,
181                              ServiceConstants.PUBLIC_JBOSSMX_XMBEAN_DTD_1_0};
182             String JavaDoc[] sig = {Object JavaDoc.class.getName(), Element JavaDoc.class.getName(),
183                             String JavaDoc.class.getName()};
184             instance = server.createMBean(xmbeanCode,
185                                           mbeanName,
186                                           loaderName,
187                                           args,
188                                           sig);
189          }
190          else
191          {
192             // This is an xmbean with an external descriptor
193
log.debug("About to create xmbean object: " + mbeanName
194                + " with code: " + code + " with descriptor: "+xmbeandd);
195             //xmbean: construct object first.
196
Object JavaDoc resource = server.instantiate(code, loaderName,
197                   constructor.params, constructor.signature);
198             // Try to find the dd first as a resource then as a URL
199
URL JavaDoc xmbeanddUrl = null;
200             try
201             {
202                xmbeanddUrl = resource.getClass().getClassLoader().getResource(xmbeandd);
203             }
204             catch (Exception JavaDoc e)
205             {
206             } // end of try-catch
207
if (xmbeanddUrl == null)
208             {
209                xmbeanddUrl = new URL JavaDoc(xmbeandd);
210             } // end of if ()
211

212             //now create the mbean
213
Object JavaDoc[] args = {resource, xmbeanddUrl};
214             String JavaDoc[] sig = {Object JavaDoc.class.getName(), URL JavaDoc.class.getName()};
215             instance = server.createMBean(xmbeanCode,
216                                           mbeanName,
217                                           loaderName,
218                                           args,
219                                           sig);
220          } // end of else
221
}
222       catch (Throwable JavaDoc e)
223       {
224          Throwable JavaDoc newE = JMXExceptionDecoder.decode(e);
225
226          // didn't work, unregister in case the jmx agent is screwed.
227
try
228          {
229             server.unregisterMBean(mbeanName);
230          }
231          catch (Throwable JavaDoc ignore)
232          {
233          }
234
235          if (newE instanceof Exception JavaDoc)
236          {
237             throw (Exception JavaDoc)newE;
238          } // end of if ()
239
throw new UndeclaredThrowableException JavaDoc(newE);
240       }
241
242       log.debug("Created bean: "+mbeanName);
243       return instance;
244    }
245
246    public void remove(ObjectName JavaDoc name) throws Exception JavaDoc
247    {
248       // add defaut domain if there isn't one in this name
249
String JavaDoc domain = name.getDomain();
250       if (domain == null || "".equals(domain))
251       {
252          name = new ObjectName JavaDoc(server.getDefaultDomain() + name);
253       }
254
255       // Remove the MBean from the MBeanServer
256
server.unregisterMBean(name);
257    }
258
259    // Inner Class --------------------------------------------------
260

261    /**
262     * Provides a wrapper around the information about which constructor
263     * that MBeanServer should use to construct a MBean.
264     * Please note that only basic datatypes (type is then the same as
265     * you use to declare it "short", "int", "float" etc.) and any class
266     * having a constructor taking a single "String" as only parameter.
267     *
268     * <p>XML syntax for contructor:
269     * <pre>
270     * <constructor>
271     * <arg type="xxx" value="yyy"/>
272     * ...
273     * <arg type="xxx" value="yyy"/>
274     * </constructor>
275     * </pre>
276     */

277    private static class ConstructorInfo
278    {
279       /** An empty parameters list. */
280       public static final Object JavaDoc EMPTY_PARAMS[] = {};
281
282       /** An signature list. */
283       public static final String JavaDoc EMPTY_SIGNATURE[] = {};
284
285       /** The constructor signature. */
286       public String JavaDoc[] signature = EMPTY_SIGNATURE;
287
288       /** The constructor parameters. */
289       public Object JavaDoc[] params = EMPTY_PARAMS;
290
291       /**
292        * Create a ConstructorInfo object for the given configuration.
293        *
294        * @param element The element to build info for.
295        * @return A constructor information object.
296        *
297        * @throws ConfigurationException Failed to create info object.
298        */

299       public static ConstructorInfo create(Element JavaDoc element)
300          throws ConfigurationException
301       {
302          ConstructorInfo info = new ConstructorInfo();
303          NodeList JavaDoc list = element.getElementsByTagName("constructor");
304          if (list.getLength() > 1 && list.item(0).getParentNode() == element)
305          {
306             throw new ConfigurationException
307             ("only one <constructor> element may be defined");
308          }
309          else if (list.getLength() == 1)
310          {
311             element = (Element JavaDoc)list.item(0);
312
313             // get all of the "arg" elements
314
list = element.getElementsByTagName("arg");
315             int length = list.getLength();
316             info.params = new Object JavaDoc[length];
317             info.signature = new String JavaDoc[length];
318             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
319
320             // decode the values into params & signature
321
for (int j=0; j<length; j++)
322             {
323                Element JavaDoc arg = (Element JavaDoc)list.item(j);
324                String JavaDoc signature = arg.getAttribute("type");
325                String JavaDoc value = arg.getAttribute("value");
326                // Allow for system property reference replacement
327
value = StringPropertyReplacer.replaceProperties(arg.getAttribute("value"));
328                Object JavaDoc realValue = value;
329
330                if( signature != null )
331                {
332                   // See if it is a primitive type first
333
Class JavaDoc typeClass = Classes.getPrimitiveTypeForName(signature);
334                   if (typeClass == null)
335                   {
336                      // Try to load the class
337
try
338                      {
339                         typeClass = loader.loadClass(signature);
340                      }
341                      catch (ClassNotFoundException JavaDoc e)
342                      {
343                         throw new ConfigurationException
344                            ("Class not found for type: " + signature, e);
345                      }
346                   }
347
348                   // Convert the string to the real value
349
PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(typeClass);
350                   if (editor == null)
351                   {
352                      try
353                      {
354                         // See if there is a ctor(String) for the type
355
Class JavaDoc[] sig = {String JavaDoc.class};
356                         Constructor JavaDoc ctor = typeClass.getConstructor(sig);
357                         Object JavaDoc[] args = {value};
358                         realValue = ctor.newInstance(args);
359                      }
360                      catch (Exception JavaDoc e)
361                      {
362                         throw new ConfigurationException("No property editor for type: " + typeClass);
363                      }
364                   }
365                   else
366                   {
367                      editor.setAsText(value);
368                      realValue = editor.getValue();
369                   }
370                }
371                info.signature[j] = signature;
372                info.params[j] = realValue;
373             }
374          }
375
376          return info;
377       }
378    }
379
380 }
381
Popular Tags