KickJava   Java API By Example, From Geeks To Geeks.

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


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.io.IOException JavaDoc;
27 import java.io.StringReader JavaDoc;
28 import java.io.StringWriter JavaDoc;
29 import java.io.Writer JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.ListIterator JavaDoc;
35 import java.util.Properties JavaDoc;
36
37 import javax.management.Attribute JavaDoc;
38 import javax.management.InstanceNotFoundException JavaDoc;
39 import javax.management.MBeanAttributeInfo JavaDoc;
40 import javax.management.MBeanInfo JavaDoc;
41 import javax.management.MBeanServer JavaDoc;
42 import javax.management.ObjectInstance JavaDoc;
43 import javax.management.ObjectName JavaDoc;
44 import javax.xml.parsers.DocumentBuilder JavaDoc;
45 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
46 import javax.xml.transform.Transformer JavaDoc;
47 import javax.xml.transform.TransformerException JavaDoc;
48 import javax.xml.transform.TransformerFactory JavaDoc;
49 import javax.xml.transform.dom.DOMSource JavaDoc;
50 import javax.xml.transform.stream.StreamResult JavaDoc;
51
52 import org.jboss.deployment.DeploymentException;
53 import org.jboss.logging.Logger;
54 import org.jboss.mx.util.JMXExceptionDecoder;
55 import org.jboss.mx.util.MBeanProxyExt;
56 import org.jboss.mx.util.ObjectNameFactory;
57 import org.jboss.system.ConfigurationException;
58 import org.jboss.system.ServiceBinding;
59 import org.jboss.system.ServiceContext;
60 import org.jboss.util.Classes;
61 import org.jboss.util.StringPropertyReplacer;
62 import org.jboss.util.propertyeditor.PropertyEditors;
63 import org.jboss.util.xml.DOMWriter;
64 import org.jboss.xb.binding.Unmarshaller;
65 import org.jboss.xb.binding.UnmarshallerFactory;
66 import org.jboss.xb.binding.sunday.unmarshalling.SchemaBindingResolver;
67 import org.jboss.xb.binding.sunday.unmarshalling.SingletonSchemaResolverFactory;
68 import org.w3c.dom.Document JavaDoc;
69 import org.w3c.dom.Element JavaDoc;
70 import org.w3c.dom.Node JavaDoc;
71 import org.w3c.dom.NodeList JavaDoc;
72 import org.w3c.dom.Text JavaDoc;
73
74 /**
75  * Service configuration helper.
76  * @author <a HREF="mailto:marc@jboss.org">Marc Fleury</a>
77  * @author <a HREF="mailto:hiram@jboss.org">Hiram Chirino</a>
78  * @author <a HREF="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
79  * @author <a HREF="mailto:jason@planet57.com">Jason Dillon</a>
80  * @author <a HREF="mailto:dimitris@jboss.org">Dimitris Andreadis</a>
81  * @version <tt>$Revision: 1.45 $</tt>
82  */

83 public class OldServiceConfigurator
84 {
85    /**
86     * Augment the PropertyEditorManager search path to incorporate the JBoss
87     * specific editors. This simply references the PropertyEditors.class to
88     * invoke its static initialization block.
89     */

90    static
91    {
92       PropertyEditors.init();
93    }
94
95    // Private Data --------------------------------------------------
96

97    /** The MBean server which this service is registered in. */
98    private final MBeanServer JavaDoc server;
99    
100    /** The parent service controller */
101    private final OldServiceController serviceController;
102    
103    /** The ServiceCreator */
104    private final OldServiceCreator serviceCreator;
105    
106    /** The ServiceBinding plugin policy */
107    private ServiceBinding serviceBinding;
108
109    /**
110     * The instance logger.
111     */

112    private final Logger log = Logger.getLogger(getClass());
113
114    // Constructor ---------------------------------------------------
115

116    /**
117     * Constructor
118     *
119     * @param server
120     * @param serviceController
121     * @param serviceCreator
122     */

123    public OldServiceConfigurator(MBeanServer JavaDoc server,
124          OldServiceController serviceController, OldServiceCreator serviceCreator)
125    {
126       this.server = server;
127       this.serviceController = serviceController;
128       this.serviceCreator = serviceCreator;
129       this.serviceBinding = null;
130    }
131
132    // Public --------------------------------------------------------
133

134    /**
135     * Dynamically plug-in a ServiceBinding policy
136     * to possibly override the configuration of a service.
137     *
138     * @param serviceBinding policy
139     */

140    public void setServiceBinding(ServiceBinding serviceBinding)
141    {
142       this.serviceBinding = serviceBinding;
143    }
144    
145    /**
146     * The <code>install</code> method iterates through the mbean tags in the
147     * supplied xml configuration and creates and configures the mbeans shown.
148     * The mbean configuration can be nested.
149     * @param config the xml <code>Element</code> containing the configuration of
150     * the mbeans to create and configure.
151     * @param loaderName the class loader
152     * @return a <code>List</code> of ObjectNames of created mbeans.
153     * @throws DeploymentException if an error occurs
154     */

155    public List JavaDoc<ObjectName JavaDoc> install(Element JavaDoc config, ObjectName JavaDoc loaderName) throws DeploymentException
156    {
157       List JavaDoc<ObjectName JavaDoc> mbeans = new ArrayList JavaDoc<ObjectName JavaDoc>();
158       try
159       {
160          if (config.getTagName().equals("mbean"))
161          {
162             internalInstall(config, mbeans, loaderName, true);
163          }
164          else
165          {
166             NodeList JavaDoc nl = config.getChildNodes();
167
168             for (int i = 0; i < nl.getLength(); i++)
169             {
170                if (nl.item(i).getNodeType() == Node.ELEMENT_NODE)
171                {
172                   Element JavaDoc element = (Element JavaDoc) nl.item(i);
173                   if (element.getTagName().equals("mbean"))
174                   {
175                      Element JavaDoc mbean = (Element JavaDoc) nl.item(i);
176                      internalInstall(mbean, mbeans, loaderName, true);
177                   } // end of if ()
178
} // end of if ()
179
}//end of for
180
} //end of else
181
return mbeans;
182       }
183       catch (Exception JavaDoc e)
184       {
185          for (ListIterator JavaDoc li = mbeans.listIterator(mbeans.size()); li.hasPrevious();)
186          {
187             ObjectName JavaDoc mbean = (ObjectName JavaDoc) li.previous();
188             try
189             {
190                serviceCreator.remove(mbean);
191             }
192             catch (Exception JavaDoc n)
193             {
194                log.error("exception removing mbean after failed deployment: " + mbean, n);
195             }
196          }
197
198          if (e instanceof DeploymentException)
199             throw (DeploymentException) e;
200
201          throw new DeploymentException(e);
202       }
203    }
204
205    /**
206     * Builds a string that consists of the configuration elements of the
207     * currently running MBeans registered in the server.
208     *
209     * @param objectNames the object names
210     * @return the xml string
211     * @throws Exception Failed to construct configuration.
212     * @todo replace with more sophisticated mbean persistence mechanism.
213     */

214    public String JavaDoc getConfiguration(ObjectName JavaDoc[] objectNames)
215       throws Exception JavaDoc
216    {
217       Writer JavaDoc out = new StringWriter JavaDoc();
218
219       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
220       DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
221       Document JavaDoc doc = builder.newDocument();
222
223       Element JavaDoc serverElement = doc.createElement("server");
224
225       // Store attributes as XML
226
for (int j = 0; j < objectNames.length; j++)
227       {
228          Element JavaDoc mbeanElement = internalGetConfiguration(doc, objectNames[j]);
229          serverElement.appendChild(mbeanElement);
230       }
231
232       doc.appendChild(serverElement);
233
234       // Write configuration
235
new DOMWriter(out).setPrettyprint(true).print(doc);
236
237       out.close();
238
239       // Return configuration
240
return out.toString();
241    }
242    
243    // Protected -----------------------------------------------------
244

245    /**
246     * The <code>configure</code> method configures an mbean based on the xml
247     * element configuration passed in. Three formats are supported:
248     * &lt;attribute name="(name)"&gt;(value)&lt;/attribute&gt; &lt;depends
249     * optional-attribute-name="(name)"&gt;(object name of mbean
250     * referenced)&lt;/depends&gt; &lt;depends-list optional-attribute-name="(name)"&gt;
251     * [list of] &lt;/depends-list-element&gt;(object name)&lt;/depends-list-element&gt;
252     * &lt;/depends-list&gt;
253     *
254     * The last two can include nested mbean configurations or ObjectNames.
255     * SIDE-EFFECT: adds all mbeans this one depends on to the ServiceContext
256     * structures.
257     * @param mbeanElement an <code>Element</code> value
258     * @throws Exception if an error occurs
259     */

260    protected void configure(ObjectName JavaDoc objectName, ObjectName JavaDoc loaderName,
261       Element JavaDoc mbeanElement, List JavaDoc<ObjectName JavaDoc> mbeans)
262       throws Exception JavaDoc
263    {
264       // Set configuration to MBeans from XML
265

266       MBeanInfo JavaDoc info;
267       try
268       {
269          info = server.getMBeanInfo(objectName);
270       }
271       catch (InstanceNotFoundException JavaDoc e)
272       {
273          // The MBean is no longer available
274
throw new DeploymentException("trying to configure nonexistent mbean: " + objectName);
275       }
276       catch (Exception JavaDoc e)
277       {
278          throw new DeploymentException("Could not get mbeanInfo", JMXExceptionDecoder.decode(e));
279       } // end of catch
280

281       if (info == null)
282       {
283          throw new DeploymentException("MBeanInfo is null for mbean: " + objectName);
284       } // end of if ()
285

286       // Get the classloader for loading attribute classes.
287
ClassLoader JavaDoc cl = server.getClassLoader(loaderName);
288       // Initialize the mbean using the configuration supplied defaults
289
MBeanAttributeInfo JavaDoc[] attributes = info.getAttributes();
290       HashMap JavaDoc<String JavaDoc, MBeanAttributeInfo JavaDoc> attributeMap = new HashMap JavaDoc<String JavaDoc, MBeanAttributeInfo JavaDoc>();
291       for (int i = 0; i < attributes.length; i++)
292       {
293          MBeanAttributeInfo JavaDoc attr = attributes[i];
294          attributeMap.put(attr.getName(), attr);
295       }
296
297       NodeList JavaDoc attrs = mbeanElement.getChildNodes();
298       for (int j = 0; j < attrs.getLength(); j++)
299       {
300          // skip over non-element nodes
301
if (attrs.item(j).getNodeType() != Node.ELEMENT_NODE)
302          {
303             continue;
304          }
305
306          Element JavaDoc element = (Element JavaDoc) attrs.item(j);
307
308          boolean replace = true;
309
310          // Set attributes
311
if (element.getTagName().equals("attribute"))
312          {
313             String JavaDoc attributeName = element.getAttribute("name");
314             boolean trim = true;
315             String JavaDoc replaceAttr = element.getAttribute("replace");
316             if (replaceAttr.length() > 0)
317                replace = Boolean.valueOf(replaceAttr).booleanValue();
318             String JavaDoc trimAttr = element.getAttribute("trim");
319             if (trimAttr.length() > 0)
320                trim = Boolean.valueOf(trimAttr).booleanValue();
321             String JavaDoc serialDataType = element.getAttribute("serialDataType");
322
323             // Get the MBeanAttributeInfo
324
MBeanAttributeInfo JavaDoc attr = attributeMap.get(attributeName);
325             if (attr == null)
326                throw new DeploymentException("No Attribute found with name: " + attributeName);
327
328             if (element.hasChildNodes())
329             {
330                Object JavaDoc value = null;
331                // Unmarshall the attribute value based on the serialDataType
332
if (serialDataType.equals("javaBean"))
333                   value = parseJavaBeanSerialData(attr, cl, element, replace, trim);
334                else if (serialDataType.equals("jbxb"))
335                   value = parseJbxbSerialData(attr, cl, element, replace, trim);
336                else
337                   value = parseTextSerialData(attr, cl, element, replace, trim);
338                
339                log.debug(attributeName + " set to " + value + " in " + objectName);
340                setAttribute(objectName, new Attribute JavaDoc(attributeName, value));
341             }//if has children
342

343          }
344          //end of "attribute
345
else if (element.getTagName().equals("depends"))
346          {
347             if (!element.hasChildNodes())
348             {
349                throw new DeploymentException("No ObjectName supplied for depends in " + objectName);
350             }
351
352             String JavaDoc mbeanRefName = element.getAttribute("optional-attribute-name");
353             if ("".equals(mbeanRefName))
354                mbeanRefName = null;
355             else
356                mbeanRefName = StringPropertyReplacer.replaceProperties(mbeanRefName);
357
358             String JavaDoc proxyType = element.getAttribute("proxy-type");
359             if ("".equals(proxyType))
360                proxyType = null;
361             else
362                proxyType = StringPropertyReplacer.replaceProperties(proxyType);
363
364             // Get the mbeanRef value
365
ObjectName JavaDoc dependsObjectName = processDependency(objectName, loaderName, element, mbeans, replace);
366             log.debug("considering " + ((mbeanRefName == null) ? "<anonymous>" : mbeanRefName.toString()) + " with object name " + dependsObjectName);
367
368             if (mbeanRefName != null)
369             {
370                Object JavaDoc attribute = dependsObjectName;
371                if (proxyType != null)
372                {
373                   if (mbeanRefName == null)
374                      throw new DeploymentException("You cannot use a proxy-type without an optional-attribute-name");
375                   if (proxyType.equals("attribute"))
376                   {
377                      MBeanAttributeInfo JavaDoc attr = attributeMap.get(mbeanRefName);
378                      if (attr == null)
379                         throw new DeploymentException("No Attribute found with name: " + mbeanRefName);
380                      proxyType = attr.getType();
381                   }
382                   Class JavaDoc proxyClass = cl.loadClass(proxyType);
383                   attribute = MBeanProxyExt.create(proxyClass, dependsObjectName,
384                      server, true);
385                }
386
387                //if if doesn't exist or has wrong type, we'll get an exception
388
setAttribute(objectName, new Attribute JavaDoc(mbeanRefName, attribute));
389             } // end of if ()
390
}
391          //end of depends
392
else if (element.getTagName().equals("depends-list"))
393          {
394             String JavaDoc dependsListName = element.getAttribute("optional-attribute-name");
395             if ("".equals(dependsListName))
396             {
397                dependsListName = null;
398             } // end of if ()
399

400             NodeList JavaDoc dependsList = element.getChildNodes();
401             ArrayList JavaDoc<ObjectName JavaDoc> dependsListNames = new ArrayList JavaDoc<ObjectName JavaDoc>();
402             for (int l = 0; l < dependsList.getLength(); l++)
403             {
404                if (dependsList.item(l).getNodeType() != Node.ELEMENT_NODE)
405                {
406                   continue;
407                }
408
409                Element JavaDoc dependsElement = (Element JavaDoc) dependsList.item(l);
410                if (dependsElement.getTagName().equals("depends-list-element"))
411                {
412                   if (!dependsElement.hasChildNodes())
413                   {
414                      throw new DeploymentException("Empty depends-list-element!");
415                   } // end of if ()
416

417                   // Get the depends value
418
ObjectName JavaDoc dependsObjectName = processDependency(objectName, loaderName, dependsElement, mbeans, replace);
419                   if (!dependsListNames.contains(dependsObjectName))
420                   {
421                      dependsListNames.add(dependsObjectName);
422                   } // end of if ()
423
}
424
425             } // end of for ()
426
if (dependsListName != null)
427             {
428                setAttribute(objectName, new Attribute JavaDoc(dependsListName, dependsListNames));
429             } // end of if ()
430
}//end of depends-list
431
}
432
433       // If a ServiceBinding policy is plugged-in, check for overriden attributes
434
if (serviceBinding != null)
435       {
436          try
437          {
438             serviceBinding.applyServiceConfig(objectName);
439          }
440          catch (Exception JavaDoc e)
441          {
442             // serviceBinding is most probably a dynamic mbean proxy
443
Throwable JavaDoc t = JMXExceptionDecoder.decode(e);
444             log.warn("Failed to apply service binding override", t);
445          }
446       }
447    }
448
449    // Private -------------------------------------------------------
450

451    private ObjectName JavaDoc internalInstall(Element JavaDoc mbeanElement, List JavaDoc<ObjectName JavaDoc> mbeans,
452          ObjectName JavaDoc loaderName, boolean replace) throws Exception JavaDoc
453       {
454          ObjectInstance JavaDoc instance = null;
455          ObjectName JavaDoc mbeanName = parseObjectName(mbeanElement, replace);
456
457          instance = serviceCreator.install(mbeanName, loaderName, mbeanElement);
458
459          // just in case it changed...
460
mbeanName = instance.getObjectName();
461
462          mbeans.add(mbeanName);
463          if (mbeanName != null)
464          {
465             ServiceContext ctx = serviceController.createServiceContext(mbeanName);
466             try
467             {
468                configure(mbeanName, loaderName, mbeanElement, mbeans);
469                ctx.state = ServiceContext.CONFIGURED;
470                ctx.problem = null;
471             }
472             catch (Throwable JavaDoc e) // TODO Backport to JBoss4!!!!
473
{
474                ctx.state = ServiceContext.FAILED;
475                ctx.problem = e;
476                log.info("Problem configuring service " + mbeanName, e);
477                //throw e;
478
}
479          }
480
481          return mbeanName;
482       }
483    
484    /**
485     * Configure the mbean attribute using the element text and PropertyEditor for the
486     * attribute type.
487     * @param attr - the mbean attribute
488     * @param cl - the class loader to use
489     * @param element - the mbean attribute element from the jboss-service descriptor
490     * @param replace - flag indicating if ${x} system property refs should be replaced
491     * @param trim - flag indicating if the element text shold be trimmed
492     * @return the configured attribute value
493     * @throws Exception
494     */

495    private Object JavaDoc parseTextSerialData(MBeanAttributeInfo JavaDoc attr, ClassLoader JavaDoc cl,
496       Element JavaDoc element, boolean replace, boolean trim)
497       throws Exception JavaDoc
498    {
499       // Get the attribute value
500
String JavaDoc attributeName = attr.getName();
501       String JavaDoc attributeText = getElementContent(element, trim, replace);
502       String JavaDoc typeName = attr.getType();
503
504       // see if it is a primitive type first
505
Class JavaDoc typeClass = Classes.getPrimitiveTypeForName(typeName);
506       if (typeClass == null)
507       {
508          // nope try look up
509
try
510          {
511             typeClass = cl.loadClass(typeName);
512          }
513          catch (ClassNotFoundException JavaDoc e)
514          {
515             throw new DeploymentException
516                ("Class not found for attribute: " + attributeName, e);
517          }
518       }
519
520       Object JavaDoc value = null;
521
522       /* Attributes of type Element are passed as is after optionally
523       performing system property replacement
524       */

525       if (typeClass.equals(Element JavaDoc.class))
526       {
527          // Use the first child Element of this element as the value
528
NodeList JavaDoc nl = element.getChildNodes();
529          for (int i = 0; i < nl.getLength(); i++)
530          {
531             Node JavaDoc n = nl.item(i);
532             if (n.getNodeType() == Node.ELEMENT_NODE)
533             {
534                value = n;
535                break;
536             }
537          }
538          // Replace any ${x} references in the element text
539
if (replace)
540          {
541             PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(typeClass);
542             if (editor == null)
543             {
544                log.warn("Cannot perform property replace on Element");
545             }
546             else
547             {
548                editor.setValue(value);
549                String JavaDoc text = editor.getAsText();
550                text = StringPropertyReplacer.replaceProperties(text);
551                editor.setAsText(text);
552                value = editor.getValue();
553             }
554          }
555       }
556
557       if (value == null)
558       {
559          PropertyEditor JavaDoc editor = PropertyEditorManager.findEditor(typeClass);
560          if (editor == null)
561          {
562             throw new DeploymentException
563                ("No property editor for attribute: " + attributeName +
564                "; type=" + typeClass);
565          }
566
567          // JBAS-1709, temporarily switch the TCL so that property
568
// editors have access to the actual deployment ClassLoader.
569
ClassLoader JavaDoc tcl = Thread.currentThread().getContextClassLoader();
570          Thread.currentThread().setContextClassLoader(cl);
571          try
572          {
573             editor.setAsText(attributeText);
574             value = editor.getValue();
575          }
576          finally
577          {
578             Thread.currentThread().setContextClassLoader(tcl);
579          }
580       }
581       return value;
582    }
583
584    /**
585     * Configure the mbean attribute as a javabean with the bean properties given by
586     * nested property elements.
587     * @param attr - the mbean attribute
588     * @param cl - the class loader to use
589     * @param element - the mbean attribute element from the jboss-service descriptor
590     * @param replace - flag indicating if ${x} system property refs should be replaced
591     * @param trim - flag indicating if the element text shold be trimmed
592     * @return the configured attribute java bean
593     * @throws Exception
594     */

595    private Object JavaDoc parseJavaBeanSerialData(MBeanAttributeInfo JavaDoc attr, ClassLoader JavaDoc cl,
596       Element JavaDoc element, boolean replace, boolean trim)
597       throws Exception JavaDoc
598    {
599       // Extract the property elements
600
String JavaDoc attributeClassName = element.getAttribute("attributeClass");
601       if( attributeClassName == null || attributeClassName.length() == 0 )
602          attributeClassName = attr.getType();
603       Class JavaDoc attributeClass = cl.loadClass(attributeClassName);
604       // Create the bean instance
605
Object JavaDoc bean = attributeClass.newInstance();
606       // Get the JavaBean properties
607
NodeList JavaDoc properties = element.getElementsByTagName("property");
608       Properties JavaDoc beanProps = new Properties JavaDoc();
609       for(int n = 0; n < properties.getLength(); n ++)
610       {
611          // Skip over non-element nodes
612
Node JavaDoc node = properties.item(n);
613          if (node.getNodeType() != Node.ELEMENT_NODE)
614          {
615             continue;
616          }
617          Element JavaDoc property = (Element JavaDoc) node;
618          String JavaDoc name = property.getAttribute("name");
619          String JavaDoc value = getElementContent(property, trim, replace);
620          beanProps.setProperty(name, value);
621       }
622
623       // Apply the properties to the bean
624
PropertyEditors.mapJavaBeanProperties(bean, beanProps);
625       return bean;
626    }
627
628    /**
629     * Configure the mbean attribute as a bean with the bean unmarshalled from
630     * the attribute xml contents using the JBossXB unmarshaller.
631     *
632     * @param attr - the mbean attribute
633     * @param cl - the class loader to use
634     * @param element - the mbean attribute element from the jboss-service descriptor
635     * @param replace - ignored
636     * @param trim - ignored
637     * @return the configured attribute bean
638     * @throws Exception
639     */

640    private Object JavaDoc parseJbxbSerialData(MBeanAttributeInfo JavaDoc attr, ClassLoader JavaDoc cl,
641       Element JavaDoc element, boolean replace, boolean trim)
642       throws Exception JavaDoc
643    {
644       // Get the attribute element content in a parsable form
645
StringBuffer JavaDoc buffer = getElementContent(element);
646
647       // Parse the attribute element content
648
SchemaBindingResolver resolver = SingletonSchemaResolverFactory.getInstance().getSchemaBindingResolver();
649       Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
650       StringReader JavaDoc reader = new StringReader JavaDoc(buffer.toString());
651       Object JavaDoc bean = unmarshaller.unmarshal(reader, resolver);
652       return bean;
653    }
654
655    private ObjectName JavaDoc processDependency(ObjectName JavaDoc container, ObjectName JavaDoc loaderName,
656       Element JavaDoc element, List JavaDoc<ObjectName JavaDoc> mbeans, boolean replace)
657       throws Exception JavaDoc
658    {
659       ObjectName JavaDoc dependsObjectName = null;
660       NodeList JavaDoc nl = element.getChildNodes();
661       for (int i = 0; i < nl.getLength(); i++)
662       {
663          Node JavaDoc childNode = nl.item(i);
664          if (childNode.getNodeType() == Node.ELEMENT_NODE)
665          {
666             Element JavaDoc child = (Element JavaDoc) childNode;
667             if (child.getTagName().equals("mbean"))
668             {
669                dependsObjectName = internalInstall(child, mbeans, loaderName, replace);
670                break;
671             }
672             else
673             {
674                throw new DeploymentException("Non mbean child element in depends tag: " + child);
675             } // end of else
676
} // end of if ()
677
} // end of for ()
678

679       if (dependsObjectName == null)
680       {
681          String JavaDoc name = getElementContent(element, true, replace);
682          dependsObjectName = ObjectNameFactory.create(name);
683       }
684       if (dependsObjectName == null)
685       {
686          throw new DeploymentException("No object name found for attribute!");
687       } // end of if ()
688

689       serviceController.registerDependency(container, dependsObjectName);
690
691       return dependsObjectName;
692    }
693
694    /**
695     * A helper to deal with those pesky JMX exceptions.
696     */

697    private void setAttribute(ObjectName JavaDoc name, Attribute JavaDoc attr)
698       throws Exception JavaDoc
699    {
700       try
701       {
702          server.setAttribute(name, attr);
703       }
704       catch (Exception JavaDoc e)
705       {
706          throw new DeploymentException("Exception setting attribute " +
707             attr + " on mbean " + name, JMXExceptionDecoder.decode(e));
708       }
709    }
710
711    private Element JavaDoc internalGetConfiguration(Document JavaDoc doc, ObjectName JavaDoc name)
712       throws Exception JavaDoc
713    {
714       Element JavaDoc mbeanElement = doc.createElement("mbean");
715       mbeanElement.setAttribute("name", name.toString());
716
717       MBeanInfo JavaDoc info = server.getMBeanInfo(name);
718       mbeanElement.setAttribute("code", info.getClassName());
719       MBeanAttributeInfo JavaDoc[] attributes = info.getAttributes();
720       boolean trace = log.isTraceEnabled();
721       for (int i = 0; i < attributes.length; i++)
722       {
723          if (trace)
724             log.trace("considering attribute: " + attributes[i]);
725          if (attributes[i].isReadable() && attributes[i].isWritable())
726          {
727             Element JavaDoc attributeElement = null;
728             if (attributes[i].getType().equals("javax.management.ObjectName"))
729             {
730                attributeElement = doc.createElement("depends");
731                attributeElement.setAttribute("optional-attribute-name", attributes[i].getName());
732             }
733             else
734             {
735                attributeElement = doc.createElement("attribute");
736                attributeElement.setAttribute("name", attributes[i].getName());
737             }
738             Object JavaDoc value = server.getAttribute(name, attributes[i].getName());
739
740             if (value != null)
741             {
742                if (value instanceof Element JavaDoc)
743                {
744                   attributeElement.appendChild(doc.importNode((Element JavaDoc) value, true));
745                }
746                else
747                {
748                   attributeElement.appendChild(doc.createTextNode(value.toString()));
749                }
750             }
751             mbeanElement.appendChild(attributeElement);
752          }
753       }
754
755       ServiceContext sc = serviceController.getServiceContext(name);
756       for (Iterator JavaDoc i = sc.iDependOn.iterator(); i.hasNext();)
757       {
758          ServiceContext needs = (ServiceContext) i.next();
759          Element JavaDoc dependsElement = doc.createElement("depends");
760          dependsElement.appendChild(doc.createTextNode(needs.objectName.toString()));
761          mbeanElement.appendChild(dependsElement);
762       }
763
764       return mbeanElement;
765    }
766
767    /**
768     * Parse an object name from the given element attribute 'name'.
769     * @param element Element to parse name from.
770     * @return Object name.
771     * @throws ConfigurationException Missing attribute 'name' (thrown if 'name'
772     * is null or "").
773     * @throws Exception
774     */

775    private ObjectName JavaDoc parseObjectName(final Element JavaDoc element, boolean replace)
776       throws Exception JavaDoc
777    {
778       String JavaDoc name = element.getAttribute("name");
779
780       if (name == null || name.trim().equals(""))
781       {
782          throw new DeploymentException("MBean attribute 'name' must be given.");
783       }
784
785       if (replace)
786          name = StringPropertyReplacer.replaceProperties(name);
787
788       return new ObjectName JavaDoc(name);
789    }
790
791    private String JavaDoc getElementContent(Element JavaDoc element, boolean trim, boolean replace)
792       throws Exception JavaDoc
793    {
794       NodeList JavaDoc nl = element.getChildNodes();
795       String JavaDoc attributeText = "";
796       for (int i = 0; i < nl.getLength(); i++)
797       {
798          Node JavaDoc n = nl.item(i);
799          if (n instanceof Text JavaDoc)
800          {
801             attributeText += ((Text JavaDoc) n).getData();
802          }
803       } // end of for ()
804
if (trim)
805          attributeText = attributeText.trim();
806       if (replace)
807          attributeText = StringPropertyReplacer.replaceProperties(attributeText);
808       return attributeText;
809    }
810
811    /**
812     * A utility method that transforms the contents of the argument element into
813     * a StringBuffer representation that can be reparsed.
814     *
815     * [FIXME] This is not a general DOMUtils method because of its funny contract. It does not
816     * support multiple child elements neither can it deal with text content.
817     *
818     * @param element - the parent dom element whose contents are to be extracted as an xml document string.
819     * @return the xml document string.
820     * @throws IOException for an IO problem
821     * @throws TransformerException for an error during the transformation
822     */

823    public static StringBuffer JavaDoc getElementContent(Element JavaDoc element) throws IOException JavaDoc, TransformerException JavaDoc
824    {
825       NodeList JavaDoc children = element.getChildNodes();
826       Element JavaDoc content = null;
827       for (int n = 0; n < children.getLength(); n++)
828       {
829          Node JavaDoc node = children.item(n);
830          if (node.getNodeType() == Node.ELEMENT_NODE)
831          {
832             content = (Element JavaDoc)node;
833             break;
834          }
835       }
836       if (content == null)
837          return null;
838
839       // Get a parsable representation of this elements content
840
DOMSource JavaDoc source = new DOMSource JavaDoc(content);
841       TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
842       Transformer JavaDoc transformer = tFactory.newTransformer();
843       StringWriter JavaDoc sw = new StringWriter JavaDoc();
844       StreamResult JavaDoc result = new StreamResult JavaDoc(sw);
845       transformer.transform(source, result);
846       sw.close();
847       return sw.getBuffer();
848    }
849 }
Popular Tags