KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > commands > DottedNamesCommand


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.cli.commands;
25
26 import com.sun.enterprise.cli.framework.*;
27 import com.sun.enterprise.admin.util.ClassUtil;
28 import com.sun.enterprise.admin.util.ArrayConversion;
29 import javax.management.Attribute JavaDoc;
30 import javax.management.MBeanServerConnection JavaDoc;
31 import javax.management.ObjectName JavaDoc;
32 import javax.management.AttributeNotFoundException JavaDoc;
33 import javax.management.RuntimeMBeanException JavaDoc;
34 import javax.management.RuntimeOperationsException JavaDoc;
35
36
37 import java.util.Vector JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.Arrays JavaDoc;
40
41
42 /**
43  * This is class handles get, set and list commands
44  * @version $Revision: 1.3 $
45  */

46 public class DottedNamesCommand extends S1ASCommand
47 {
48
49     private static final String JavaDoc GET_COMMAND = "get";
50     private static final String JavaDoc SET_COMMAND = "set";
51     private static final String JavaDoc LIST_COMMAND = "list";
52     private static final String JavaDoc GET_OPERATION = "dottedNameGet";
53     private static final String JavaDoc LIST_OPERATION = "dottedNameList";
54     private static final String JavaDoc GET_MONITORING_OPERATION = "dottedNameMonitoringGet";
55     private static final String JavaDoc LIST_MONITORING_OPERATION = "dottedNameMonitoringList";
56     private static final String JavaDoc SET_OPERATION = "dottedNameSet";
57     private static final String JavaDoc MONITOR_OPTION = "monitor";
58     private static final String JavaDoc OBJECT_NAME = "com.sun.appserv:name=dotted-name-get-set,type=dotted-name-support";
59     private static final String JavaDoc INTERVAL_OPTION = "interval";
60     private static final String JavaDoc ITERATIONS_OPTION = "iterations";
61     private static final String JavaDoc PROPERTY_STRING = "property|system-property";
62
63
64     /**
65      * This method validates the options for this command
66      * @return boolean returns true if success else returns false
67      * @throws CommandValidationException
68      */

69     public boolean validateOptions() throws CommandValidationException
70     {
71         // if monitor option is specified for a get operation and
72
// the interval and iterations specified along with it, we need to make
73
// sure that the values specified for interval and iterations
74
// are valid
75
if(getOperation().equals(GET_MONITORING_OPERATION))
76         {
77             if(!(isIntervalValid() && isIterationValid()))
78                 return false;
79         }
80         return super.validateOptions();
81     }
82
83     private boolean isIntervalValid(){
84         
85         String JavaDoc interval = getOption(INTERVAL_OPTION);
86         
87         if(interval == null)
88             return true;
89         else if((interval != null) && (Integer.parseInt(interval) > 0))
90             return true;
91         else
92         {
93             printMessage(getLocalizedString("InvalidInterval", new Object JavaDoc[] {interval}));
94             return false;
95         }
96     }
97     
98     private boolean isIterationValid() {
99         
100         String JavaDoc iterations = getOption(ITERATIONS_OPTION);
101         
102         if(iterations == null)
103             return true;
104         else if((iterations != null) && (Integer.parseInt(iterations) > 0))
105             return true;
106         else
107         {
108             printMessage(getLocalizedString("InvalidIterations", new Object JavaDoc[] {iterations}));
109             return false;
110         }
111     }
112     
113     /*
114         Compare Attributes (for sorting). Attribute by itself doesn't work correctly.
115      */

116     private final class AttributeComparator implements java.util.Comparator JavaDoc
117     {
118             public int
119         compare( Object JavaDoc o1, Object JavaDoc o2 )
120         {
121             final Attribute JavaDoc attr1 = (Attribute JavaDoc)o1;
122             final Attribute JavaDoc attr2 = (Attribute JavaDoc)o2;
123             
124             return( attr1.getName().compareTo( attr2.getName() ) );
125         }
126         
127             public boolean
128         equals( Object JavaDoc other )
129         {
130             return( other instanceof AttributeComparator );
131         }
132     }
133     
134     /*
135         Extract all attributes from the results into one large array without duplicates.
136     */

137         private Attribute JavaDoc []
138     collectAllAttributes( Object JavaDoc [] results )
139     {
140         // use a HashMap to eliminate duplicates; use name as the key
141
final HashMap JavaDoc attrs = new HashMap JavaDoc();
142         
143         for( int i = 0; i < results.length; ++i )
144         {
145             final Object JavaDoc result = results[ i ];
146             
147             if ( result instanceof Attribute JavaDoc )
148             {
149                 attrs.put( ((Attribute JavaDoc)result).getName(), result );
150             }
151             else if ( result instanceof Attribute JavaDoc[] )
152             {
153                 final Attribute JavaDoc[] list = (Attribute JavaDoc[])result;
154                 
155                 for( int attrIndex = 0; attrIndex < list.length; ++attrIndex )
156                 {
157                     final Attribute JavaDoc attr = list[ attrIndex ];
158                     
159                     attrs.put( attr.getName(), attr );
160                 }
161             }
162             else
163             {
164                 assert( result instanceof Exception JavaDoc );
165             }
166         }
167         
168         final Attribute JavaDoc[] attrsArray = new Attribute JavaDoc[ attrs.size() ];
169         attrs.values().toArray( attrsArray );
170         Arrays.sort( attrsArray, new AttributeComparator() );
171         
172         return( attrsArray );
173     }
174     
175     /**
176      * An abstract method that Executes the command
177      * @throws CommandException
178      */

179     public void runCommand() throws CommandException, CommandValidationException
180     {
181         if(!validateOptions())
182             return;
183
184         //use http connector
185
final MBeanServerConnection JavaDoc mbsc = getMBeanServerConnection(getHost(),
186                                         getPort(),
187                                         getUser(),
188                                         getPassword());
189         final Object JavaDoc[] params = getDottedNamesParam(getName().equals(LIST_COMMAND)?
190                                                     false:true);
191         final String JavaDoc[] types = new String JavaDoc[] {STRING_ARRAY};
192         final String JavaDoc operationName = getOperation();
193         final String JavaDoc interval = getOption(INTERVAL_OPTION);
194         final String JavaDoc iterations = getOption(ITERATIONS_OPTION);
195         
196         try
197         {
198             // we always invoke with an array, and so the result is always an Object []
199
final Object JavaDoc[] returnValues = (Object JavaDoc[])mbsc.invoke(new ObjectName JavaDoc(OBJECT_NAME),
200                                 operationName, params, types);
201             if ( operationName.indexOf( "List" ) >= 0)
202             {
203                 // a list operation, just print the String []
204
displayResultFromList( (String JavaDoc [])returnValues );
205             }
206             else if(operationName.equals(this.GET_MONITORING_OPERATION) && (interval != null) && (iterations != null))
207             {
208                 String JavaDoc[] userArgs = (String JavaDoc [])params[ 0 ];
209                 displayResultFromGetOrSet( userArgs, returnValues );
210                 long interval_millis = Integer.parseInt(interval) * 1000;
211                 int counter = Integer.parseInt(iterations);
212                 int i = 1;
213                 do {
214                     printMessage("\n");
215                     if (i < counter) {
216                         try {
217                             Thread.currentThread().sleep(interval_millis);
218                             Object JavaDoc[] retVals = (Object JavaDoc[]) mbsc.invoke(new ObjectName JavaDoc(OBJECT_NAME),
219                                                                       operationName,
220                                                                       params,
221                                                                       types);
222                             userArgs = (String JavaDoc []) params[0];
223                             displayResultFromGetOrSet(userArgs, retVals);
224                             ++i;
225                         } catch (InterruptedException JavaDoc ie) {
226                         }
227                     }
228                 }while(i < counter);
229             }
230             else
231             {
232                 final String JavaDoc[] userArgs = (String JavaDoc [])params[ 0 ];
233                 
234                 displayResultFromGetOrSet( userArgs, returnValues );
235             }
236         }
237         catch(Exception JavaDoc e)
238         {
239             final String JavaDoc msg = getExceptionMessage( e );
240             if ( msg != null)
241             {
242                 CLILogger.getInstance().printDetailMessage( msg );
243             }
244             
245             throw new CommandException(getLocalizedString("CommandUnSuccessful",
246                                   new Object JavaDoc[] {name} ), e);
247         }
248     }
249
250
251     /**
252      * get the dotted notation from the operand and convert it to a Object[]
253      * @return Object[]
254      */

255     private Object JavaDoc[] getDottedNamesParam(boolean convertUnderscore)
256     {
257         final Vector JavaDoc dottedNames = getOperands();
258         String JavaDoc [] dottedNamesArray = new String JavaDoc[dottedNames.size()];
259         
260         for (int ii=0; ii<dottedNames.size(); ii++)
261         {
262             if (convertUnderscore)
263                 dottedNamesArray[ii] = convertUnderscoreToHyphen((String JavaDoc)dottedNames.get(ii));
264             else
265                 dottedNamesArray[ii] = (String JavaDoc)dottedNames.get(ii);
266         }
267         return new Object JavaDoc[]{dottedNamesArray};
268         
269         //return new Object[] {(String[])dottedNames.toArray(new String[dottedNames.size()])};
270
}
271
272
273     /**
274      * get the operation to invoke depending on the command name and option
275      * if command name is "set" then the operation is dottedNameSet
276      * if command name is "get" then the operation is dottedNameGet
277      * if the command name is "get" with --monitor option to true, then the
278      * operation is dottedNameMonitoringGet
279      * all others return null.
280      * @return name of th operation
281      */

282     private String JavaDoc getOperation()
283     {
284         if (getName().equals(SET_COMMAND))
285             return SET_OPERATION;
286         else if (getName().equals(GET_COMMAND))
287         {
288             if (getBooleanOption(MONITOR_OPTION))
289                 return GET_MONITORING_OPERATION;
290             else
291                 return GET_OPERATION;
292         }
293         else if (getName().equals(LIST_COMMAND))
294         {
295             if (getBooleanOption(MONITOR_OPTION))
296                 return LIST_MONITORING_OPERATION;
297             else
298                 return LIST_OPERATION;
299         }
300         return null;
301     }
302
303     private void printMessage( String JavaDoc msg )
304     {
305         CLILogger.getInstance().printMessage( msg );
306     }
307
308         private String JavaDoc
309     getExceptionMessage( Exception JavaDoc e )
310     {
311         String JavaDoc msg = null;
312
313         if (e instanceof RuntimeMBeanException JavaDoc) {
314             RuntimeMBeanException JavaDoc rmbe = (RuntimeMBeanException JavaDoc) e;
315             msg = rmbe.getTargetException().getLocalizedMessage();
316         } else if (e instanceof RuntimeOperationsException JavaDoc) {
317             RuntimeOperationsException JavaDoc roe = (RuntimeOperationsException JavaDoc) e;
318             msg = roe.getTargetException().getLocalizedMessage();
319         } else {
320             msg = e.getLocalizedMessage();
321         }
322         if ( msg == null || msg.length() == 0 )
323         {
324             msg = e.getMessage();
325         }
326             
327         if ( msg == null || msg.length() == 0 )
328         {
329             msg = e.getClass().getName();
330         }
331         
332         return( msg );
333     }
334     
335   
336
337
338     private static String JavaDoc INNER_ARRAY_DELIM = ","; // when an array is inside another
339
private static String JavaDoc OUTER_ARRAY_DELIM = System.getProperty("line.separator"); // top-level array
340

341     /**
342      * figure out the returnValue type and call appropriate print methods
343      * @params returnval
344      * @throws CommandException if could not print AttributeList
345      */

346         private void
347     displayResultFromGetOrSet( final String JavaDoc[] inputs, final Object JavaDoc [] returnValues )
348         throws Exception JavaDoc
349     {
350         if ( returnValues.length == 1 )
351         {
352             // there was a single string provided as input
353
final Object JavaDoc result = returnValues[ 0 ];
354             
355             if ( result instanceof Exception JavaDoc )
356             {
357                 throw (Exception JavaDoc) result;
358             }
359             else if ( result.getClass() == Attribute JavaDoc[].class )
360             {
361                 // this must have been the result of a wildcard input
362
final Attribute JavaDoc[] attrs = (Attribute JavaDoc[])result;
363                 
364                 if ( attrs.length == 0 )
365                 {
366                     throw new AttributeNotFoundException JavaDoc( getLocalizedString("NoWildcardMatches") );
367                 }
368                 
369                 printMessage( stringify( attrs, OUTER_ARRAY_DELIM ) );
370             }
371             else
372             {
373                 printMessage( stringify( result, OUTER_ARRAY_DELIM ) );
374             }
375         }
376         else
377         {
378             // more than one input String; collect all the resulting Attributes
379
// into one big non-duplicate sorted list and print them.
380
final Attribute JavaDoc[] attrs = collectAllAttributes( returnValues );
381             
382             printMessage( stringify( attrs, OUTER_ARRAY_DELIM ) );
383             
384             // tell about any failures
385
for( int i = 0; i < returnValues.length; ++i )
386             {
387                 if ( returnValues[ i ] instanceof Exception JavaDoc )
388                 {
389                     final Exception JavaDoc e = (Exception JavaDoc)returnValues[ i ];
390                     
391                     final String JavaDoc msg = getLocalizedString( "ErrorInGetSet",
392                         new Object JavaDoc [] { inputs[ i ], getExceptionMessage( e ) } );
393                         
394                     printMessage( msg );
395                 }
396             }
397         }
398         
399         return;
400     }
401     
402     
403         private String JavaDoc
404     stringifyArray( final Object JavaDoc [] a, String JavaDoc delim )
405     {
406         final StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
407     
408         for( int i = 0; i < a.length; ++i )
409         {
410             buf.append( stringify( a[ i ], INNER_ARRAY_DELIM ) );
411             if ( i != a.length - 1 )
412             {
413                 buf.append( delim );
414             }
415         }
416         return( buf.toString() );
417     }
418     
419         private String JavaDoc
420     stringify( Object JavaDoc o )
421     {
422         return( stringify( o, "\n" ) );
423     }
424
425     /*
426         Turn the object into a String suitable for display to the user.
427      */

428         private String JavaDoc
429     stringify( Object JavaDoc o, String JavaDoc delim )
430     {
431         String JavaDoc result = null;
432         
433         if ( o == null )
434         {
435             result = "";
436         }
437         else if ( o instanceof Attribute JavaDoc )
438         {
439             final Attribute JavaDoc attr = (Attribute JavaDoc)o;
440             
441             result = attr.getName() + " = " + stringify( attr.getValue(), INNER_ARRAY_DELIM );
442         }
443         else if ( ClassUtil.objectIsPrimitiveArray( o ) )
444         {
445            final Object JavaDoc [] objectList = ArrayConversion.toAppropriateType( o );
446            
447            result = stringifyArray( objectList, delim );
448         }
449         else if ( ClassUtil.objectIsArray( o ) )
450         {
451             result = stringifyArray( (Object JavaDoc [])o, delim );
452         }
453         else if ( o instanceof Exception JavaDoc )
454         {
455             final Exception JavaDoc e = (Exception JavaDoc)o;
456             
457             result = getExceptionMessage( e );
458         }
459         else
460         {
461             result = o.toString();
462         }
463         
464         assert( result != null );
465         return( result );
466     }
467
468     
469
470     
471     private void displayResultFromList( final String JavaDoc [] result )
472     {
473         if ( result.length == 0 )
474         {
475             //need to convert the operands to String for display
476

477             final String JavaDoc displayOperands = stringify(getDottedNamesParam(true),
478                                                      INNER_ARRAY_DELIM);
479             printMessage(getLocalizedString("EmptyList", new Object JavaDoc[] {
480                 displayOperands }));
481         }
482         else
483         {
484             printMessage( stringify( result, OUTER_ARRAY_DELIM ) );
485         }
486     }
487
488
489     /**
490      * This method will convert the attribute in the dotted name notation
491      * from underscore to hyphen.
492      * @param param - the dotted name to convert
493      * @return the converted string
494      */

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

515     public boolean checkPropertyToConvert(String JavaDoc param)
516     {
517         final int index = param.lastIndexOf('.');
518         if (index < 0) return false;
519         final String JavaDoc elementName = param.substring(index+1);
520         if (elementName.matches(PROPERTY_STRING))
521             return true;
522         else
523             return false;
524     }
525     
526     
527 }
528
Popular Tags