KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > framework > Command


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.framework;
25
26 import java.util.Vector JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.regex.Pattern JavaDoc;
33 import java.util.regex.Matcher JavaDoc;
34
35 /**
36  * <code>Command<code> object is the super Base class for all the commands.
37  * This is a generic Command Class which would fit
38  * into any Command Line Interface (CLI) module.
39  * @version $Revision: 1.6 $
40  */

41 abstract public class Command implements ICommand
42 {
43
44     private static final char REPLACE_START_CHAR = '{';
45     private static final char REPLACE_END_CHAR = '}';
46     private static final char VARIABLE_START_CHAR = '$';
47     private static final char OPERAND_START_CHAR = '#';
48     private static final String JavaDoc PATTERN_MATCHING = "\\{([\\$\\#])(\\w[\\w\\-]*)\\}";
49         //private static final String PATTERN_MATCHING = "\\{([\\$\\#])(\\w+)\\}";
50

51     protected String JavaDoc name = null;
52     //protected HashMap options;
53
protected HashMap JavaDoc clOptions;
54     protected HashMap JavaDoc envOptions;
55     protected Vector JavaDoc operands;
56     protected String JavaDoc usageStr = null;
57     protected Hashtable JavaDoc properties;
58     private List JavaDoc booleanOptionsList = null;
59     
60     /** Creates new Command */
61     public Command()
62     {
63         operands = new Vector JavaDoc();
64         //options = new HashMap();
65
clOptions = new HashMap JavaDoc();
66         envOptions = new HashMap JavaDoc();
67     }
68     
69     /**
70      * An abstract method that Executes the command
71      * @throws CommandException
72      */

73     abstract public void runCommand()
74         throws CommandException, CommandValidationException;
75
76     /**
77      * An abstract method that validates the options
78      * on the specification in the xml properties file
79      * This method verifies for the correctness of number of
80      * operands and if all the required options are supplied by the client.
81      * @return boolean returns true if success else returns false
82      */

83     abstract public boolean validateOptions() throws CommandValidationException;
84
85     
86     /**
87      * Gets the name of the command
88      * @return String the name of the command
89      */

90     public String JavaDoc getName()
91     {
92         return name;
93     }
94     
95     /**
96      * Sets the name of the command
97      * @param String the name of the command
98      */

99     public void setName(String JavaDoc name)
100     {
101         this.name = name;
102     }
103     
104     /**
105      * Gets the list of operands of this command
106      * @return Vector the list of operands.
107      */

108     public Vector JavaDoc getOperands()
109     {
110         return operands;
111     }
112     
113     /**
114      * Sets the list of operands for this command
115      * @param Vector the list of operands.
116      */

117     public void setOperands(Vector JavaDoc operands)
118     {
119         this.operands = operands;
120     }
121     
122     /**
123      * Gets the list of options for this Command
124      * @return Vector List of options for this command
125      */

126     public HashMap JavaDoc getOptions()
127     {
128         HashMap JavaDoc options = new HashMap JavaDoc(clOptions);
129         Iterator JavaDoc optionNames = envOptions.keySet().iterator();
130         while (optionNames.hasNext())
131         {
132             final String JavaDoc optionKey = (String JavaDoc) optionNames.next();
133             if (!options.containsKey(optionKey))
134                 options.put(optionKey, (String JavaDoc) envOptions.get(optionKey));
135         }
136         return options;
137     }
138     
139     
140     /**
141      * Gets the list of options read from command line for this Command
142      * @return Vector List of options for this command
143      */

144     public HashMap JavaDoc getCLOptions()
145     {
146         return clOptions;
147     }
148     
149     /**
150      * Gets the list of options read from environment for this Command
151      * @return Vector List of options for this command
152      */

153     public HashMap JavaDoc getENVOptions()
154     {
155         return envOptions;
156     }
157     
158     /**
159      * Sets the list of options for this Command
160      * @param options List of options for this command
161      */

162     /*
163     public void setOptions(HashMap options)
164     {
165         this.options = options;
166     }
167     */

168     
169     
170     /**
171      * Sets the list of options read from Command Line for this Command
172      * @param clOptions List of options for this command
173      */

174     public void setCLOptions(HashMap JavaDoc clOptions)
175     {
176         this.clOptions = clOptions;
177     }
178     
179     /**
180      * Sets the list of options read from Environment for this Command
181      * @param envOptions List of options for this command
182      */

183     public void setEnvOptions(HashMap JavaDoc envOptions)
184     {
185         this.envOptions = envOptions;
186     }
187     
188     /**
189      * Finds the option with the give name
190      * @return Option return option if found else return null
191      */

192     public String JavaDoc getOption(String JavaDoc optionName)
193     {
194         if (!optionNameExist(optionName)) return null;
195         return (clOptions.get(optionName) != null)?
196                                 (String JavaDoc) clOptions.get(optionName) :
197                                 (String JavaDoc) envOptions.get(optionName);
198     }
199     
200     
201     /**
202      * Finds the option with the give name
203      * @return Option return option if found else return null
204      */

205     public String JavaDoc getCLOption(String JavaDoc optionName)
206     {
207         return ((String JavaDoc) clOptions.get(optionName));
208     }
209     
210     
211     /**
212      * Finds the option with the give name
213      * @return Option return option if found else return null
214      */

215     public String JavaDoc getENVOption(String JavaDoc optionName)
216     {
217         return ((String JavaDoc) envOptions.get(optionName));
218     }
219     
220     
221     /**
222      * Sets the option value for the give name
223      * @param optionName name of the option
224      * @param optionValue value of the option
225      */

226     public void setOption(String JavaDoc optionName, String JavaDoc optionValue)
227     {
228         clOptions.put(optionName, optionValue);
229     }
230
231
232     /**
233      * Sets the boolean options list.
234      * booleanOptionsList contains the list of boolean options.
235      * this variable is currently used in toString() to determine
236      * if the boolean options are to be printed with "=" between
237      * the options name and value.
238      * @param list of boolean options
239      */

240     public void setBooleanOptions(List JavaDoc booleanOptions)
241     {
242         booleanOptionsList = booleanOptions;
243     }
244     
245     
246     /**
247      * Finds the option with the give name
248      * @return boolean return boolean type of the option value
249      */

250     protected boolean getBooleanOption(String JavaDoc optionName)
251     {
252         return new Boolean JavaDoc(getOption(optionName)).booleanValue();
253     }
254     
255     
256     /**
257      * Finds the option with the give name
258      * @return Option return option if found else return -1
259      */

260     protected int getIntegerOption(String JavaDoc optionName)
261     {
262         //assert
263
assert(!optionNameExist(optionName));
264         return (new Integer JavaDoc(getOption(optionName)).intValue());
265     }
266
267
268     /**
269      * returns true if the option name exist in the options list
270      * @true if option name exist
271      */

272     private boolean optionNameExist(String JavaDoc optionName)
273     {
274         return (clOptions.containsKey(optionName) || envOptions.containsKey(optionName));
275     }
276     
277     
278     /**
279      * Gets the Usage text for this command
280      * @return String returns usage text for this command
281      */

282     public String JavaDoc getUsageText()
283     {
284         return usageStr;
285     }
286     
287     /**
288      * Sets the Usage text for this command
289      * @param String usage-text for this command
290      */

291     public void setUsageText(String JavaDoc usageText)
292     {
293         this.usageStr = usageText;
294     }
295
296     /**
297      * Searches for the property with the specified key in this
298      * properties list
299      * return the property
300      */

301     public Object JavaDoc getProperty(String JavaDoc key)
302     {
303         return properties.get(key);
304     }
305
306
307     /**
308      * Sets the properties of the command
309      * @param properties, the list of properties for this command
310      */

311     public void setProperty(String JavaDoc key, Object JavaDoc value)
312     {
313         properties.put(key, value);
314     }
315
316
317     /**
318      * returns the properties list
319      * return the property
320      */

321     protected Hashtable JavaDoc getProperties(String JavaDoc key)
322     {
323         return properties;
324     }
325
326
327     /**
328      * Sets the properties of the command
329      * @param properties, the list of properties for this command
330      */

331     protected void setProperties(Hashtable JavaDoc properties)
332     {
333         this.properties = properties;
334     }
335
336
337     /**
338      * returns the localized string from the properties file as defined in
339      * the CommandProperties element of CLIDescriptor.xml file
340      * Calls the LocalStringsManagerFactory.getCommandLocalStringsManager()
341      * method, returns "Key not found" if it cannot find the key
342      * @param key, the string to be localized
343      */

344     protected String JavaDoc getLocalizedString(String JavaDoc key)
345     {
346         LocalStringsManager lsm = null;
347         try
348         {
349             lsm = LocalStringsManagerFactory.getCommandLocalStringsManager();
350         }
351         catch (CommandValidationException cve)
352         {
353             return LocalStringsManager.DEFAULT_STRING_VALUE;
354         }
355         return lsm.getString(key);
356     }
357
358
359     /**
360      * returns the localized string from the properties file as defined in
361      * the CommandProperties element of CLIDescriptor.xml file
362      * Calls the LocalStringsManagerFactory.getCommandLocalStringsManager()
363      * method, returns "Key not found" if it cannot find the key
364      * @param key, the string to be localized
365      * @param toInsert, the strings to be inserted in the placeholders
366      */

367     protected String JavaDoc getLocalizedString(String JavaDoc key, Object JavaDoc[] toInsert)
368     {
369         LocalStringsManager lsm = null;
370         try
371         {
372             lsm = LocalStringsManagerFactory.getCommandLocalStringsManager();
373             return lsm.getString(key, toInsert);
374         }
375         catch (CommandValidationException cve)
376         {
377             return LocalStringsManager.DEFAULT_STRING_VALUE;
378         }
379     }
380
381
382     /**
383      * Overrides the Object's toString() method
384      * @return String The string representation of Command
385      */

386     public String JavaDoc toString()
387     {
388         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
389
390         strbuf.append(getName());
391
392         Iterator JavaDoc optionNames = clOptions.keySet().iterator();
393         while (optionNames.hasNext())
394         {
395             final String JavaDoc optionKey = (String JavaDoc) optionNames.next();
396             strbuf.append(" --" + optionKey );
397             if (booleanOptionsList.contains(optionKey))
398                 strbuf.append("=");
399             else
400                 strbuf.append(" ");
401             strbuf.append((String JavaDoc) clOptions.get(optionKey));
402         }
403         for (int ii=0; ii<operands.size(); ii++)
404         {
405             strbuf.append(" "+ operands.get(ii).toString());
406         }
407         return strbuf.toString();
408     }
409
410
411     /**
412      * this method replaces pattern with option or operand values
413      * @param replaceValue - value to replace
414      * @param regexp - regular expression pattern
415      * @return replaced string or null if could not replace string
416      */

417     public String JavaDoc replacePattern(String JavaDoc replaceValue)
418         throws CommandException
419     {
420         if (replaceValue == null) return null;
421         final Pattern JavaDoc patt = Pattern.compile(PATTERN_MATCHING);
422         final Matcher JavaDoc match = patt.matcher(replaceValue);
423         String JavaDoc outstr = replaceValue;
424         
425         try
426         {
427             if (match.find())
428             {
429                 StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
430                 do
431                 {
432                     String JavaDoc value = findPatternStringValue(match.group(1),
433                                                           match.group(2));
434                         //value = escapeTheEscape(value);
435
if (value == null)
436                         return value;
437                     value = prepareStringForAppend(value);
438                     match.appendReplacement(strbuf, value);
439                     CLILogger.getInstance().printDebugMessage("strbuf = " + strbuf);
440                 } while (match.find());
441                 match.appendTail(strbuf);
442                 outstr = strbuf.toString();
443             }
444         }
445         catch (java.lang.IllegalArgumentException JavaDoc iae)
446         {
447             try
448             {
449                 final LocalStringsManager lsm =
450                 LocalStringsManagerFactory.getFrameworkLocalStringsManager();
451                 throw new CommandException(lsm.getString("RequireEscapeChar"), iae);
452             }
453             catch (CommandValidationException cve)
454             {
455                 throw new CommandException(cve);
456             }
457         }
458         catch (Exception JavaDoc e)
459         {
460             throw new CommandException(e);
461         }
462         return (outstr.length()<1)?null:outstr;
463     }
464
465
466     /**
467      * this method finds the pattern for option and operand
468      * option pattern starts with "$" while operand pattern starts with "#"
469      * once key is determined, the option or operand value is returned
470      * @param pattern
471      * @param key to get option or operand values
472      * @return option/operand value if could not find value, then empty
473      * string is returned
474      */

475     private String JavaDoc findPatternStringValue(String JavaDoc pattern, String JavaDoc key)
476         throws CommandException
477     {
478         String JavaDoc value = null;
479         try
480         {
481             if (pattern.equals(String.valueOf(OPERAND_START_CHAR)))
482             {
483                 if (operands.size() > 0)
484                     value = (String JavaDoc)getOperands().get(Integer.parseInt(key)-1);
485             }
486             else if (pattern.equals(String.valueOf(VARIABLE_START_CHAR)))
487                 value = getOption(key);
488         }
489         catch(Exception JavaDoc e)
490         {
491             throw new CommandException(e);
492         }
493         // (bug 6363010), temporary fix, return null and make sure this isn't
494
// propagated into the attributeList to the backend
495
//return (value==null)?"":value;
496
return value;
497     }
498
499
500     /**
501      * this method is a hack
502      * to add escape character to each esacpe chars encounters except
503      * the escape character is follow by a '$'.
504      * match.appendReplacement will throw an IllegalArgumentException
505      * if literal $ does not preceed by an escape char.
506      * the purpose for doing this is for the match.appendReplacement
507      * which drops the escape character.
508      */

509     private String JavaDoc prepareStringForAppend(String JavaDoc str)
510     {
511         final String JavaDoc strTmp = escapeTheEscape(str);
512         return addEscapeToLiteral(strTmp);
513     }
514
515
516     /**
517      * This method adds escape character to each escape chars encounters
518      * the purpose for doing this is is that match.appendReplacement
519      * drops the escape character.
520      * @param strToEscape - to the string to check for escape characters
521      * @returns the string with the esacpe characters escaped
522      */

523     private String JavaDoc escapeTheEscape(String JavaDoc strToEscape)
524     {
525         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
526         int previousIndex =0;
527         int index =strToEscape.indexOf("\\");
528         while (index > -1)
529         {
530             if (index<strToEscape.length()-1 && strToEscape.charAt(index+1) == '$')
531                 strbuf.append(strToEscape.substring(previousIndex, index));
532             else
533                 strbuf.append(strToEscape.substring(previousIndex, index)+"\\\\");
534             previousIndex = index+1;
535             index = strToEscape.indexOf("\\", index+1);
536         }
537         strbuf.append(strToEscape.substring(previousIndex));
538         return strbuf.toString();
539     }
540
541
542     /**
543      * This method adds escape character preceding the '$' character.
544      * The reason for doing this is because match.appendReplacement
545      * will throw an IllegalArgumentException if the literal '$'
546      * does not precede by an escape character.
547      * The java api class Matcher, uses the regular expression
548      * '$<number>' as a group reference. So if it encounters '$<non-numeric>
549      * it'll throw an IllegalArgumentException. In order to by pass this
550      * exception, the literal '$' must precede with an escape character.
551      * @param strToEscape - to the string to check for '$'
552      * @returns the string with the esacpe character added to '$'
553      */

554     private String JavaDoc addEscapeToLiteral(String JavaDoc strToAdd)
555     {
556         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
557         int previousIndex =0;
558         int index = strToAdd.indexOf('$');
559         while (index > -1)
560         {
561             strbuf.append(strToAdd.substring(previousIndex, index)+"\\$");
562             previousIndex = index+1;
563             index = strToAdd.indexOf('$', index+1);
564         }
565         strbuf.append(strToAdd.substring(previousIndex));
566         return strbuf.toString();
567
568     }
569
570
571     /**
572      * returns the index of the delimeter string in the search string.
573      * @param searchStr the string to be searched
574      * @param delimeterStr the delimeter string to be searched in the searchStr
575      * @param fromIndex the delimeter to be searched at the specified location
576      * @return delimeterIndex starting index of the delimeter in search string
577      */

578     protected int getDelimeterIndex(String JavaDoc searchStr, String JavaDoc delimeter,
579                                     int fromIndex)
580     {
581         return searchStr.indexOf(delimeter, fromIndex);
582     }
583 }
584
Popular Tags