KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > diagnostics > collect > MonitoringInfoHelper


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.diagnostics.collect;
25
26
27 import com.sun.enterprise.admin.util.ClassUtil;
28 import com.sun.enterprise.admin.util.ArrayConversion;
29 import com.sun.enterprise.admin.server.core.jmx.AppServerMBeanServerFactory;
30 import com.sun.enterprise.admin.server.core.jmx.InitException;
31
32 import com.sun.enterprise.diagnostics.DiagnosticException;
33 import com.sun.logging.LogDomains;
34
35 import javax.management.*;
36
37
38 import java.util.*;
39 import java.util.logging.Logger JavaDoc;
40 import java.util.logging.Level JavaDoc;
41
42
43 /**
44  * A helper which executes List, Get for Dotted Names Command
45  * @author Jagadish Ramu
46  */

47 public class MonitoringInfoHelper {
48
49     private static final String JavaDoc LIST_COMMAND = "list";
50     private static final String JavaDoc LIST_OPERATION = "dottedNameList";
51     private static final String JavaDoc LIST_MONITORING_OPERATION =
52             "dottedNameMonitoringList";
53     private static final String JavaDoc GET_COMMAND = "get";
54     private static final String JavaDoc GET_OPERATION = "dottedNameGet";
55     private static final String JavaDoc GET_MONITORING_OPERATION =
56             "dottedNameMonitoringGet";
57
58
59     public final static String JavaDoc STRING_ARRAY = (new String JavaDoc[]{}).
60             getClass().getName();
61     private static final String JavaDoc MONITOR_OPTION = "monitor";
62     private static final String JavaDoc OBJECT_NAME =
63             "com.sun.appserv:name=dotted-name-get-set,type=dotted-name-support";
64     private static final String JavaDoc PROPERTY_STRING = "property|system-property";
65
66     public final static String JavaDoc SECURE = "secure";
67     private ArrayList<String JavaDoc> operands;
68     private String JavaDoc name;
69     private HashMap options;
70
71     private static Logger JavaDoc logger =
72             LogDomains.getLogger(LogDomains.ADMIN_LOGGER);
73
74     private ArrayList<String JavaDoc> output;
75
76     public MonitoringInfoHelper() {
77         options = new HashMap();
78     }
79
80     /**
81      * Operands passed to List/ Get command
82      *
83      * @param operands
84      */

85     public void setOperands(ArrayList<String JavaDoc> operands) {
86         this.operands = operands;
87     }
88
89     /**
90      * Operands passed to List/ Get command
91      *
92      * @return Vector representing the operands
93      */

94     public ArrayList<String JavaDoc> getOperands() {
95         return operands;
96     }
97
98     /**
99      * set the command name ( list / get )
100      *
101      * @param name
102      */

103     public void setName(String JavaDoc name) {
104         this.name = name;
105     }
106
107     /**
108      * get the command name (list / get)
109      *
110      * @return String
111      */

112     public String JavaDoc getName() {
113         return name;
114     }
115
116
117     /**
118      * Sets the list of options for this Command
119      *
120      * @param options List of options for this command
121      */

122     public void setOptions(HashMap options) {
123         this.options = options;
124     }
125
126     /**
127      * Finds the option with the give name
128      *
129      * @return Option return option if found else return null
130      */

131     public String JavaDoc getOption(String JavaDoc optionName) {
132         if (!optionNameExist(optionName)) {
133             return null;
134         }
135         return (String JavaDoc) options.get(optionName);
136     }
137
138     /**
139      * returns true if the option name exist in the options list
140      *
141      * @ true if option name exist
142      */

143     private boolean optionNameExist(String JavaDoc optionName) {
144         return options.containsKey(optionName);
145     }
146
147
148     /**
149      * Sets the option value for the give name
150      *
151      * @param optionName name of the option
152      * @param optionValue value of the option
153      */

154     public void setOption(String JavaDoc optionName, String JavaDoc optionValue) {
155         options.put(optionName, optionValue);
156     }
157
158
159     /**
160      * Finds the option with the give name
161      *
162      * @return boolean return boolean type of the option value
163      */

164     protected boolean getBooleanOption(String JavaDoc optionName) {
165         return Boolean.valueOf(getOption(optionName));
166     }
167
168
169     /**
170      * execute the command (list or get)
171      *
172      * @param result - list inwhich results are stored
173      * @throws com.sun.enterprise.diagnostics.DiagnosticException
174      */

175     public void runCommand(ArrayList<String JavaDoc> result) throws DiagnosticException {
176         output = result;
177         //use http connector
178

179         final Object JavaDoc[] params = getDottedNamesParam
180                 (getName().equals(LIST_COMMAND) ?
181                 false : true);
182         final String JavaDoc[] types = new String JavaDoc[]{STRING_ARRAY};
183         final String JavaDoc operationName = getOperation();
184
185
186         try {
187
188             MBeanServer mbs = AppServerMBeanServerFactory.
189                     getMBeanServerInstance();
190             // we always invoke with an array, and so the
191
// result is always an Object []
192
final Object JavaDoc[] returnValues = (Object JavaDoc[]) mbs.
193                     invoke(new ObjectName(OBJECT_NAME),
194                     operationName, params, types);
195             if (operationName.indexOf("List") >= 0) {
196                 // a list operation, just print the String []
197
displayResultFromList((String JavaDoc []) returnValues);
198             }
199
200             else {
201                 final String JavaDoc[] userArgs = (String JavaDoc []) params[0];
202
203                 displayResultFromGetOrSet(userArgs, returnValues);
204             }
205         }
206
207         catch (InitException ie) {
208             logger.log(Level.WARNING, "Initialization" +
209                     " exception occurred while getting" +
210                     " MBean Server Instance", ie);
211             throw new DiagnosticException(ie.getMessage());
212         }
213
214         catch (Exception JavaDoc e) {
215             final String JavaDoc msg = getExceptionMessage(e);
216             if (msg != null) {
217                 logger.log(Level.WARNING, e.getMessage(), e);
218             }
219             throw new DiagnosticException(e.getMessage());
220         }
221     }
222
223     private static String JavaDoc OUTER_ARRAY_DELIM = System.
224             getProperty("line.separator"); // top-level array
225

226     /**
227      * figure out the returnValue type and call appropriate print methods
228      *
229      * @ params returnval
230      * @ throws CommandException if could not print AttributeList
231      */

232     private void
233             displayResultFromGetOrSet(final String JavaDoc[] inputs,
234                                       final Object JavaDoc [] returnValues)
235             throws Exception JavaDoc {
236         if (returnValues.length == 1) {
237             // there was a single string provided as input
238
final Object JavaDoc result = returnValues[0];
239
240             if (result instanceof Exception JavaDoc) {
241                 throw (Exception JavaDoc) result;
242             } else if (result.getClass() == Attribute[].class) {
243                 // this must have been the result of a wildcard input
244
final Attribute[] attrs = (Attribute[]) result;
245
246                 if (attrs.length == 0) {
247                     throw new AttributeNotFoundException("NoWildcardMatches");
248                 }
249
250                 printMessage(stringify(attrs, OUTER_ARRAY_DELIM));
251             } else {
252                 printMessage(stringify(result, OUTER_ARRAY_DELIM));
253             }
254         } else {
255             // more than one input String; collect all the resulting Attributes
256
// into one big non-duplicate sorted list and print them.
257
final Attribute[] attrs = collectAllAttributes(returnValues);
258
259             //addToResults( stringify( attrs, OUTER_ARRAY_DELIM ) );
260

261             for (Attribute attr : attrs) {
262                 addToResults(attr.getName() + " = " + attr.getValue());
263             }
264
265             // tell about any failures
266
for (int i = 0; i < returnValues.length; ++i) {
267                 if (returnValues[i] instanceof Exception JavaDoc) {
268                     final Exception JavaDoc e = (Exception JavaDoc) returnValues[i];
269
270                     final String JavaDoc msg = "ErrorInGetSet " +
271                             inputs[i] + e.getLocalizedMessage();
272
273                     printMessage(msg);
274                 }
275             }
276         }
277     }
278
279
280     /*
281          Extract all attributes from the results into one
282           large array without duplicates.
283      */

284     private Attribute []
285             collectAllAttributes(Object JavaDoc [] results) {
286         // use a HashMap to eliminate duplicates; use name as the key
287
final HashMap attrs = new HashMap();
288
289         for (final Object JavaDoc result : results) {
290             if (result instanceof Attribute) {
291                 attrs.put(((Attribute) result).getName(), result);
292             } else if (result instanceof Attribute[]) {
293                 final Attribute[] list = (Attribute[]) result;
294
295                 for (int attrIndex = 0; attrIndex < list.length; ++attrIndex) {
296                     final Attribute attr = list[attrIndex];
297
298                     attrs.put(attr.getName(), attr);
299                 }
300             } else {
301                 assert(result instanceof Exception JavaDoc);
302             }
303         }
304
305         final Attribute[] attrsArray = new Attribute[ attrs.size() ];
306         attrs.values().toArray(attrsArray);
307         Arrays.sort(attrsArray, new AttributeComparator());
308
309         return (attrsArray);
310     }
311
312 /*
313         Compare Attributes (for sorting). Attribute by itself
314         doesn't work correctly.
315      */

316
317     private final class AttributeComparator implements Comparator {
318         public int
319                 compare(Object JavaDoc o1, Object JavaDoc o2) {
320             final Attribute attr1 = (Attribute) o1;
321             final Attribute attr2 = (Attribute) o2;
322
323             return (attr1.getName().compareTo(attr2.getName()));
324         }
325
326         public boolean
327                 equals(Object JavaDoc other) {
328             return (other instanceof AttributeComparator);
329         }
330     }
331
332     /**
333      * get the dotted notation from the operand and convert it to a Object[]
334      *
335      * @return Object[]
336      */

337     private Object JavaDoc[] getDottedNamesParam(boolean convertUnderscore) {
338         final ArrayList<String JavaDoc> dottedNames = getOperands();
339         String JavaDoc [] dottedNamesArray = new String JavaDoc[dottedNames.size()];
340
341         for (int ii = 0; ii < dottedNames.size(); ii++) {
342             if (convertUnderscore) {
343                 dottedNamesArray[ii] = convertUnderscoreToHyphen
344                         (dottedNames.get(ii));
345             } else {
346                 dottedNamesArray[ii] = dottedNames.get(ii);
347             }
348         }
349         return new Object JavaDoc[]{dottedNamesArray};
350
351
352     }
353
354
355     /**
356      * get the operation to invoke depending on the command name and option
357      * if command name is "set" then the operation is dottedNameSet
358      * if command name is "get" then the operation is dottedNameGet
359      * if the command name is "get" with --monitor option to true, then the
360      * operation is dottedNameMonitoringGet
361      * all others return null.
362      *
363      * @return name of th operation
364      */

365     private String JavaDoc getOperation() {
366
367         if (getName().equals(GET_COMMAND)) {
368             if (getBooleanOption(MONITOR_OPTION)) {
369                 return GET_MONITORING_OPERATION;
370             } else {
371                 return GET_OPERATION;
372             }
373         } else if (getName().equals(LIST_COMMAND)) {
374             if (getBooleanOption(MONITOR_OPTION)) {
375                 return LIST_MONITORING_OPERATION;
376             } else {
377                 return LIST_OPERATION;
378             }
379         }
380         return null;
381
382     }
383
384     /**
385      * Log the messages
386      *
387      * @param msg
388      */

389     private void printMessage(String JavaDoc msg) {
390         logger.log(Level.INFO, msg, "INFO");
391     }
392
393     /**
394      * add the results to output
395      *
396      * @param msg
397      */

398     private void addToResults(String JavaDoc msg) {
399         if (output != null) {
400             output.add(msg);
401
402         }
403     }
404
405
406     private String JavaDoc
407             getExceptionMessage(Exception JavaDoc e) {
408         String JavaDoc msg = null;
409
410         if (e instanceof RuntimeMBeanException) {
411             RuntimeMBeanException rmbe = (RuntimeMBeanException) e;
412             msg = rmbe.getTargetException().getLocalizedMessage();
413         } else if (e instanceof RuntimeOperationsException) {
414             RuntimeOperationsException roe = (RuntimeOperationsException) e;
415             msg = roe.getTargetException().getLocalizedMessage();
416         } else {
417             msg = e.getLocalizedMessage();
418         }
419         if (msg == null || msg.length() == 0) {
420             msg = e.getMessage();
421         }
422
423         if (msg == null || msg.length() == 0) {
424             msg = e.getClass().getName();
425         }
426
427         return (msg);
428     }
429
430     private static String JavaDoc INNER_ARRAY_DELIM = ",";
431     // when an array is inside another
432

433     private String JavaDoc stringifyArray(final Object JavaDoc [] a, String JavaDoc delim) {
434         final StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
435
436         for (int i = 0; i < a.length; ++i) {
437             buf.append(stringify(a[i], INNER_ARRAY_DELIM));
438             if (i != a.length - 1) {
439                 buf.append(delim);
440             }
441         }
442         return (buf.toString());
443     }
444
445
446     /*
447          Turn the object into a String suitable for display to the user.
448       */

449     private String JavaDoc stringify(Object JavaDoc o, String JavaDoc delim) {
450         String JavaDoc result = null;
451
452         if (o == null) {
453             result = "";
454         } else if (o instanceof Attribute) {
455             final Attribute attr = (Attribute) o;
456
457             result = attr.getName() + " = " + stringify(attr.getValue(),
458                     INNER_ARRAY_DELIM);
459         } else if (ClassUtil.objectIsPrimitiveArray(o)) {
460             final Object JavaDoc [] objectList = ArrayConversion.toAppropriateType(o);
461
462             result = stringifyArray(objectList, delim);
463         } else if (ClassUtil.objectIsArray(o)) {
464             result = stringifyArray((Object JavaDoc []) o, delim);
465         } else if (o instanceof Exception JavaDoc) {
466             final Exception JavaDoc e = (Exception JavaDoc) o;
467
468             result = getExceptionMessage(e);
469         } else {
470             result = o.toString();
471         }
472
473
474         return (result);
475     }
476
477     private void displayResultFromList(final String JavaDoc [] result) {
478         if (result.length == 0) {
479             //need to convert the operands to String for display
480

481             final String JavaDoc displayOperands = stringify(getDottedNamesParam(true),
482                     INNER_ARRAY_DELIM);
483             printMessage("EmptyList - " + displayOperands);
484         } else {
485             for (String JavaDoc value : result) {
486                 addToResults(value);
487             }
488         }
489     }
490
491
492     /**
493      * This method will convert the attribute in the dotted name notation
494      * from underscore to hyphen.
495      *
496      * @param param - the dotted name to convert
497      * @return the converted string
498      */

499     public String JavaDoc convertUnderscoreToHyphen(String JavaDoc param) {
500         int endIndex = param.indexOf('=');
501         int begIndex = (endIndex > 0) ? param.lastIndexOf('.', endIndex) :
502                 param.lastIndexOf('.');
503         if (begIndex < 1 || checkPropertyToConvert(
504                 param.substring(0, begIndex))) {
505             return param;
506         }
507         if (endIndex > 0) {
508             return param.substring(0, begIndex) +
509                     param.substring(begIndex, endIndex).replace('_', '-') +
510                     param.substring(endIndex);
511         } else {
512             return param.substring(0, begIndex) +
513                     param.substring(begIndex).replace('_', '-');
514         }
515     }
516
517     /**
518      * This method checks if the element in the dotted name contains "property"
519      * or "system-property". If the element is "property" or "system-property"
520      * then return true else return false.
521      *
522      * @param param - dotted name
523      * @return true if dotted name contains "property" or "system-property"
524      * false
525      */

526     public boolean checkPropertyToConvert(String JavaDoc param) {
527         final int index = param.lastIndexOf('.');
528         if (index < 0) {
529             return false;
530         }
531         final String JavaDoc elementName = param.substring(index + 1);
532         return elementName.matches(PROPERTY_STRING);
533     }
534 }
535
Popular Tags