alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.tomcat5.mgmt;

import java.io.BufferedReader;
import java.net.URLEncoder;
import javax.management.j2ee.Management;
import javax.management.*;
import java.rmi.RemoteException;
import java.util.*;
import org.netbeans.modules.tomcat5.TomcatFactory;
import org.netbeans.modules.tomcat5.TomcatManager;
import org.netbeans.modules.tomcat5.TomcatManagerImpl;
import org.netbeans.modules.tomcat5.TomcatModule;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;

/** Management implementation for Tomcat.
 * XXX need to implement caching.
 * @author Radim Kubacki
 */
public class TomcatManagement implements Management {
    
    /** MBean name */
    private static final String ATTR_NAME = "Name"; // NOI18N
    private static final String OP_ATTR_NAME = "name"; // NOI18N
    
    /** parameter name for query requests */
    private static final String QUERY = "?qry="; // NOI18N
    
    /** associated TomcatManager */
    TomcatManager tm;
    
    /** Creates a new instance of TomcatManagement */
    public TomcatManagement (TomcatManager tm) {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "Created TomcatManagement"); // NOI18N
        
        this.tm = tm;
        try {
            initManagement ();
        }
        catch (Exception e) {
            ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, e);
        }
    }
    
    private void initManagement () throws Exception {
    }
    
    
    public Object getAttribute(ObjectName objName, String str) 
    throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.getAttribute "+objName+", "+str); // NOI18N
        TomcatManagerImpl impl = new TomcatManagerImpl (tm);
        String s = impl.jmxProxy (QUERY+URLEncoder.encode (objName.toString ()));    // PENDING encoding NOI18N
        java.util.Map map = parse (s, str);
        java.util.Iterator it = map.keySet ().iterator ();
        return it.hasNext ()? it.next (): null;
    }
    
    public javax.management.AttributeList getAttributes(ObjectName objName, String[] str) 
    throws InstanceNotFoundException, ReflectionException, RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.getAttributes "+objName); // NOI18N
        // PENDING
        TomcatManagerImpl impl = new TomcatManagerImpl (tm);
        String s = impl.jmxProxy (QUERY+URLEncoder.encode (objName.toString ()));    // PENDING encoding NOI18N
        java.util.Map map = parse (s, null);
        java.util.Iterator it = map.keySet ().iterator ();
        java.util.List attrNames = java.util.Arrays.asList (str);
        AttributeList attrs = new AttributeList ();
        while (it.hasNext ()) {
            String name = (String)it.next ();
            if (attrNames.contains (name)) {
                attrs.add (new Attribute (name, map.get(name)));
            }
        }
        return attrs;
    }
    
    public String getDefaultDomain() throws RemoteException {
        return "none"; // server.getDefaultDomain ();
    }
        
    public javax.management.j2ee.ListenerRegistration getListenerRegistry() throws java.rmi.RemoteException {
        return new TomcatManagement.ListenerRegistry ();
    }
    
    public Integer getMBeanCount() throws RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.getMBeanCount"); // NOI18N
        return new Integer(0); // server.getMBeanCount ();
    }

    public MBeanInfo getMBeanInfo (ObjectName objectName) 
    throws IntrospectionException, InstanceNotFoundException, ReflectionException, RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.getMBeanInfo "+objectName); // NOI18N
        
        TomcatManagerImpl impl = new TomcatManagerImpl (tm);
        String s = impl.jmxProxy (QUERY+URLEncoder.encode (objectName.toString ()));    // PENDING encoding NOI18N
        java.util.Map map = parse (s, null);
        java.util.Iterator it = map.keySet ().iterator ();
        java.util.ArrayList l = new java.util.ArrayList ();
        while (it.hasNext ()) {
            try {
                String name = (String)it.next ();
                if (!ATTR_NAME.equals (name)) {
                    l.add (new MBeanAttributeInfo (name, "java.lang.String", name, true, false, false)); // NOI18N
                }
            }
            catch (IllegalArgumentException e) {
                TomcatFactory.getEM ().notify (ErrorManager.INFORMATIONAL, e);
                throw new IntrospectionException (e.getMessage ());
            }
        }
        String clz = (String)map.get ("className"); // NOI18N
        if (clz == null) {
            clz = (String)map.get ("modelerType"); // NOI18N
        }
        MBeanAttributeInfo [] attrs = (MBeanAttributeInfo[])l.toArray (new MBeanAttributeInfo[l.size ()]);
        MBeanInfo mbi = new MBeanInfo (
            clz, 
            (String)map.get (ATTR_NAME), 
            attrs,
            new MBeanConstructorInfo [0],
            createOperations (objectName),
            new MBeanNotificationInfo [0]
        );
        return mbi;
    }
        
    public Object invoke (ObjectName objectName, String opname, Object[] obj, String[] str3) 
    throws InstanceNotFoundException, MBeanException, ReflectionException, RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.invoke "+opname+" on "+objectName);    // NOI18N
        if ("start".equals (opname)) {  // NOI18N
            String path = objectName.getKeyProperty (OP_ATTR_NAME);
            int idx = path.indexOf ('/',2);
            if (idx > 0) {
                path = path.substring (idx);
                TomcatManagerImpl impl = new TomcatManagerImpl (tm);
                impl.start (new TomcatModule (tm.getTargets ()[0], path));
                return null;
            }
        }
        else if ("stop".equals (opname)) {  // NOI18N
            String path = objectName.getKeyProperty (OP_ATTR_NAME);
            int idx = path.indexOf ('/',2);
            if (idx > 0) {
                path = path.substring (idx);
                TomcatManagerImpl impl = new TomcatManagerImpl (tm);
                impl.stop (new TomcatModule (tm.getTargets ()[0], path));
                return null;
            }
        }
        else if ("remove".equals (opname)) {  // NOI18N
            String path = objectName.getKeyProperty (OP_ATTR_NAME);
            int idx = path.indexOf ('/',2);
            if (idx > 0) {
                path = path.substring (idx);
                TomcatManagerImpl impl = new TomcatManagerImpl (tm);
                impl.remove (new TomcatModule (tm.getTargets ()[0], path));
                return null;
            }
        }
        throw new MBeanException (new UnsupportedOperationException ());
    }
    
    
    public boolean isRegistered(ObjectName objectName) throws RemoteException {
        // PENDING
        return false;
    }
    public java.util.Set queryNames(ObjectName objectName, QueryExp queryExp) throws RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.queryNames "+objectName+", "+queryExp); // NOI18N
        // PENDING queryExp is null, why?
        TomcatManagerImpl impl = new TomcatManagerImpl (tm);
        String s = impl.jmxProxy (QUERY+URLEncoder.encode (objectName.toString ()));    // PENDING encoding NOI18N
        java.util.Iterator it = parse (s, ATTR_NAME).keySet ().iterator ();
        java.util.Set names= new java.util.HashSet ();
        while (it.hasNext ()) {
            try {
                names.add (new ObjectName ((String)it.next ()));
            }
            catch (MalformedObjectNameException e) {
                TomcatFactory.getEM ().notify (ErrorManager.INFORMATIONAL, e);
            }
        }
        return names;
    }
    
    public void setAttribute(ObjectName objectName, Attribute attribute) 
    throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, RemoteException {
        TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "TomcatManagement.setAttribute "+objectName+", "+attribute); // NOI18N
        TomcatManagerImpl impl = new TomcatManagerImpl (tm);
        String s = impl.jmxProxy ("?set="+URLEncoder.encode (objectName.toString ())+"&att="+attribute.getName ()+"&val="+attribute.getValue ());    // PENDING encoding NOI18N
        if (!s.startsWith ("Result: ok")) {
            throw new ReflectionException (new Exception ());
        }
        return;
    }
    
    public AttributeList setAttributes(ObjectName objectName, AttributeList attributeList) 
    throws InstanceNotFoundException, ReflectionException, RemoteException {
        java.util.Iterator it = attributeList.iterator ();
        while (it.hasNext ()) {
            Attribute a = (Attribute)it.next ();
            try {
                setAttribute (objectName, a);
            }
            catch (Exception ex) {
                throw new ReflectionException (ex);
            }
        }
        return attributeList;
    }

    // Dummy methods required due to inheritance from EJBObject
    
    public javax.ejb.EJBHome getEJBHome() throws java.rmi.RemoteException {
        return null;
    }
    
    public javax.ejb.Handle getHandle() throws java.rmi.RemoteException {
        return null;
    }

    public Object getPrimaryKey() throws java.rmi.RemoteException {
        return null;
    }

    public boolean isIdentical(javax.ejb.EJBObject eJBObject) throws java.rmi.RemoteException {
        return false;
    }

    public void remove() throws java.rmi.RemoteException, javax.ejb.RemoveException {
    }
    
    /** Parses output of jmxproxy command to get Map of attr names and their values
     * @param s parsed string
     * @param attr null to get all attribute values or value of scanned attribute
     * @return (attribute, value) pairs if attr is not null or (value, value) if
     * attribute name is specified
     */
    private Map parse (String s, String attr) {
        BufferedReader reader = new BufferedReader (new java.io.StringReader (s));
        java.util.Map result = new java.util.HashMap ();
        try {
            //skip first two lines (MBeanCount:0\n\n)
            reader.readLine (); reader.readLine ();
            String line;
            while ((line = reader.readLine ()) != null) {
                while (line.endsWith ("\\n")) {  // NOI18N
                    // multiline value
                    String nextLine = reader.readLine ();
                    if (nextLine == null || nextLine.length ()<1) {
                        break;
                    }
                    line = line.substring (0, line.length ()-2) + nextLine.substring (1);
                }
                if (attr == null) {
                    int idx = line.indexOf (": ");  // NOI18N
                    if (idx > 0) {
                        result.put (line.substring (0, idx), line.substring (idx+2));
                    }
                }
                else if (line.startsWith (attr+": ")) {  // NOI18N
                    int idx = line.indexOf (": ");  // NOI18N
                    if (idx > 0) {
                        result.put (line.substring (idx+2), line.substring (idx+2));
                    }
                }
            }
        }
        catch (java.io.IOException ioe) {
            TomcatFactory.getEM ().notify (ErrorManager.INFORMATIONAL, ioe); // NOI18N
        }
        return result;
    }
    
    /** Creates fake operations for MBeans obtained from tomcat.
     * Start/stop/remove is supported for WebModules
     */
    private MBeanOperationInfo [] createOperations (ObjectName oName) {
        if ("WebModule".equals (oName.getKeyProperty ("j2eeType"))) {  // NOI18N
            MBeanOperationInfo [] ops = new MBeanOperationInfo [3];
            ops[0] = new MBeanOperationInfo (
                "start", // NOI18N
                NbBundle.getMessage (TomcatManagement.class, "LBL_startOperationDesc"),
                null,
                null,
                MBeanOperationInfo.ACTION
            );
            ops[1] = new MBeanOperationInfo (
                "stop", // NOI18N 
                NbBundle.getMessage (TomcatManagement.class, "LBL_stopOperationDesc"),
                null,
                null,
                MBeanOperationInfo.ACTION
            );
            ops[2] = new MBeanOperationInfo (
                "remove",  // NOI18N
                NbBundle.getMessage (TomcatManagement.class, "LBL_removeOperationDesc"),
                null,
                null,
                MBeanOperationInfo.ACTION
            );
            return ops;
        }
        return new MBeanOperationInfo [0];
    }
    
    private static class ListenerRegistry implements javax.management.j2ee.ListenerRegistration {
        
        public void addNotificationListener (ObjectName oName, NotificationListener lsnr, NotificationFilter filter, Object obj) 
        throws javax.management.InstanceNotFoundException, java.rmi.RemoteException {
            // no op
        }
        
        public void removeNotificationListener (ObjectName oName, NotificationListener lsnr) 
        throws javax.management.InstanceNotFoundException, javax.management.ListenerNotFoundException, 
            java.rmi.RemoteException {
                // no op
        }
        
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.