User: user57  
  Date: 01/04/25 13:09:01

  Modified:    src/main/org/jboss/configuration ConfigurationService.java
                        ConfigurationServiceMBean.java
  Added:       src/main/org/jboss/configuration package.html
  Log:
   o Modified to auto-trim by default.  Read changelog for more information.
   o Added Javadoc comments for most members.
   o Added package documentation.
   o Using logException() in all cases where partial decoding of JMX exceptions
  
  Revision  Changes    Path
  1.27      +519 -422  jboss/src/main/org/jboss/configuration/ConfigurationService.java
  
  Index: ConfigurationService.java
  ===================================================================
  RCS file: 
/cvsroot/jboss/jboss/src/main/org/jboss/configuration/ConfigurationService.java,v
  retrieving revision 1.26
  retrieving revision 1.27
  diff -u -r1.26 -r1.27
  --- ConfigurationService.java 2001/04/21 07:24:49     1.26
  +++ ConfigurationService.java 2001/04/25 20:09:00     1.27
  @@ -30,7 +30,7 @@
   import org.jboss.util.ServiceMBeanSupport;
   import org.jboss.util.XmlHelper;
   
  -/** 
  +/**
    * The ConfigurationService MBean is loaded when JBoss starts up by the
    * JMX MLet.
    *
  @@ -45,37 +45,61 @@
    * @author  Rickard �berg ([EMAIL PROTECTED])
    * @author  [EMAIL PROTECTED]
    * @author  Jason Dillon <a 
href="mailto:[EMAIL PROTECTED]";>&lt;[EMAIL PROTECTED]&gt;</a>
  - * @version $Revision: 1.26 $
  + * @version $Revision: 1.27 $
    */
   public class ConfigurationService
  -   extends ServiceMBeanSupport
  -   implements ConfigurationServiceMBean
  +    extends ServiceMBeanSupport
  +    implements ConfigurationServiceMBean
   {
  -    // Constants -----------------------------------------------------
  +    /** The name of the file initial configuration is read from. */
  +    public static final String CONFIGURATION_FILE = "jboss.jcml";
  +
  +    /** The name of the file that running state will be written into. */
  +    public static final String RUNNING_STATE_FILE = "jboss-auto.jcml";
  +    
  +    /** Primitive type name -> class map. */
       private static Hashtable primitives = new Hashtable();
  +    
  +    /** Setup the primitives map. */
  +    static {
  +        primitives.put("int", Integer.TYPE);
  +        primitives.put("boolean", Boolean.TYPE);
  +        primitives.put("double", Double.TYPE);
  +        primitives.put("float", Float.TYPE);
  +        primitives.put("long", Long.TYPE);
  +    }
  +    
  +    /**
  +     * A mapping from the Service interface method names to the
  +     * corresponding index into the ServiceProxy.hasOp array.
  +     */
  +    private static HashMap serviceOpMap = new HashMap();
   
  -    static
  -    {
  -        primitives.put("int",Integer.TYPE);
  -        primitives.put("boolean",Boolean.TYPE);
  -        primitives.put("double",Double.TYPE);
  -        primitives.put("float",Float.TYPE);
  -        primitives.put("long",Long.TYPE);
  +    /**
  +     * Initialize the service operation map.
  +     */
  +    static {
  +        serviceOpMap.put("init", new Integer(0));
  +        serviceOpMap.put("start", new Integer(1));
  +        serviceOpMap.put("destroy", new Integer(2));
  +        serviceOpMap.put("stop", new Integer(3));
       }
  +    
   
  -    // Attributes ----------------------------------------------------
  +    /** Instance logger. */
       private final Log log = Log.createLog(getName());
  -
  +    
  +    /** The MBean server which this service is registered in. */
       private MBeanServer server;
  +    
  +    /** The name of the ServiceControl service. */
       private ObjectName serviceControl;
  -
  +    
       /** Flag to indicate if attribute values should be automatically trimmed. */
       private boolean autoTrim;
  -   
  -    // Static --------------------------------------------------------
  -
  +    
       // Constructors --------------------------------------------------
  -
  +    
       /**
        * Construct a <tt>ConfigurationService</tt>.
        *
  @@ -84,17 +108,17 @@
       public ConfigurationService(final boolean autoTrim) {
           this.autoTrim = autoTrim;
       }
  -
  +    
       /**
  -     * Construct a <tt>ConfigurationService</tt> that will not auto-trim
  +     * Construct a <tt>ConfigurationService</tt> that auto-trim
        * attribute values.
        */
       public ConfigurationService() {
  -        this(false);
  +        this(true);
       }
  -   
  +    
       // Public --------------------------------------------------------
  -
  +    
       /**
        * Get the attribute value auto-trim flag.
        *
  @@ -103,580 +127,653 @@
       public boolean getAutoTrim() {
           return autoTrim;
       }
  -
  +    
  +    /**
  +     * Get the name of this object.  Always ignores the given
  +     * object name.
  +     *
  +     * @param server    The server which the object is registered in.
  +     * @param name      The user specified object name (ignored).
  +     * @return          The name of this object.
  +     */
       public ObjectName getObjectName(MBeanServer server, ObjectName name)
  -        throws javax.management.MalformedObjectNameException
  +        throws MalformedObjectNameException
       {
           this.server = server;
           return new ObjectName(OBJECT_NAME);
       }
   
  -    public String getName()
  -    {
  -       return "Configuration";
  +    /**
  +     * Return the name of the service.
  +     *
  +     * @return  Always "Configuration".
  +     */
  +    public String getName() {
  +        return "Configuration";
       }
   
  -    public void load(Document configuration)
  -        throws Exception
  -    {
  +    /**
  +     * Parses the given configuration document and sets MBean attributes.
  +     *
  +     * @param configuration     The parsed configuration document.
  +     *
  +     * @throws Exception        Failed to load.
  +     */
  +    public void load(Document configuration) throws Exception {
           // Get the ServiceControl MBean
           serviceControl = new ObjectName(server.getDefaultDomain(), "service", 
"ServiceControl");
  -        if( server.isRegistered(serviceControl) == false )
  -            throw new IllegalStateException("Failed to find ServiceControl mbean, 
name="+serviceControl);
  -
  -        try
  -        {          
  +        if (server.isRegistered(serviceControl) == false)
  +            throw new IllegalStateException
  +                ("Failed to find ServiceControl mbean, name=" + serviceControl);
  +            
  +        try {
               // Set configuration to MBeans from XML
               NodeList nl = configuration.getElementsByTagName("mbean");
  -            for (int i = 0; i < nl.getLength(); i++)
  -            {
  +            for (int i = 0; i < nl.getLength(); i++) {
                   Element mbeanElement = (Element)nl.item(i);
  -
  -                // get the name of the mbean 
  +                
  +                // get the name of the mbean
                   ObjectName objectName = parseObjectName(mbeanElement);
                   MBeanInfo info;
  -                try
  -                {
  +                try {
                       info = server.getMBeanInfo(objectName);
  -                } catch (InstanceNotFoundException e)
  -                {
  -                  // The MBean is no longer available
  -                  // It's ok, skip to next one
  -                  continue;
  +                } catch (InstanceNotFoundException e) {
  +                    // The MBean is no longer available
  +                    // It's ok, skip to next one
  +                    continue;
                   }
                   
                   // Set attributes
                   NodeList attrs = mbeanElement.getElementsByTagName("attribute");
  -                for (int j = 0; j < attrs.getLength(); j++)
  -                {
  +                for (int j = 0; j < attrs.getLength(); j++) {
                       Element attributeElement = (Element)attrs.item(j);
                       String attributeName = attributeElement.getAttribute("name");
  -                    if (attributeElement.hasChildNodes())
  -                    {
  +                    if (attributeElement.hasChildNodes()) {
                           String attributeValue = 
((Text)attributeElement.getFirstChild()).getData();
  -
  +                        
                           if (autoTrim) {
                               attributeValue = attributeValue.trim();
                           }
                           
                           MBeanAttributeInfo[] attributes = info.getAttributes();
  -                        for (int k = 0; k < attributes.length; k++)
  -                        {
  -                            if (attributeName.equals(attributes[k].getName()))
  -                            {
  +                        for (int k = 0; k < attributes.length; k++) {
  +                            if (attributeName.equals(attributes[k].getName())) {
                                   String typeName = attributes[k].getType();
                                   Class typeClass;
  -                                if (primitives.containsKey(typeName))
  -                                {
  +                                if (primitives.containsKey(typeName)) {
                                       typeClass = (Class)primitives.get(typeName);
  -                                } else
  -                                {
  +                                } else {
                                       typeClass = Class.forName(typeName);
                                   }
                                   PropertyEditor editor = 
PropertyEditorManager.findEditor(typeClass);
                                   editor.setAsText(attributeValue);
                                   Object value = editor.getValue();
  -
  -                                log.debug(attributeName +" set to 
"+attributeValue+" in "+objectName);
  +                                
  +                                log.debug(attributeName + " set to " + 
attributeValue + " in " + objectName);
                                   server.setAttribute(objectName, new 
Attribute(attributeName, value));
  -
  +                                
                                   break;
                               }
                           }
                       }
  -
                   }
  -
  +                
                   // Register the mbean with the JBoss ServiceControl mbean
                   registerService(objectName, info, mbeanElement);
  -            }
  -        } catch (Throwable e)
  -        {
  -            if (e instanceof RuntimeMBeanException)
  -            {
  -               e = ((RuntimeMBeanException)e).getTargetException();
  -            }
  -            else if( e instanceof MBeanException)
  -            {
  -               e = ((MBeanException)e).getTargetException();
               }
  +        }
  +        catch (Throwable e) {
  +            logException(e);
   
  -            Log.getLog().exception(e);
  +            // yikes this is not too safe
               throw (Exception)e;
           }
       }
   
  -   public String save()
  -        throws Exception
  -   {
  +    /**
  +     * Builds a string that consists of the configuration elements of
  +     * the currently running MBeans registered in the server.
  +     *
  +     * @throws Exception    Failed to construct configuration.
  +     */
  +    public String save() throws Exception {
           Writer out = new StringWriter();
  -
  +        
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = factory.newDocumentBuilder();
           Document doc = builder.newDocument();
  -
  +        
           Element serverElement = doc.createElement("server");
  -
  +        
           // Store attributes as XML
           Iterator mbeans = server.queryMBeans(null, null).iterator();
  -        while (mbeans.hasNext())
  -        {
  +        while (mbeans.hasNext()) {
               ObjectInstance instance = (ObjectInstance)mbeans.next();
               ObjectName name = (ObjectName)instance.getObjectName();
               Element mbeanElement = doc.createElement("mbean");
  -            mbeanElement.setAttribute("name",name.toString());
  -
  +            mbeanElement.setAttribute("name", name.toString());
  +            
               MBeanInfo info = server.getMBeanInfo(name);
  -            mbeanElement.setAttribute("code",info.getClassName());
  +            mbeanElement.setAttribute("code", info.getClassName());
               MBeanAttributeInfo[] attributes = info.getAttributes();
               boolean hasAttributes = true;
  -            for (int i = 0; i < attributes.length; i++)
  -            {
  -                if (attributes[i].isReadable() && 
isAttributeWriteable(server.getObjectInstance(name).getClassName(), 
attributes[i].getName(), attributes[i].getType()))
  -                {
  -                    if(!attributes[i].isWritable())
  -                        log.debug("Detected JMX Bug: Server reports attribute 
'"+attributes[i].getName()+"' is not writeable for MBean 
'"+name.getCanonicalName()+"'");
  +            for (int i = 0; i < attributes.length; i++) {
  +                if (attributes[i].isReadable() && 
isAttributeWriteable(server.getObjectInstance(name).getClassName(), 
attributes[i].getName(), attributes[i].getType())) {
  +                    if (!attributes[i].isWritable()) {
  +                        log.debug("Detected JMX Bug: Server reports attribute 
'"+attributes[i].getName() + "' is not writeable for MBean '" + 
name.getCanonicalName() + "'");
  +                    }
                       Element attributeElement = doc.createElement("attribute");
                       Object value = server.getAttribute(name, 
attributes[i].getName());
  -
  +                    
                       attributeElement.setAttribute("name", attributes[i].getName());
  -
  -                    if (value != null)
  +                    
  +                    if (value != null) {
                           
attributeElement.appendChild(doc.createTextNode(value.toString()));
  -
  +                    }
  +                        
                       mbeanElement.appendChild(attributeElement);
  -
                       hasAttributes = true;
                   }
               }
  -
  -            if (hasAttributes)
  +            
  +            if (hasAttributes) {
                   serverElement.appendChild(mbeanElement);
  +            }
           }
  -
  +        
           doc.appendChild(serverElement);
  -
  +        
           // Write configuration
           XmlHelper.write(out, doc);
  -
  +        
           out.close();
  -
  +        
           // Return configuration
           return out.toString();
  -   }
  +    }
   
  -   public void saveConfiguration()
  -      throws Exception
  -   {
  -      // Get XML
  -      String xml = save();
  -
  -      // Get JCML file
  -      URL confFile = 
Thread.currentThread().getContextClassLoader().getResource("jboss-auto.jcml");
  -
  -      if (confFile != null)
  -      {
  -         // Store to auto-saved JCML file
  -         PrintWriter out = null;
  -         try {
  -             out = new PrintWriter(new FileOutputStream(confFile.getFile()));
  -          } catch (java.io.FileNotFoundException e) {
  -           log.error("Configuration file "+confFile.getFile()+" must be available 
and writable.");
  -           log.exception(e);
  -          }
  -          out.print(xml);
  -          out.close();
  -      }
  -   }
  +    /**
  +     * Saves the current configuration of each registered MBean to
  +     * the {@link #RUNNING_STATE_FILE} file.  This will only occur if
  +     * a file of the that name exists in the classpath.
  +     *
  +     * @throws Exception    Failed to save configuration.
  +     */
  +    public void saveConfiguration() throws Exception {
  +        // Get XML
  +        String xml = save();
  +        
  +        // Get JCML file
  +        ClassLoader loader = Thread.currentThread().getContextClassLoader();
  +        URL confFile = loader.getResource(RUNNING_STATE_FILE);
  +        
  +        if (confFile != null) {
  +            // Store to auto-saved JCML file
  +            PrintWriter out = null;
  +            try {
  +                out = new PrintWriter(new FileOutputStream(confFile.getFile()));
  +                out.print(xml);
  +            }
  +            catch (FileNotFoundException e) {
  +                log.error("Configuration file " + confFile.getFile() +
  +                          " must be available and writable.");
  +                log.exception(e);
  +            }
  +            finally {
  +                out.close();
  +            }
  +        }
  +    }
  +    
  +    /**
  +     * Load the configuration from the {@link #CONFIGURATION_FILE},
  +     * installs and initailize configured MBeans and registeres the
  +     * beans as services.
  +     *
  +     * <p>This is a 2-step process:
  +     * <ol>
  +     *   <li>Load user conf. and create MBeans from that.
  +     *   <li>Apply user conf to created MBeans.
  +     * </ol>
  +     *
  +     * @throws Exception    ???
  +     */
  +    public void loadConfiguration() throws Exception {
  +        // The class loader used to kocal the configuration file
  +        ClassLoader loader = Thread.currentThread().getContextClassLoader();
  +        
  +        // Load user config from XML, and create the MBeans
  +        InputStream input = loader.getResourceAsStream(CONFIGURATION_FILE);
  +        String data = null;
  +        try {
  +            byte[] buffer = new byte[input.available()];
  +            input.read(buffer);
  +            data = new String(buffer);
  +        }
  +        finally {
  +            input.close();
  +        }
  +        
  +        // Parse XML
  +        Document doc;
  +        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  +        DocumentBuilder parser = factory.newDocumentBuilder();
  +        
  +        try {
  +            doc = parser.parse(new InputSource(new StringReader(data)));
  +        } catch (SAXException e) {
  +            throw new IOException(e.getMessage());
  +        }
   
  -    public void loadConfiguration()
  -       throws Exception
  -    {
  -      // This is a 2-step process
  -      // 1) Load user conf. and create MBeans from that
  -      // 2) Apply user conf to created MBeans
  -
  -       // Load user config from XML, and create the MBeans
  -       InputStream conf = 
Thread.currentThread().getContextClassLoader().getResourceAsStream("jboss.jcml");
  -       byte[] arr = new byte[conf.available()];
  -       conf.read(arr);
  -       conf.close();
  -       String cfg = new String(arr);
  -
  -       // Parse XML
  -       Document userConf;
  -       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  -       DocumentBuilder parser = factory.newDocumentBuilder();
  -
  -
  -       try
  -       {
  -           userConf = parser.parse(new InputSource(new StringReader(cfg)));
  -       }
  -       catch (SAXException se)
  -       {
  -            throw new IOException(se.getMessage());
  -       }
  -
  -       create(userConf);
  -
  -       // Apply user conf
  -       conf = 
Thread.currentThread().getContextClassLoader().getResourceAsStream("jboss.jcml");
  -       arr = new byte[conf.available()];
  -       conf.read(arr);
  -       conf.close();
  -       cfg = new String(arr);
  +        // create mbeans for the parsed configuration
  +        create(doc);
   
  -       load(userConf);
  +        // load each created mbean, set attributes and register services
  +        load(doc);
       }
  -
  +    
       // Protected -----------------------------------------------------
  -
  -   /**
  -    * Parse an object name from the given element attribute 'name'.
  -    *
  -    * @param element    Element to parse name from.
  -    * @return           Object name.
  -    * 
  -    * @throws ConfigurationException   Missing attribute 'name'
  -    *                                  (thrown if 'name' is null or "").
  -    * @throws MalformedObjectNameException
  -    */
  -   protected ObjectName parseObjectName(final Element element) 
  -      throws ConfigurationException, MalformedObjectNameException
  -   {
  -      String name = element.getAttribute("name");
  -      if (name == null || name.trim().equals("")) {
  -         throw new ConfigurationException
  -            ("MBean attribute 'name' must be given.");
  -      }
  -
  -      return new ObjectName(name);
  -   }
  -
  -   /**
  -    * Provides a wrapper around the information about which constructor 
  -    * that MBeanServer should use to construct a MBean.
  -    *
  -    * <p>XML syntax for contructor:
  -    *   <pre>
  -    *      <constructor>
  -    *         <arg type="xxx" value="yyy"/>
  -    *         ...
  -    *         <arg type="xxx" value="yyy"/>
  -    *      </constructor>
  -    *   </pre>
  -    */
  -   protected static class ConstructorInfo
  -   {
  -      public static final Object EMPTY_PARAMS[] = {};
  -      public static final String EMPTY_SIGNATURE[] = {};
  -
  -      /** The constructor signature. */
  -      public String[] signature = EMPTY_SIGNATURE;
  -
  -      /** The constructor parameters. */
  -      public Object[] params = EMPTY_PARAMS;
  -       
  -      /**
  -       * Create a ConstructorInfo object for the given configuration.
  -       *
  -       * @param element   The element to build info for.
  -       * @return          A constructor information object.
  -       *
  -       * @throws ConfigurationException   Failed to create info object.
  -       */
  -      public static ConstructorInfo create(Element element)
  -         throws ConfigurationException
  -      {
  -         ConstructorInfo info = new ConstructorInfo();
  -
  -         NodeList list = element.getElementsByTagName("constructor");
  -         if (list.getLength() > 1) {
  +    
  +    /**
  +     * Parse an object name from the given element attribute 'name'.
  +     *
  +     * @param element    Element to parse name from.
  +     * @return           Object name.
  +     * 
  +     * @throws ConfigurationException   Missing attribute 'name'
  +     *                                  (thrown if 'name' is null or "").
  +     * @throws MalformedObjectNameException
  +     */
  +    private ObjectName parseObjectName(final Element element)
  +        throws ConfigurationException, MalformedObjectNameException
  +    {
  +        String name = element.getAttribute("name");
  +        if (name == null || name.trim().equals("")) {
               throw new ConfigurationException
  -               ("only one <constructor> element may be defined");
  -         }
  -         else if (list.getLength() == 1) {
  -            element = (Element)list.item(0);
  -             
  -            // get all of the "arg" elements
  -            list = element.getElementsByTagName("arg");
  -            int length = list.getLength();
  -            info.params = new Object[length];
  -            info.signature = new String[length];
  -             
  -            // decode the values into params & signature
  -            for (int j=0; j<length; j++) {
  -               Element arg = (Element)list.item(j);
  -               //
  -               // NOTE: should coerce value to the correct type??
  -               //
  -               info.signature[j] = arg.getAttribute("type");
  -               info.params[j] = arg.getAttribute("value");
  -            }
  -         }
  -          
  -         return info;
  -      }
  -   }
  -
  -    protected void create(Document configuration)
  -        throws Exception
  +            ("MBean attribute 'name' must be given.");
  +        }
  +        
  +        return new ObjectName(name);
  +    }
  +    
  +    /**
  +     * Provides a wrapper around the information about which constructor 
  +     * that MBeanServer should use to construct a MBean.
  +     *
  +     * <p>XML syntax for contructor:
  +     *   <pre>
  +     *      <constructor>
  +     *         <arg type="xxx" value="yyy"/>
  +     *         ...
  +     *         <arg type="xxx" value="yyy"/>
  +     *      </constructor>
  +     *   </pre>
  +     */
  +    private static class ConstructorInfo
       {
  -        try
  +        /** An empty parameters list. */
  +        public static final Object EMPTY_PARAMS[] = {};
  +
  +        /** An signature list. */
  +        public static final String EMPTY_SIGNATURE[] = {};
  +        
  +        /** The constructor signature. */
  +        public String[] signature = EMPTY_SIGNATURE;
  +        
  +        /** The constructor parameters. */
  +        public Object[] params = EMPTY_PARAMS;
  +        
  +        /**
  +         * Create a ConstructorInfo object for the given configuration.
  +         *
  +         * @param element   The element to build info for.
  +         * @return          A constructor information object.
  +         *
  +         * @throws ConfigurationException   Failed to create info object.
  +         */
  +        public static ConstructorInfo create(Element element)
  +            throws ConfigurationException
           {
  +            ConstructorInfo info = new ConstructorInfo();
  +            
  +            NodeList list = element.getElementsByTagName("constructor");
  +            if (list.getLength() > 1) {
  +                throw new ConfigurationException
  +                ("only one <constructor> element may be defined");
  +            }
  +            else if (list.getLength() == 1) {
  +                element = (Element)list.item(0);
  +                
  +                // get all of the "arg" elements
  +                list = element.getElementsByTagName("arg");
  +                int length = list.getLength();
  +                info.params = new Object[length];
  +                info.signature = new String[length];
  +                
  +                // decode the values into params & signature
  +                for (int j=0; j<length; j++) {
  +                    Element arg = (Element)list.item(j);
  +                    //
  +                    // NOTE: should coerce value to the correct type??
  +                    //
  +                    info.signature[j] = arg.getAttribute("type");
  +                    info.params[j] = arg.getAttribute("value");
  +                }
  +            }
  +            
  +            return info;
  +        }
  +    }
  +    
  +    /**
  +     * Parses the given configuration document and creates MBean
  +     * instances in the current MBean server.
  +     *
  +     * @param configuration     The configuration document.
  +     *
  +     * @throws ConfigurationException   The configuration document contains
  +     *                                  invalid or missing syntax.
  +     * @throws Exception                Failed for some other reason.
  +     */
  +    private void create(Document configuration) throws Exception {
  +        try {
  +            ObjectName loader =
  +                new ObjectName(server.getDefaultDomain(), "service", "MLet");
  +            
               // Set configuration to MBeans from XML
               NodeList nl = configuration.getElementsByTagName("mbean");
  -            for (int i = 0; i < nl.getLength(); i++)
  -            {
  +            for (int i = 0; i < nl.getLength(); i++) {
                   Element mbeanElement = (Element)nl.item(i);
  -
  -                // get the name of the mbean 
  +                
  +                // get the name of the mbean
                   ObjectName objectName = parseObjectName(mbeanElement);
  -
  +                
                   MBeanInfo info;
                   try {
                       info = server.getMBeanInfo(objectName);
  -                } catch (InstanceNotFoundException e)
  -                {
  -                  // The MBean is no longer available
  -                  // If class is given, instantiate it
  -                  String code = mbeanElement.getAttribute("code");
  -                  if (code != null)
  -                  {
  -                     try
  -                     {
  +                } catch (InstanceNotFoundException e) {
  +                    // The MBean is no longer available
  +                    // If class is given, instantiate it
  +                    String code = mbeanElement.getAttribute("code");
  +                    if (code == null) {
  +                        throw new ConfigurationException
  +                            ("missing 'code' attribute");
  +                    }
  +                    
  +                    try {
                           // get the constructor params/sig to use
  -                        ConstructorInfo constructor = 
  -                           ConstructorInfo.create(mbeanElement);
  -
  -                        // Could probably cache this value
  -                        ObjectName loader = new 
ObjectName(server.getDefaultDomain(), "service", "MLet");
  -
  +                        ConstructorInfo constructor =
  +                            ConstructorInfo.create(mbeanElement);
  +                        
                           // Create the MBean instance
  -                        ObjectInstance instance = 
  -                           server.createMBean(code, 
  -                                              objectName, 
  -                                              loader, 
  -                                              constructor.params, 
  -                                              constructor.signature);
  +                        ObjectInstance instance =
  +                            server.createMBean(code,
  +                                               objectName,
  +                                               loader,
  +                                               constructor.params,
  +                                               constructor.signature);
                           info = server.getMBeanInfo(instance.getObjectName());
  -                     } catch (Throwable ex)
  -                     {
  -                        log.error("Could not create MBean 
"+objectName+"("+code+")");
  +                    } catch (Throwable ex) {
  +                        log.error("Could not create MBean " +
  +                                  objectName + "(" + code + ")");
                           logException(ex);
  -
  +                        
                           // Ah what the heck.. skip it
                           continue;
  -                     }
  -                  } else
  -                  {
  -                     // No code attribute given - can't instantiate
  -                     // it's ok, skip to next one
  -                     continue;
  -                  }
  +                    }
                   }
  -            }
  -        } catch (Throwable e)
  -        {
  -            if (e instanceof RuntimeMBeanException)
  -            {
  -               e = ((RuntimeMBeanException)e).getTargetException();
  +
  +                // info is not being used
               }
  +        } catch (Throwable e) {
  +            logException(e);
   
  -            Log.getLog().exception(e);
  +            // yikes this is not too safe
               throw (Exception)e;
           }
       }
  -
  -    private boolean isAttributeWriteable(String className, String attribute, String 
type) {
  +    
  +    /**
  +     * Checks if an attribute of a given class is writtable.
  +     *
  +     * @param className     The name of the class to check.
  +     * @param attribute     The name of the attribute to check.
  +     * @param type          The attribute type that the setter takes.
  +     *
  +     * @throws Exception    Unable to determin if attribute is writable.
  +     */
  +    private boolean isAttributeWriteable(final String className,
  +                                         final String attribute,
  +                                         final String type)
  +    {
           Class arg = null;
           Class cls = null;
           try {
  -            if(type.equals("int"))
  +            if (type.equals("int"))
                   arg = Integer.TYPE;
  -            else if(type.equals("boolean"))
  +            else if (type.equals("boolean"))
                   arg = Boolean.TYPE;
  -            else if(type.equals("float"))
  +            else if (type.equals("float"))
                   arg = Float.TYPE;
  -            else if(type.equals("byte"))
  +            else if (type.equals("byte"))
                   arg = Byte.TYPE;
  -            else if(type.equals("short"))
  +            else if (type.equals("short"))
                   arg = Short.TYPE;
  -            else if(type.equals("char"))
  +            else if (type.equals("char"))
                   arg = Character.TYPE;
  -            else if(type.equals("long"))
  +            else if (type.equals("long"))
                   arg = Long.TYPE;
  -            else if(type.equals("double"))
  +            else if (type.equals("double"))
                   arg = Double.TYPE;
  -            else arg = Class.forName(type);
  -        } catch(ClassNotFoundException e) {
  -            log.error("Unable to check parameter of type '"+type+"'");
  +            else
  +                arg = Class.forName(type);
  +        } catch (ClassNotFoundException e) {
  +            log.error("Unable to check parameter of type '" + type + "'");
               return false;
           }
  +        
           try {
               cls = Class.forName(className);
  -        } catch(ClassNotFoundException e) {
  -            log.error("Unable to check MBean of type '"+className+"'");
  +        } catch (ClassNotFoundException e) {
  +            log.error("Unable to check MBean of type '" + className + "'");
               return false;
           }
  +
           try {
  -            Method m = cls.getMethod("set"+attribute, new Class[]{arg});
  -            return m != null && Modifier.isPublic(m.getModifiers()) && 
!Modifier.isStatic(m.getModifiers()) && m.getReturnType().equals(Void.TYPE);
  -        } catch(NoSuchMethodException e) {}
  +            Method m = cls.getMethod("set" + attribute, new Class[] { arg });
  +            return isSetterMethod(m);
  +        } catch (NoSuchMethodException ignore) {}
  +        
           return false;
       }
  +
  +    /**
  +     * Check if the given method is a "setter" method.
  +     *
  +     * @param m     The method to check.
  +     * @return      True if the method is a "setter" method.
  +     */
  +    private boolean isSetterMethod(final Method m) {
  +        if (m != null) {
  +            return
  +                Modifier.isPublic(m.getModifiers()) &&
  +                !Modifier.isStatic(m.getModifiers()) &&
  +                m.getReturnType().equals(Void.TYPE);
  +        }
   
  -    /** Register the mbean given by objectName with the ServiceControl service.
  -    */
  -    void registerService(ObjectName objectName, MBeanInfo info, Element 
mbeanElement)
  +        return false;
  +    }
  +    
  +    /**
  +     * Register the mbean given by objectName with the ServiceControl service.
  +     *
  +     * @param objectName
  +     * @param info
  +     * @param mbeanElement
  +     *
  +     * @throws ClassNotFoundException
  +     * @throws InstantiationException
  +     * @throws IllegalAccessException
  +     */
  +    private void registerService(ObjectName objectName,
  +                                 MBeanInfo info,
  +                                 Element mbeanElement)
           throws ClassNotFoundException, InstantiationException, 
IllegalAccessException
       {
           // Check for a serviceFactory attribute
           String serviceFactory = mbeanElement.getAttribute("serviceFactory");
           Service service = getServiceInstance(objectName, info, serviceFactory);
  -        if( service != null )
  -        {
  -            Object[] args = {service};
  -            String[] signature = {"org.jboss.util.Service"};
  -            try
  -            {
  +        
  +        if (service != null) {
  +            Object[] args = { service };
  +            String[] signature = { "org.jboss.util.Service" };
  +            try {
                   server.invoke(serviceControl, "register", args, signature);
  -            }
  -            catch(Exception e)
  -            {
  +            } catch (Exception e) {
                   logException(e);
               }
           }
       }
  -
  -    /** Get the Service interface through which the mbean given by objectName will
  -        be managed.
  -    */
  -    Service getServiceInstance(ObjectName objectName, MBeanInfo info, String 
serviceFactory)
  +    
  +    /**
  +     * Get the Service interface through which the mbean given by 
  +     * objectName will be managed.
  +     * 
  +     * @param objectName
  +     * @param info
  +     * @param serviceFactory
  +     *
  +     * @throws ClassNotFoundException
  +     * @throws InstantiationException
  +     * @throws IllegalAccessException
  +     */
  +    private Service getServiceInstance(ObjectName objectName,
  +                                         MBeanInfo info,
  +                                         String serviceFactory)
           throws ClassNotFoundException, InstantiationException, 
IllegalAccessException
       {
           Service service = null;
           ClassLoader loader = Thread.currentThread().getContextClassLoader();
  -        if( serviceFactory != null && serviceFactory.length() > 0 )
  -        {
  +        if (serviceFactory != null && serviceFactory.length() > 0) {
               Class clazz = loader.loadClass(serviceFactory);
               ServiceFactory factory = (ServiceFactory) clazz.newInstance();
               service = factory.createService(server, objectName);
  -        }
  -        else
  -        {
  +        } else {
               MBeanOperationInfo[] opInfo = info.getOperations();
               Class[] interfaces = { org.jboss.util.Service.class };
               InvocationHandler handler = new ServiceProxy(objectName, opInfo);
               service = (Service) Proxy.newProxyInstance(loader, interfaces, handler);
           }
  +        
           return service;
       }
  -
  -    /** A mapping from the Service interface method names to the
  -    corresponding index into the ServiceProxy.hasOp array.
  -    */
  -    static HashMap serviceOpMap = new HashMap();
  -    static
  -    {
  -        serviceOpMap.put("init", new Integer(0));
  -        serviceOpMap.put("start", new Integer(1));
  -        serviceOpMap.put("destroy", new Integer(2));
  -        serviceOpMap.put("stop", new Integer(3));
  +    
  +    /**
  +     * Go through the myriad of nested JMX exception to pull out the
  +     * true exception if possible and log it.
  +     *
  +     * @param e     The exception to be logged.
  +     */
  +    private void logException(Throwable e) {
  +        if (e instanceof RuntimeErrorException) {
  +            e = ((RuntimeErrorException)e).getTargetError();
  +        } else if (e instanceof RuntimeMBeanException) {
  +            e = ((RuntimeMBeanException)e).getTargetException();
  +        } else if (e instanceof RuntimeOperationsException) {
  +            e = ((RuntimeOperationsException)e).getTargetException();
  +        } else if (e instanceof MBeanException) {
  +            e = ((MBeanException)e).getTargetException();
  +        } else if (e instanceof ReflectionException) {
  +            e = ((ReflectionException)e).getTargetException();
  +        }
  +        
  +        log.exception(e);
       }
  -    /** An implementation of InvocationHandler used to proxy of the Service
  -    interface for mbeans. It determines which of the init/start/stop/destroy
  -    methods of the Service interface an mbean implements by inspecting its
  -    MBeanOperationInfo values. Each Service interface method that has a
  -    matching operation is forwarded to the mbean by invoking the method
  -    through the MBeanServer object.
  -    */
  -    class ServiceProxy implements InvocationHandler
  -    {
   
  -        private boolean[] hasOp = {false, false, false, false};
  +    /**
  +     * An implementation of InvocationHandler used to proxy of the Service
  +     * interface for mbeans. It determines which of the init/start/stop/destroy
  +     * methods of the Service interface an mbean implements by inspecting its
  +     * MBeanOperationInfo values. Each Service interface method that has a
  +     * matching operation is forwarded to the mbean by invoking the method
  +     * through the MBeanServer object.
  +     */
  +    private class ServiceProxy implements InvocationHandler
  +    {
  +        private boolean[] hasOp = { false, false, false, false };
           private ObjectName objectName;
  -
  -        /** Go through the opInfo array and for each operation that
  -        matches on of the Service interface methods set the corresponding
  -        hasOp array value to true.
  -        */
  -        ServiceProxy(ObjectName objectName, MBeanOperationInfo[] opInfo)
  +        
  +        /**
  +         * Go through the opInfo array and for each operation that
  +         * matches on of the Service interface methods set the corresponding
  +         * hasOp array value to true.
  +         *
  +         * @param objectName
  +         * @param opInfo
  +         */
  +        public ServiceProxy(ObjectName objectName,
  +                            MBeanOperationInfo[] opInfo)
           {
               this.objectName = objectName;
               int opCount = 0;
  -            for(int op = 0; op < opInfo.length; op ++)
  -            {
  +            
  +            for (int op = 0; op < opInfo.length; op ++) {
                   MBeanOperationInfo info = opInfo[op];
                   String name = info.getName();
                   Integer opID = (Integer) serviceOpMap.get(name);
  -                if( opID == null )
  -                   continue;
  -
  +                if (opID == null) {
  +                    continue;
  +                }
  +                    
                   // Validate that is a no-arg void return type method
  -                if( info.getReturnType().equals("void") == false )
  +                if (info.getReturnType().equals("void") == false)
                       continue;
  -                if( info.getSignature().length != 0 )
  +                if (info.getSignature().length != 0)
                       continue;
  +                
                   hasOp[opID.intValue()] = true;
  -                opCount ++;
  +                opCount++;
               }
  -            // Log a warning if the mbean does not implement any Service methods
  -            if( opCount == 0 )
  -                log.warning(objectName+" does not implement any Service methods");
  +            
  +            // Log a warning if the mbean does not implement
  +            // any Service methods
  +            if (opCount == 0)
  +                log.warning(objectName +
  +                            " does not implement any Service methods");
           }
  -
  -        /** Map the method name to a Service interface method index and
  -        if the corresponding hasOp array element is true, dispatch the
  -        method to the mbean we are proxying.
  -        @return null always.
  -        */
  -        public Object invoke(Object proxy, Method method, Object[] args) throws 
Throwable
  +        
  +        /**
  +         * Map the method name to a Service interface method index and
  +         * if the corresponding hasOp array element is true, dispatch the
  +         * method to the mbean we are proxying.
  +         *
  +         * @param proxy
  +         * @param method
  +         * @param args
  +         * @return              Always null.
  +         *
  +         * @throws Throwable
  +         */
  +        public Object invoke(Object proxy, Method method, Object[] args)
  +            throws Throwable
           {
               String name = method.getName();
               Integer opID = (Integer) serviceOpMap.get(name);
  -            if( opID != null && hasOp[opID.intValue()] == true )
  -            {
  -                try
  -                {
  -                    String[] sig = {};
  +            
  +            if (opID != null && hasOp[opID.intValue()] == true ) {
  +                try {
  +                    String[] sig = {}
  +                                   ;
                       server.invoke(objectName, name, args, sig);
  -                }
  -                catch(JMRuntimeException e)
  -                {
  +                } catch (JMRuntimeException e) {
                       logException(e);
                   }
  -                catch(JMException e)
  -                {
  +                catch (JMException e) {
                       logException(e);
                   }
               }
  +            
               return null;
           }
       }
  -
  -   /** 
  -    * Go through the myriad of nested JMX exception to pull out the
  -    * true exception if possible and log it.
  -    */
  -   protected void logException(Throwable e) {
  -      if (e instanceof RuntimeErrorException) {
  -         e = ((RuntimeErrorException)e).getTargetError();
  -      }
  -      else if (e instanceof RuntimeMBeanException) {
  -         e = ((RuntimeMBeanException)e).getTargetException();
  -      }
  -      else if (e instanceof RuntimeOperationsException) {
  -         e = ((RuntimeOperationsException)e).getTargetException();
  -      }
  -      else if (e instanceof MBeanException) {
  -         e = ((MBeanException)e).getTargetException();
  -      }
  -      else if (e instanceof ReflectionException) {
  -         e = ((ReflectionException)e).getTargetException();
  -      }
  -
  -      log.exception(e);
  -   }
   }
  
  
  
  1.6       +48 -19    
jboss/src/main/org/jboss/configuration/ConfigurationServiceMBean.java
  
  Index: ConfigurationServiceMBean.java
  ===================================================================
  RCS file: 
/cvsroot/jboss/jboss/src/main/org/jboss/configuration/ConfigurationServiceMBean.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -r1.5 -r1.6
  --- ConfigurationServiceMBean.java    2001/04/21 07:24:49     1.5
  +++ ConfigurationServiceMBean.java    2001/04/25 20:09:00     1.6
  @@ -7,19 +7,19 @@
   
   package org.jboss.configuration;
   
  +import org.w3c.dom.Document;
  +
   /**
  - *   <description> 
  + * The <em>JMX</em> admin interface for the {@link ConfigurationService}
  + * MBean.
    *      
  - *   @see <related>
  - *   @author Rickard �berg ([EMAIL PROTECTED])
  - *   @version $Revision: 1.5 $
  + * @author Rickard �berg ([EMAIL PROTECTED])
  + * @version $Revision: 1.6 $
    */
   public interface ConfigurationServiceMBean
   {
  -   // Constants -----------------------------------------------------
  -   public static final String OBJECT_NAME = ":service=Configuration";
  -    
  -   // Public --------------------------------------------------------
  +    /** The default object name. */
  +    public static final String OBJECT_NAME = ":service=Configuration";
   
       /**
        * Get the attribute value auto-trim flag.
  @@ -27,16 +27,45 @@
        * @return  True if attribute values are auto-trimmed.
        */
       boolean getAutoTrim();
  -   
  -     public void load(org.w3c.dom.Document conf)
  -             throws Exception;
  +
  +    /**
  +     * Parses the given configuration document and sets MBean attributes.
  +     *
  +     * @param configuration     The parsed configuration document.
  +     *
  +     * @throws Exception        Failed to load.
  +     */
  +    void load(Document configuration) throws Exception;
  +             
  +    /**
  +     * Builds a string that consists of the configuration elements of
  +     * the currently running MBeans registered in the server.
  +     *
  +     * @throws Exception    Failed to construct configuration.
  +     */
  +     String save() throws Exception;
                
  -     public String save()
  -             throws Exception;
  -      
  -   public void loadConfiguration()
  -      throws Exception;
  -      
  -   public void saveConfiguration()
  -      throws Exception;
  +    /**
  +     * Load the configuration from the configuration file,
  +     * installs and initailize configured MBeans and registeres the
  +     * beans as services.
  +     *
  +     * <p>This is a 2-step process:
  +     * <ol>
  +     *   <li>Load user conf. and create MBeans from that.
  +     *   <li>Apply user conf to created MBeans.
  +     * </ol>
  +     *
  +     * @throws Exception    ???
  +     */
  +   void loadConfiguration() throws Exception;
  +
  +    /**
  +     * Saves the current configuration of each registered MBean to
  +     * the running state file file.  This will only occur if
  +     * a file of the that name exists in the classpath.
  +     *
  +     * @throws Exception    Failed to save configuration.
  +     */
  +   void saveConfiguration() throws Exception;
   }
  
  
  
  1.1                  jboss/src/main/org/jboss/configuration/package.html
  
  Index: package.html
  ===================================================================
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
    <head>
      <!-- $Id: package.html,v 1.1 2001/04/25 20:09:00 user57 Exp $ -->
      <!--
  
      This file is part of JBoss; the OpenSource EJB server.
                                                                                
      This library is free software; you can redistribute it and/or modify it   
      under the terms of the GNU Lesser General Public License as published     
      by the Free Software Foundation; either version 2 of the License, or      
      (at your option) any later version.                                       
                                                                                
      This library is distributed in the hope that it will be useful, but       
      WITHOUT ANY WARRANTY; without even the implied warranty of                
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         
      Lesser General Public License for more details.                           
                                                                                
      You should have received a copy of the GNU Lesser General Public          
      License along with this library; if not, write to the Free Software       
      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA   
  
      -->
    </head>
  
    <body bgcolor="white">
      <p>Provides configuration functionality for loading services.
  
      <h2>Package Specification</h2>
      <ul>
        <li><a href="javascript: alert('not available')">Not Available</a>
      </ul>
        
      <h2>Related Documentation</h2>
      <ul>
        <li><a href="javascript: alert('not available')">Not Available</a>
      </ul>
  
      <h2>Package Status</h2>
      <ul>
        <li><font color="green"><b>STABLE</b></font>
      </ul>
  
      <!-- Put @see and @since tags down here. -->
  
    </body>
  </html>
  
  
  
  

_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
http://lists.sourceforge.net/lists/listinfo/jboss-development

Reply via email to