KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > jmx > AbstractMBeanTask


1 package org.apache.tools.ant.taskdefs.optional.jmx;
2
3 /*
4  * ============================================================================
5  * The Apache Software License, Version 1.1
6  * ============================================================================
7  *
8  * Copyright (C) 2000-2002 The Apache Software Foundation. All
9  * rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modifica-
12  * tion, are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  * this list of conditions and the following disclaimer.
16  *
17  * 2. Redistributions in binary form must reproduce the above copyright notice,
18  * this list of conditions and the following disclaimer in the documentation
19  * and/or other materials provided with the distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any, must
22  * include the following acknowledgment: "This product includes software
23  * developed by the Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself, if
25  * and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Ant" and "Apache Software Foundation" must not be used to
28  * endorse or promote products derived from this software without prior
29  * written permission. For written permission, please contact
30  * apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache", nor may
33  * "Apache" appear in their name, without prior written permission of the
34  * Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
37  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
38  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
39  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
40  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
41  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
42  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
43  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
45  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  *
47  * This software consists of voluntary contributions made by many individuals
48  * on behalf of the Apache Software Foundation. For more information on the
49  * Apache Software Foundation, please see <http://www.apache.org/>.
50  *
51  */

52   
53 import javax.management.MBeanAttributeInfo JavaDoc;
54 import javax.management.MBeanServer JavaDoc;
55 import javax.management.MalformedObjectNameException JavaDoc;
56 import javax.management.ObjectName JavaDoc;
57 import org.apache.tools.ant.BuildException;
58 import org.apache.tools.ant.taskdefs.optional.jmx.connector.JMXConnector;
59 import org.apache.tools.ant.types.optional.ContextType;
60 import org.apache.tools.ant.types.optional.MBeanType;
61
62
63 /**
64  * This is the abstract base class for Ant JMX mbean tasks.
65  * Implementations of AbstractMBean inherit its attributes (see below) for connecting to
66  * the JMX MBean server.</br></br>
67  *
68  * Refer to the user documentation for more information and examples on how to use
69  * this task.
70  *
71  * @author <a HREF="mailto:bdueck@yahoo.com">Brian Dueck</a>
72  * @version $Id: AbstractMBeanTask.java,v 1.5 2003/05/26 15:15:09 bdueck Exp $
73  *
74  */

75 public abstract class AbstractMBeanTask extends AbstractManagementTask {
76     
77     private ObjectName JavaDoc objectName = null;
78     private String JavaDoc name = null;
79     private String JavaDoc activeDomain = null;
80
81     private JMXConnector jmxServer = null;
82
83     public AbstractMBeanTask() {
84         super();
85         setContext(new MBeanType());
86     }
87     
88     /**
89      * Execute the MBean task.
90      *
91      * @throws BuildException If an error occurs.
92      */

93     public void execute() throws BuildException {
94         try {
95             
96             MBeanServer JavaDoc server = login(getProviderUrl(), getJndiName(),
97                                     getUser(),getPassword());
98             execute(server);
99         } catch (Exception JavaDoc x) {
100             if (this.getFailOnError()) {
101                 x.printStackTrace();
102                 throw new BuildException("Error! " + x, x);
103             } else {
104                 log("Warning! " + x,org.apache.tools.ant.Project.MSG_WARN);
105             }
106         }
107     }
108             
109     /**
110      * Execute the JMX MBean task against the specified MBeanServer.
111      *
112      * @param mbserver The target MBeanServer.
113      * @throws BuildException If an error occurs.
114      */

115     protected abstract void execute(MBeanServer JavaDoc mbserver) throws BuildException;
116     
117     /**
118      * Return stringified version of the MBean.
119      *
120      * @return Stringified information about this object.
121      */

122     public String JavaDoc toString() {
123         try {
124             return getObjectName().toString();
125         } catch (MalformedObjectNameException JavaDoc x) {
126             throw new BuildException(x);
127         }
128     }
129
130     /**
131      * Returns an ObjectName for this nested Ant MBean element.
132      * Lazily caches the result in a private instance.
133      *
134      * @return Returns the target ObjectName for this task.
135      * @throws MalformedObjectNameException If there is an error creating a valid ObjectName based on the parameters
136      * specified for this task (jndiName, server, name, type).
137      */

138     protected ObjectName JavaDoc getObjectName() throws MalformedObjectNameException JavaDoc {
139         
140         if (objectName == null) {
141             objectName = new ObjectName JavaDoc(getName());
142             if ((activeDomain != null) && ((objectName.getDomain() == null) || (objectName.getDomain().length() == 0)) ) {
143                 objectName = new ObjectName JavaDoc(activeDomain + getName());
144             }
145         }
146         return objectName;
147     }
148
149
150     /**
151      * Sets the <code>name</code> attribute.
152      *
153      * @param name The name of the mbean.
154      */

155     public void setName(String JavaDoc name) {
156         if ( (getContext() != null) && (getContext().getClass().isAssignableFrom(MBeanType.class)) ) {
157             ((MBeanType)getContext()).setName(name);
158         } else {
159             this.name = name;
160         }
161     }
162
163     /**
164      * The name of the JMX MBean.
165      *
166      * @return The name of the MBean.
167      */

168     protected String JavaDoc getName() {
169         if ( (getContext() != null) && (getContext().getClass().isAssignableFrom(MBeanType.class)) ) {
170             return ((MBeanType)getContext()).getName();
171         } else {
172             return name;
173         }
174     }
175     
176     
177     public String JavaDoc getActiveDomain() {
178         return activeDomain;
179     }
180     
181     public JMXConnector getJMXServer() {
182         return jmxServer;
183     }
184     
185     public void setMBeanRef(org.apache.tools.ant.types.Reference ref) {
186         Object JavaDoc obj = ref.getReferencedObject(this.getProject());
187
188         if (!(obj instanceof MBeanType)) {
189             String JavaDoc msg = "'" + ref.getRefId() + "' doesn't denote a " + MBeanType.DATA_TYPE_NAME + ". " + ref.getRefId() + " is a " + obj.getClass().getName();
190             throw new BuildException(msg);
191         }
192         setContext((ContextType) obj);
193     }
194
195     /**
196      * Helper function to find the MBeanAttributeInfo for the indicated attribute name.
197      *
198      * @returns The attribute info value or null if the named attribute cannot be
199      * found.
200      *
201      */

202     protected MBeanAttributeInfo JavaDoc findAttributeInfo(javax.management.MBeanInfo JavaDoc beanInfo, String JavaDoc attributeName) {
203         MBeanAttributeInfo JavaDoc[] attributes = beanInfo.getAttributes();
204         for (int counter = 0; counter < attributes.length; counter++) {
205             if (attributes[counter].getName().equals(attributeName)) {
206                 return attributes[counter];
207             }
208         }
209         return null;
210     }
211         
212     /**
213      * Helper function to return MBeanAttributeInfo[] as a Map.
214      *
215      * @returns A map containing MBeanAttributeInfo's. Keyed by name, value is MBeanAttributeInfo.
216      *
217      */

218     protected java.util.Map JavaDoc getAttributes(javax.management.MBeanInfo JavaDoc beanInfo) {
219         return getAttributes(beanInfo,null);
220     }
221     
222     /**
223      * Helper function to return MBeanAttributeInfo[] as a Map.
224      * Returned attributes can be filtered by passing in a set of attribute names (ignored if null).
225      *
226      * @returns A map containing MBeanAttributeInfo's. Keyed by name, value is MBeanAttributeInfo.
227      *
228      */

229     protected java.util.Map JavaDoc getAttributes(javax.management.MBeanInfo JavaDoc beanInfo, java.util.Set JavaDoc attributeNames) {
230         java.util.Map JavaDoc result = new java.util.TreeMap JavaDoc();
231         MBeanAttributeInfo JavaDoc[] attributes = beanInfo.getAttributes();
232         for (int counter = 0; counter < attributes.length; counter++) {
233             
234             if ( (attributeNames == null) || (attributeNames.contains(attributes[counter].getName()) ) ) {
235                 result.put(attributes[counter].getName(), attributes[counter]);
236             }
237         }
238         return result;
239     }
240
241     /**
242      * Helper function to extract attribute names from an MBeanFeatureInfo[]
243      * as a String[].
244      *
245      * @param features The feature information.
246      * @return An array of strings with the feature names.
247      */

248     protected String JavaDoc[] getFeatureNames(javax.management.MBeanFeatureInfo JavaDoc[] features) {
249         String JavaDoc[] result = new String JavaDoc[features.length];
250         
251         for (int counter = 0; counter < features.length; counter++) {
252             result[counter] = features[counter].getName();
253         }
254         
255         return result;
256     }
257     /**
258      * Logs into a JMX server and returns the MBeanServer to
259      * use during task execution. The caller is responsible
260      * for invoking this method prior to executing any other
261      * methods on this interface.
262      *
263      * @param providerUrl The url of the JNDI provider.
264      * @param jndiName The JNDI name of the MBeanServer.
265      * @param user The user name to use for authentication.
266      * @param password The password to use for authentication.
267      * @return An MBeanServer.
268      * @raise BuildException if an error occurs attempting to login.
269      */

270     private MBeanServer JavaDoc login(String JavaDoc providerUrl, String JavaDoc jndiName, String JavaDoc user, String JavaDoc password) throws javax.naming.NamingException JavaDoc {
271         try {
272
273             if (getContext().getServerType() == null) {
274                 log("Warning! serverType not specified or unrecognized type. Defaulting to WebLogic.");
275                 getContext().setServerType("weblogic");
276             }
277
278             jmxServer = org.apache.tools.ant.taskdefs.optional.jmx.connector.JMXConnectorFactory.createConnector(getContext().getServerType());
279             java.util.Hashtable JavaDoc properties = jmxServer.getInitialContextProperties(providerUrl,user,password);
280             
281             MBeanServer JavaDoc mbserver = jmxServer.getMBeanServer(properties,jndiName);
282             activeDomain = jmxServer.getActiveDomain(mbserver);
283             return mbserver;
284             
285         } catch (Exception JavaDoc e) {
286             e.printStackTrace();
287             throw new BuildException("JMX Error. " + e.getMessage(), e);
288         }
289     }
290     
291     /**
292      * Removes a given mbean from an mbean server if required by the IfExists
293      * flag.
294      * If the mbean does not exist in the target mbean server, this is a null op.
295      * If the mbean exists, the action taken is determined by the ifExists
296      * paramter.</p>
297      * mbean exists && ifExists = skip : The mbean is left in place.</p>
298      * mbean exists && ifExists = warn : A warning is given and the mbean is left in place.</p>
299      * mbean exists && ifExists = fail : BuildException is thrown.</p>
300      * mbean exists && ifExists = replace : A warning is given and the mbean is removed.</p>
301      * mbean exists && ifExists = replaceAttributes : A warning is given but the mbean is left in place.</p>
302      *
303      * @param mbserver The MBeanServer that hosts the mbean.</p>
304      * @param mbean The mbean to remove.
305      * @param ifExists One of IfExists.getValues().
306      * @see IfExists
307      * @throws BuildException
308      */

309     protected void removeMBeanIfExists(javax.management.MBeanServer JavaDoc mbserver,
310         javax.management.ObjectName JavaDoc mbean, String JavaDoc ifExists)
311         throws org.apache.tools.ant.BuildException {
312             
313         if (mbserver.isRegistered(mbean)) {
314             String JavaDoc message = "Mbean " + mbean.getCanonicalName() + " already exists. ";
315             if (ifExists.equals(IfExists.FAIL)) {
316                 throw new org.apache.tools.ant.BuildException(message);
317             } else if (ifExists.equals(IfExists.SKIP)) {
318                 return;
319             } else if (ifExists.equals(IfExists.WARN)) {
320                 log("Warning! " + message + "Skipping." + mbean);
321                 return;
322             } else if (ifExists.equals(IfExists.REPLACE)) {
323                 log("Warning! " + message + "It will be deleted and replaced. " + mbean);
324                 try {
325                     mbserver.unregisterMBean(mbean);
326                 } catch (javax.management.InstanceNotFoundException JavaDoc eatMe) {
327                     log("Warning! " + message + "However it cannot be properly removed.");
328                 } catch (javax.management.MBeanRegistrationException JavaDoc eatMe) {
329                     log("Warning! " + message + "However it cannot be properly removed.");
330                 }
331             } else if (ifExists.equals(IfExists.REPLACE_ATTRIBUTES)) {
332                 log("Warning! " + message + "Its attributes will be replaced. " + mbean);
333             }
334         }
335     }
336 }
337
338 /*
339  * $Log: AbstractMBeanTask.java,v $
340  * Revision 1.5 2003/05/26 15:15:09 bdueck
341  * Slight adjustment to log message.
342  *
343  * Revision 1.4 2003/05/26 10:13:05 bdueck
344  * *** empty log message ***
345  *
346  * Revision 1.3 2003/04/21 15:29:41 bdueck
347  * Various changes in preparation for version 1.2.
348  *
349  * Revision 1.2 2003/04/01 22:02:08 bdueck
350  * Factored out basic JNDI connectivity. Added support for mbeanref.
351  *
352  * Revision 1.1 2003/01/17 12:33:55 bdueck
353  * Initial check-in
354  *
355  *
356  */
Popular Tags