FileDocCategorySizeDatePackage
JMXAccessorTask.javaAPI DocApache Tomcat 6.0.1423985Fri Jul 20 04:20:32 BST 2007org.apache.catalina.ant.jmx

JMXAccessorTask

public class JMXAccessorTask extends org.apache.catalina.ant.BaseRedirectorHelperTask
Access JMX JSR 160 MBeans Server.
  • open more then one JSR 160 rmi connection
  • Get/Set Mbeans attributes
  • Call Mbean Operation with arguments
  • Argument values can be converted from string to int,long,float,double,boolean,ObjectName or InetAddress
  • Query Mbeans
  • Show Get, Call, Query result at Ant console log
  • Bind Get, Call, Query result at Ant properties
Examples: open server with reference and autorisation

<jmxOpen
host="127.0.0.1"
port="9014"
username="monitorRole"
password="mysecret"
ref="jmx.myserver"
/>

All calls after opening with same refid reuse the connection.

First call to a remote MBeanserver save the JMXConnection a referenz jmx.server

All JMXAccessorXXXTask support the attribute if and unless. With if the task is only execute when property exist and with unless when property not exists.
NOTE : These tasks require Ant 1.6 or later interface.
author
Peter Rossbach
version
$Revision: 467222 $ $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
since
5.5.10

Fields Summary
public static String
JMX_SERVICE_PREFIX
public static String
JMX_SERVICE_SUFFIX
private String
name
private String
resultproperty
private String
url
private String
host
private String
port
private String
password
private String
username
private String
ref
private boolean
echo
private boolean
separatearrayresults
private String
delimiter
private String
unlessCondition
private String
ifCondition
private Properties
properties
private static final String
info
Descriptive information describing this implementation.
Constructors Summary
Methods Summary
public static javax.management.MBeanServerConnectionaccessJMXConnection(org.apache.tools.ant.Project project, java.lang.String url, java.lang.String host, java.lang.String port, java.lang.String username, java.lang.String password, java.lang.String refId)
Get Current Connection from ref parameter or create a new one!

return
The server connection
throws
MalformedURLException
throws
IOException

        MBeanServerConnection jmxServerConnection = null;
        boolean isRef = project != null && refId != null && refId.length() > 0;
        if (isRef) {
            Object pref = project.getReference(refId);
            try {
                jmxServerConnection = (MBeanServerConnection) pref;
            } catch (ClassCastException cce) {
                if (project != null) {
                    project.log("wrong object reference " + refId + " - "
                            + pref.getClass());
                }
                return null;
            }
        }
        if (jmxServerConnection == null) {
            jmxServerConnection = createJMXConnection(url, host, port,
                    username, password);
        }
        if (isRef && jmxServerConnection != null) {
            project.addReference(refId, jmxServerConnection);
        }
        return jmxServerConnection;
    
protected java.lang.ObjectconvertStringToType(java.lang.String value, java.lang.String valueType)
Convert string to datatype FIXME How we can transfer values from ant project reference store (ref)?

param
value The value
param
valueType The type
return
The converted object

        if ("java.lang.String".equals(valueType))
            return value;

        Object convertValue = value;
        if ("java.lang.Integer".equals(valueType) || "int".equals(valueType)) {
            try {
                convertValue = new Integer(value);
            } catch (NumberFormatException ex) {
                if (isEcho())
                    handleErrorOutput("Unable to convert to integer:" + value);
            }
        } else if ("java.lang.Long".equals(valueType)
                || "long".equals(valueType)) {
            try {
                convertValue = new Long(value);
            } catch (NumberFormatException ex) {
                if (isEcho())
                    handleErrorOutput("Unable to convert to long:" + value);
            }
        } else if ("java.lang.Boolean".equals(valueType)
                || "boolean".equals(valueType)) {
            convertValue = new Boolean(value);
        } else if ("java.lang.Float".equals(valueType)
                || "float".equals(valueType)) {
            try {
                convertValue = new Float(value);
            } catch (NumberFormatException ex) {
                if (isEcho())
                    handleErrorOutput("Unable to convert to float:" + value);
            }
        } else if ("java.lang.Double".equals(valueType)
                || "double".equals(valueType)) {
            try {
                convertValue = new Double(value);
            } catch (NumberFormatException ex) {
                if (isEcho())
                    handleErrorOutput("Unable to convert to double:" + value);
            }
        } else if ("javax.management.ObjectName".equals(valueType)
                || "name".equals(valueType)) {
            try {
                convertValue = new ObjectName(value);
            } catch (MalformedObjectNameException e) {
                if (isEcho())
                    handleErrorOutput("Unable to convert to ObjectName:"
                            + value);
            }
        } else if ("java.net.InetAddress".equals(valueType)) {
            try {
                convertValue = InetAddress.getByName(value);
            } catch (UnknownHostException exc) {
                if (isEcho())
                    handleErrorOutput("Unable to resolve host name:" + value);
            }
        }
        return convertValue;
    
public static javax.management.MBeanServerConnectioncreateJMXConnection(java.lang.String url, java.lang.String host, java.lang.String port, java.lang.String username, java.lang.String password)
create a new JMX Connection with auth when username and password is set.

        String urlForJMX;
        if (url != null)
            urlForJMX = url;
        else
            urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port
                    + JMX_SERVICE_SUFFIX;
        Map environment = null;
        if (username != null && password != null) {
            String[] credentials = new String[2];
            credentials[0] = username;
            credentials[1] = password;
            environment = new HashMap();
            environment.put(JMXConnector.CREDENTIALS, credentials);
        }
        return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX),
                environment).getMBeanServerConnection();

    
protected voidcreateProperty(java.lang.Object result)
create result as property with name from attribute resultproperty

param
result The result
see
#createProperty(String, Object)

        if (resultproperty != null) {
            createProperty(resultproperty, result);
        }
    
protected voidcreateProperty(java.lang.String propertyPrefix, java.lang.Object result)
create result as property with name from property prefix When result is an array and isSeparateArrayResults is true, resultproperty used as prefix (resultproperty.0-array.length and store the result array length at resultproperty.length. Other option is that you delemit your result with a delimiter (java.util.StringTokenizer is used).

param
propertyPrefix
param
result

        if (propertyPrefix == null)
            propertyPrefix = "";
        if (result instanceof CompositeDataSupport) {
            CompositeDataSupport data = (CompositeDataSupport) result;
            CompositeType compositeType = data.getCompositeType();
            Set keys = compositeType.keySet();
            for (Iterator iter = keys.iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                Object value = data.get(key);
                OpenType type = compositeType.getType(key);
                if (type instanceof SimpleType) {
                    setProperty(propertyPrefix + "." + key, value);
                } else {
                    createProperty(propertyPrefix + "." + key, value);
                }
            }
        } else if (result instanceof TabularDataSupport) {
            TabularDataSupport data = (TabularDataSupport) result;
            for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                Object key = iter.next();
                for (Iterator iter1 = ((List) key).iterator(); iter1.hasNext();) {
                    Object key1 = iter1.next();
                    CompositeData valuedata = data.get(new Object[] { key1 });
                    Object value = valuedata.get("value");
                    OpenType type = valuedata.getCompositeType().getType(
                            "value");
                    if (type instanceof SimpleType) {
                        setProperty(propertyPrefix + "." + key1, value);
                    } else {
                        createProperty(propertyPrefix + "." + key1, value);
                    }
                }
            }
        } else if (result.getClass().isArray()) {
            if (isSeparatearrayresults()) {
                int size = 0;
                for (int i = 0; i < Array.getLength(result); i++) {
                    if (setProperty(propertyPrefix + "." + size, Array.get(
                            result, i))) {
                        size++;
                    }
                }
                if (size > 0) {
                    setProperty(propertyPrefix + ".Length", Integer
                            .toString(size));
                }
            }
        } else {
            String delim = getDelimiter();
            if (delim != null) {
                StringTokenizer tokenizer = new StringTokenizer(result
                        .toString(), delim);
                int size = 0;
                for (; tokenizer.hasMoreTokens();) {
                    String token = tokenizer.nextToken();
                    if (setProperty(propertyPrefix + "." + size, token)) {
                        size++;
                    }
                }
                if (size > 0)
                    setProperty(propertyPrefix + ".Length", Integer
                            .toString(size));
            } else {
                setProperty(propertyPrefix, result.toString());
            }
        }
    
protected voidechoResult(java.lang.String name, java.lang.Object result)

param
name context of result
param
result

        if (isEcho()) {
            if (result.getClass().isArray()) {
                for (int i = 0; i < Array.getLength(result); i++) {
                    handleOutput(name + "." + i + "=" + Array.get(result, i));
                }
            } else
                handleOutput(name + "=" + result);
        }
    
public voidexecute()
Execute the specified command. This logic only performs the common attribute validation required by all subclasses; it does not perform any functional logic directly.

exception
BuildException if a validation error occurs

        if (testIfCondition() && testUnlessCondition()) {
            try {
                String error = null;

                MBeanServerConnection jmxServerConnection = getJMXConnection();
                error = jmxExecute(jmxServerConnection);
                if (error != null && isFailOnError()) {
                    // exception should be thrown only if failOnError == true
                    // or error line will be logged twice
                    throw new BuildException(error);
                }
            } catch (Throwable t) {
                if (isFailOnError()) {
                    throw new BuildException(t);
                } else {
                    handleErrorOutput(t.getMessage());
                }
            } finally {
                closeRedirector();
            }
        }
    
public java.lang.StringgetDelimiter()

return
Returns the delimiter.

        return delimiter;
    
public java.lang.StringgetHost()
The Host of the JMX JSR 160 MBeanServer to be used.

        return (this.host);
    
public java.lang.StringgetIf()

return
Returns the ifCondition.

        return ifCondition;
    
public java.lang.StringgetInfo()
Return descriptive information about this implementation and the corresponding version number, in the format <description>/<version>.


                        
       

        return (info);

    
protected javax.management.MBeanServerConnectiongetJMXConnection()
get JMXConnection

return
The connection
throws
MalformedURLException
throws
IOException


        MBeanServerConnection jmxServerConnection = null;
        if (isUseRef()) {
            Object pref = null ;
            if(getProject() != null) {
                pref = getProject().getReference(getRef());
                if (pref != null) {
                    try {
                        jmxServerConnection = (MBeanServerConnection) pref;
                    } catch (ClassCastException cce) {
                        getProject().log(
                            "Wrong object reference " + getRef() + " - "
                                    + pref.getClass());
                        return null;
                    }
                }
            }
            if (jmxServerConnection == null) {
                jmxServerConnection = accessJMXConnection(getProject(),
                        getUrl(), getHost(), getPort(), getUsername(),
                        getPassword(), getRef());
            }
        } else {
            jmxServerConnection = accessJMXConnection(getProject(), getUrl(),
                    getHost(), getPort(), getUsername(), getPassword(), null);
        }
        return jmxServerConnection;
    
public java.lang.StringgetName()
The name used at remote MbeanServer

        return (this.name);
    
public java.lang.StringgetPassword()
The login password for the Manager application.

        return (this.password);
    
public java.lang.StringgetPort()
The Port of the JMX JSR 160 MBeanServer to be used.

        return (this.port);
    
public java.util.MapgetProperties()
get all properties, when project is there got all project Properties

return
properties

        Project currentProject = getProject();
        if (currentProject != null) {
            return currentProject.getProperties();
        } else {
            return properties;
        }        
    
public java.lang.StringgetProperty(java.lang.String property)
get all Properties

param
property
return
The property

        Project currentProject = getProject();
        if (currentProject != null) {
            return currentProject.getProperty(property);
        } else {
            return properties.getProperty(property);
        }
    
public java.lang.StringgetRef()

return
Returns the ref.

        return ref;
    
public java.lang.StringgetResultproperty()

return
Returns the resultproperty.

        return resultproperty;
    
public java.lang.StringgetUnless()

return
Returns the unlessCondition.

        return unlessCondition;
    
public java.lang.StringgetUrl()
The URL of the JMX JSR 160 MBeanServer to be used.

        return (this.url);
    
public java.lang.StringgetUsername()
The login username for the JMX MBeanServer.

        return (this.username);
    
public booleanisEcho()

return
Returns the echo.

        return echo;
    
public booleanisSeparatearrayresults()

return
Returns the separatearrayresults.

        return separatearrayresults;
    
public booleanisUseRef()

return
Returns the useRef.

        return ref != null && !"".equals(ref);
    
public java.lang.StringjmxExecute(javax.management.MBeanServerConnection jmxServerConnection)
Execute the specified command, based on the configured properties. The input stream will be closed upon completion of this task, whether it was executed successfully or not.

exception
Exception if an error occurs


        if ((jmxServerConnection == null)) {
            throw new BuildException("Must open a connection!");
        } else if (isEcho()) {
            handleOutput("JMX Connection ref=" + ref + " is open!");
        }
        return null;
    
public voidsetDelimiter(java.lang.String separator)

param
separator The delimiter to set.

        this.delimiter = separator;
    
public voidsetEcho(boolean echo)

param
echo The echo to set.

        this.echo = echo;
    
public voidsetHost(java.lang.String host)

        this.host = host;
    
public voidsetIf(java.lang.String c)
Only execute if a property of the given name exists in the current project.

param
c property name

        ifCondition = c;
    
public voidsetName(java.lang.String objectName)

        this.name = objectName;
    
public voidsetPassword(java.lang.String password)

        this.password = password;
    
public voidsetPort(java.lang.String port)

        this.port = port;
    
public booleansetProperty(java.lang.String property, java.lang.Object value)

param
property The property
param
value The value
return
True if successful

        if (property != null) {
            if (value == null)
                value = "";
            if (isEcho()) {
                handleOutput(property + "=" + value.toString());
            }
            Project currentProject = getProject();
            if (currentProject != null) {
                currentProject.setNewProperty(property, value.toString());
            } else {
                properties.setProperty(property, value.toString());
            }
            return true;
        }
        return false;
    
public voidsetRef(java.lang.String refId)

param
refId The ref to set.

        this.ref = refId;
    
public voidsetResultproperty(java.lang.String propertyName)

param
propertyName The resultproperty to set.

        this.resultproperty = propertyName;
    
public voidsetSeparatearrayresults(boolean separateArrayResults)

param
separateArrayResults The separatearrayresults to set.

        this.separatearrayresults = separateArrayResults;
    
public voidsetUnless(java.lang.String c)
Only execute if a property of the given name does not exist in the current project.

param
c property name

        unlessCondition = c;
    
public voidsetUrl(java.lang.String url)

        this.url = url;
    
public voidsetUsername(java.lang.String username)

        this.username = username;
    
protected booleantestIfCondition()
test the if condition

return
true if there is no if condition, or the named property exists

        if (ifCondition == null || "".equals(ifCondition)) {
            return true;
        }
        return getProperty(ifCondition) != null;
    
protected booleantestUnlessCondition()
test the unless condition

return
true if there is no unless condition, or there is a named property but it doesn't exist

        if (unlessCondition == null || "".equals(unlessCondition)) {
            return true;
        }
        return getProperty(unlessCondition) == null;