KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > cli > jmx > cmd > CmdBase


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 /*
25  * $Header: /cvs/glassfish/admin-cli/cli-api/src/java/com/sun/cli/jmx/cmd/CmdBase.java,v 1.3 2005/12/25 03:45:28 tcfujii Exp $
26  * $Revision: 1.3 $
27  * $Date: 2005/12/25 03:45:28 $
28  */

29  
30
31 package com.sun.cli.jmx.cmd;
32
33 import java.util.HashMap JavaDoc;
34 import java.util.Arrays JavaDoc;
35 import java.util.Iterator JavaDoc;
36
37 import java.util.regex.Pattern JavaDoc;
38 import java.util.regex.Matcher JavaDoc;
39
40 import com.sun.cli.util.stringifier.SmartStringifier;
41 import com.sun.cli.util.stringifier.Stringifier;
42 import com.sun.cli.util.stringifier.StringifierRegistry;
43 import com.sun.cli.util.stringifier.ArrayStringifier;
44 import com.sun.cli.util.DebugState;
45
46 import com.sun.cli.jmx.cmd.ArgHelper;
47
48 public abstract class CmdBase implements Cmd, CmdOutput, DebugState
49 {
50     public final static String JavaDoc ENV_TOKENS = "TOKENS";
51     public final static String JavaDoc ENV_CMD_RUNNER = "CMD_RUNNER";
52     public final static String JavaDoc ENV_CMD_FACTORY = "CMD_FACTORY";
53     public final static String JavaDoc ENV_COMMANDS = "COMMANDS";
54     
55     // user accessible
56
public final static String JavaDoc ENV_DEBUG = "debug";
57     
58     private final CmdEnv mEnv;
59     final String JavaDoc [] mTokens;
60     private ArgHelper mArgHelper;
61     
62     private CmdOutput mOutput;
63     
64     Stringifier mStringifier =
65         new SmartStringifier( StringifierRegistry.DEFAULT, "\n", false );
66     
67     // debug message
68
void
69     dm( Object JavaDoc o )
70     {
71         mOutput.println( mStringifier.stringify( o ) );
72     }
73     
74     CmdBase( final CmdEnv env )
75     {
76         mEnv = env;
77         
78         mOutput = new CmdOutputImpl( System.out, System.err );
79         
80         mTokens = (String JavaDoc [])env.get( "TOKENS" );
81         
82         // can't instantiate here; need the result of virtual method getOptionInfo()
83
mArgHelper = null;
84     }
85     
86     /*
87         Wrapper around the cmd-supplied OptionsInfo which allows us to layer
88         additional global options onto the command, such as -h, --help.
89      */

90     private static class OptionsInfoWrapper implements ArgHelper.OptionsInfo
91     {
92         final ArgHelper.OptionsInfo mInfo;
93         
94         OptionsInfoWrapper( ArgHelper.OptionsInfo info )
95         {
96             mInfo = info;
97         }
98         
99             static boolean
100         isHelp( String JavaDoc token )
101         {
102             return( token.equalsIgnoreCase( "-h" ) ||
103                         token.equalsIgnoreCase( "--help" ) ||
104                         token.equalsIgnoreCase( "-help" ) );
105         }
106         
107         public String JavaDoc tokenToOptionName( String JavaDoc token )
108         { return( mInfo.tokenToOptionName( token ) ); }
109             
110         public String JavaDoc tokenToOptionData( String JavaDoc token )
111         { return( mInfo.tokenToOptionData( token ) ); }
112             
113         public boolean isLegalOption( String JavaDoc token )
114         {
115             return( mInfo.isLegalOption( token ) || isHelp( token ) );
116         }
117             
118         public boolean isBoolean( String JavaDoc token )
119         { return( isHelp( token ) ? true : mInfo.isBoolean( token ) ); }
120             
121         public int getNumValues( String JavaDoc token )
122         { return( isHelp( token ) ? 0 : mInfo.getNumValues( token ) ); }
123     }
124     
125         void
126     initArgHelper()
127         throws ArgHelper.IllegalOptionException
128     {
129         if ( mArgHelper == null )
130         {
131             final java.util.ListIterator JavaDoc iter =
132                 Arrays.asList( mTokens ).listIterator( 1 );
133             
134             final ArgHelper.OptionsInfo optionsInfo = getOptionInfo();
135             
136             mArgHelper = new ArgHelperImpl( iter, new OptionsInfoWrapper( optionsInfo ) );
137         }
138     }
139     
140         CmdFactory
141     getCmdFactory()
142     {
143         return( (CmdFactory)envGet( ENV_CMD_FACTORY ) );
144     }
145     
146     
147         void
148     envRemove( String JavaDoc key)
149     {
150         mEnv.remove( key );
151     }
152     
153         Object JavaDoc
154     envGet( String JavaDoc key)
155     {
156         return( mEnv.get( key ) );
157     }
158     
159         Object JavaDoc
160     envGet( String JavaDoc key, Object JavaDoc defaultValue )
161     {
162         Object JavaDoc value = envGet( key );
163         
164         if ( value == null )
165         {
166             value = defaultValue;
167         }
168
169         return( value );
170     }
171     
172         java.util.Set JavaDoc
173     getEnvKeys( )
174     {
175         return( mEnv.getKeys() );
176     }
177     
178         java.util.Set JavaDoc
179     getEnvKeys( String JavaDoc regExp )
180     {
181         final Iterator JavaDoc iter = getEnvKeys().iterator();
182         final java.util.Set JavaDoc filteredSet = new java.util.HashSet JavaDoc();
183         
184         final Pattern JavaDoc pattern = Pattern.compile( regExp );
185         
186         while ( iter.hasNext() )
187         {
188             final String JavaDoc key = (String JavaDoc)iter.next();
189             
190             final Matcher JavaDoc m = pattern.matcher( key );
191             
192             if ( m.matches() )
193             {
194                 filteredSet.add( key );
195             }
196             
197         }
198
199         return( filteredSet );
200     }
201     
202         void
203     envPut( String JavaDoc key, Object JavaDoc value, boolean allowPersistence )
204     {
205         mEnv.put( key, value, allowPersistence);
206     }
207     
208         ArgHelper
209     getArgHelper()
210     {
211         assert( mArgHelper != null );
212         
213         return( mArgHelper );
214     }
215     
216         int
217     countOptions( )
218         throws ArgHelper.IllegalOptionException
219     {
220         return( getArgHelper().countOptions( ) );
221     }
222     
223         String JavaDoc
224     getString( String JavaDoc name, String JavaDoc defaultValue)
225         throws ArgHelper.IllegalOptionException
226     {
227         return( getArgHelper().getString( name, defaultValue ) );
228     }
229     
230     
231         Integer JavaDoc
232     getInteger( String JavaDoc name)
233         throws ArgHelper.IllegalOptionException
234     {
235         return( getArgHelper().getInteger( name ) );
236     }
237     
238         Boolean JavaDoc
239     getBoolean( String JavaDoc name, Boolean JavaDoc defaultValue)
240         throws ArgHelper.IllegalOptionException
241     {
242         return( getArgHelper().getBoolean( name, defaultValue ) );
243     }
244     
245         String JavaDoc []
246     getOperands( )
247     {
248         return( getArgHelper().getOperands( ) );
249     }
250     
251         String JavaDoc
252     getCmdNameAsInvoked( )
253     {
254         return( mTokens[ 0 ] );
255     }
256     
257         void
258     requireNumOperands( final int numRequiredOperands)
259          throws WrongNumberOfOperandsException
260     {
261         final String JavaDoc [] operands = getOperands();
262         
263         if ( operands.length < numRequiredOperands )
264         {
265             requireNumOperandsFailed( operands.length, numRequiredOperands, null);
266         }
267     }
268     
269         void
270     requireNumOperands( final int numRequiredOperands, String JavaDoc msg)
271          throws WrongNumberOfOperandsException
272     {
273         final String JavaDoc [] operands = getOperands();
274         
275         if ( operands.length < numRequiredOperands )
276         {
277             requireNumOperandsFailed( operands.length, numRequiredOperands, msg);
278         }
279     }
280     
281         int
282     getNumRequiredOperands()
283     {
284         // require 1, by default
285
return( 1 );
286     }
287     
288     class WrongNumberOfOperandsException extends Exception JavaDoc
289     {
290         WrongNumberOfOperandsException( String JavaDoc msg )
291         {
292             super( msg );
293         }
294     }
295     
296         void
297     requireNumOperandsFailed( int numSupplied, int numRequired, String JavaDoc msg)
298          throws WrongNumberOfOperandsException
299     {
300         printError( "ERROR: " + numRequired + " arguments required, " + numSupplied + " supplied" );
301         if ( msg != null )
302         {
303             println( msg );
304         }
305         else
306         {
307             printUsage();
308         }
309         throw new WrongNumberOfOperandsException( "illlegal number of operands" );
310     }
311     
312     
313         ArgHelper.OptionsInfo
314     getOptionInfo()
315         throws ArgHelper.IllegalOptionException
316     {
317         // default to none
318
return( new ArgHelperOptionsInfo( ) );
319     }
320     
321     
322         public void
323     print( Object JavaDoc o )
324     {
325         mOutput.print( o );
326     }
327     
328         public void
329     println( Object JavaDoc o )
330     {
331         mOutput.println( o );
332     }
333     
334         public void
335     printError( Object JavaDoc o )
336     {
337         mOutput.printError( o );
338     }
339     
340         public void
341     printDebug( Object JavaDoc o )
342     {
343         mOutput.printDebug( o );
344     }
345     
346         public boolean
347     getDebug()
348     {
349         boolean isDebug = false;
350         final String JavaDoc value = (String JavaDoc)envGet( ENV_DEBUG );
351         if ( value != null )
352         {
353             isDebug = value.equalsIgnoreCase( "true" ) ||
354                         value.equalsIgnoreCase( "t" ) ||
355                         value.equalsIgnoreCase( "yes" )||
356                         value.equalsIgnoreCase( "y" );
357         }
358         return( isDebug );
359     }
360     
361         void
362     preExecute()
363         throws Exception JavaDoc
364     {
365         initArgHelper();
366         requireNumOperands( getNumRequiredOperands() );
367     }
368     
369         void
370     handleException( final Exception JavaDoc e )
371     {
372         if ( e instanceof WrongNumberOfOperandsException )
373         {
374             // already reported
375
}
376         else if ( e instanceof ArgHelper.IllegalOptionException )
377         {
378             printError( "ERROR: " + e.getMessage() );
379             printUsage();
380         }
381         else if ( e instanceof java.io.IOException JavaDoc)
382         {
383             printError( "ERROR: " + e.getMessage() );
384         }
385         else
386         {
387             printError( "ERROR: exception of type: " +
388                 e.getClass().getName() + ", msg = " + e.getMessage() );
389             e.printStackTrace();
390         }
391     }
392     
393         public final void
394     execute( )
395         throws Exception JavaDoc
396     {
397         try
398         {
399             preExecute();
400         
401             if ( getBoolean( "help", Boolean.FALSE ).booleanValue() ||
402                     getBoolean( "h", Boolean.FALSE ).booleanValue() )
403             {
404                 printUsage();
405             }
406             else
407             {
408                 executeInternal( );
409             }
410         }
411         catch( Exception JavaDoc e )
412         {
413             handleException( e );
414             e.printStackTrace();
415         }
416     }
417     
418     abstract void executeInternal( ) throws Exception JavaDoc;
419     abstract String JavaDoc getUsage( );
420         
421     private static final Class JavaDoc [] EMPTY_SIG = new Class JavaDoc [ 0 ];
422     private static final Object JavaDoc [] EMPTY_ARGS = new Object JavaDoc [ 0 ];
423     
424         public static String JavaDoc []
425     getCmdNames( final Class JavaDoc theClass )
426         throws java.lang.NoSuchMethodException JavaDoc,
427             java.lang.IllegalAccessException JavaDoc, java.lang.reflect.InvocationTargetException JavaDoc
428     {
429         String JavaDoc [] names = null;
430         
431         final java.lang.reflect.Method JavaDoc m = theClass.getDeclaredMethod( "getNames", EMPTY_SIG );
432     
433         names = (String JavaDoc [])m.invoke( theClass, EMPTY_ARGS);
434         
435         return( names );
436     }
437     
438         String JavaDoc
439     getAlsoKnownAs( Class JavaDoc theClass )
440     {
441         String JavaDoc aka = "";
442         
443         try
444         {
445             aka = ArrayStringifier.stringify( getCmdNames( theClass ), " " );
446         }
447         catch( Exception JavaDoc e )
448         {
449             // Hmmm..
450
}
451         
452         return( "Also known as: " + aka );
453     }
454     
455         void
456     printUsage()
457     {
458         println( getUsage() );
459         
460         
461         println( getAlsoKnownAs( this.getClass() ) );
462     }
463 }
464
465
Popular Tags