KickJava   Java API By Example, From Geeks To Geeks.

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


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  * CLIDescriptorsReader.java
26  *
27  * Created on June 9, 2003, 12:19 PM
28  */

29 package com.sun.enterprise.cli.framework;
30
31 //imports
32
import java.net.URL JavaDoc;
33 import java.net.URLEncoder JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.Vector JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.util.StringTokenizer JavaDoc;
40 import java.io.IOException JavaDoc;
41 import java.io.Serializable JavaDoc;
42 import java.io.ObjectOutputStream JavaDoc;
43 import java.io.FileOutputStream JavaDoc;
44 import java.io.ObjectInputStream JavaDoc;
45 import java.io.InputStream JavaDoc;
46 import java.io.FileInputStream JavaDoc;
47 import java.io.File JavaDoc;
48 import java.io.FileNotFoundException JavaDoc;
49 import java.io.FilenameFilter JavaDoc;
50 import java.io.UnsupportedEncodingException JavaDoc;
51
52 //XML imports
53
import javax.xml.parsers.DocumentBuilder JavaDoc;
54 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
55 import javax.xml.parsers.ParserConfigurationException JavaDoc;
56
57 import org.xml.sax.SAXException JavaDoc;
58 import org.xml.sax.EntityResolver JavaDoc;
59 import org.xml.sax.InputSource JavaDoc;
60 import com.sun.org.apache.xerces.internal.parsers.DOMParser;
61
62 import org.w3c.dom.Document JavaDoc;
63 import org.w3c.dom.Node JavaDoc;
64 import org.w3c.dom.NamedNodeMap JavaDoc;
65
66 /**
67  *
68  * @author pa100654
69  */

70 public class CLIDescriptorsReader
71 {
72     
73     public static int DONT_SERIALIZE = 0;
74     public static int SERIALIZE_COMMANDS_TO_FILES = 1;
75     public static int SERIALIZE_COMMANDS_TO_FILE = 2;
76     public static String JavaDoc SERIALIZED_DESCRIPTOR_FILE = ".CLIDescriptors";
77     public static String JavaDoc SERIALIZED_COMMANDS_DEFAULT_DIR = "cli";
78     public static String JavaDoc ENVIRONMENT_PREFIX = "environment-prefix";
79     public static String JavaDoc ENVIRONMENT_FILENAME = "environment-filename";
80     //static instance of itself
81
private static CLIDescriptorsReader cliDescriptorsReader;
82     
83     // The directory where the serialized file has to be saved
84
private String JavaDoc serializeDir = SERIALIZED_COMMANDS_DEFAULT_DIR;
85
86     // Attribute which says whether the component descriptors and commands
87
// descriptors have to read from a file or loaded to a file.
88
private int serializeDescriptors = DONT_SERIALIZE;
89     
90     // List of valid commands from all the components
91
private ValidCommandsList commandsList = null;
92     
93     // List of valid options from all the components
94
private HashMap JavaDoc validOptions = null;
95
96     // List of options to be replaced by all the commands in the descriptor files
97
private HashMap JavaDoc replaceOptions = null;
98
99     // List of descriptors (URLs)
100
private Vector JavaDoc descriptors = null;
101     
102     // Vector of Properties from all the descriptor files
103
private Vector JavaDoc properties = null;
104     
105     // Default command to use
106
private String JavaDoc defaultCommand = null;
107
108     // Help class name for the help command
109
private String JavaDoc helpClass = null;
110     
111
112
113     private static String JavaDoc DESCRIPTOR_FILE_NAME = "CLIDescriptor.xml";
114     /**
115         Construct CLIDescriptorsReader object
116     */

117     protected CLIDescriptorsReader()
118     {
119         initialize();
120     }
121     
122     
123     /**
124         Construct CLIDescriptorsReader object with the given arguments.
125         @param descriptor, the URL for the CLI Descriptor file
126     */

127     protected CLIDescriptorsReader(URL JavaDoc descriptor)
128     {
129         setDescriptor(descriptor);
130         initialize();
131     }
132     
133     
134     /**
135         Construct CLIDescriptorsReader object with the given arguments.
136     @param descriptors, the URL's for the CLI Descriptor file
137     */

138     protected CLIDescriptorsReader(Vector JavaDoc descriptors)
139     {
140         this.descriptors = descriptors;
141         initialize();
142     }
143     
144     
145     /**
146      *Initialize the CLIDescriptorsReader object and read the components
147      */

148     private void initialize()
149     {
150         commandsList = new ValidCommandsList();
151         validOptions = new HashMap JavaDoc();
152         replaceOptions = new HashMap JavaDoc();
153         properties = new Vector JavaDoc();
154     }
155
156
157     /**
158      * returns the instance of the CLIDescriptorsReader
159      */

160     public static CLIDescriptorsReader getInstance()
161     {
162         if (cliDescriptorsReader == null)
163         {
164             cliDescriptorsReader= new CLIDescriptorsReader();
165         }
166         return cliDescriptorsReader;
167     }
168
169     
170     /**
171       Returns the command object. if the commandName is null then the default
172       command object is returned.
173       @param commandName the command name
174       @return ValidCommand the valid command object
175      */

176     public ValidCommand getCommand(String JavaDoc commandName)
177                            throws CommandValidationException
178     {
179         ValidCommand command = null;
180         if ((commandsList == null) || (commandsList.size() == 0))
181         {
182             command = getCommandFromFileOrDescriptor(commandName);
183         }
184         else
185         {
186             command = commandsList.getValidCommand(commandName);
187         }
188         return command;
189     }
190
191
192     /**
193      * returns the default command string
194      * @return defaultCommand
195      */

196     public String JavaDoc getDefaultCommand()
197     {
198         return defaultCommand;
199     }
200
201
202     /**
203      * returns the help class string
204      * @return helpClass
205      */

206     public String JavaDoc getHelpClass()
207     {
208         return helpClass;
209     }
210
211     /**
212       Returns the commands list
213       if not already read, the commands are read either from the serialized
214       command file(s) or the command descriptor(s)
215       @return ValidCommandsList the list of valid commands
216      */

217     public ValidCommandsList getCommandsList() throws CommandValidationException
218     {
219         if ((commandsList == null) || (commandsList.size() == 0))
220         {
221             loadAllCommandsFromFilesOrDescriptors();
222         }
223         return commandsList;
224     }
225
226     
227     /**
228       Returns the properties list of all the commands module's
229       @return Iterator the list of Properties
230      */

231     public Iterator JavaDoc getProperties() throws CommandValidationException
232     {
233         return properties.iterator();
234     }
235
236     
237     /**
238       Returns the command object
239       @param commandName the command name
240       @return ValidCommand the valid command object
241      */

242     private ValidCommand getCommandFromFileOrDescriptor(String JavaDoc commandName)
243                            throws CommandValidationException
244     {
245         ValidCommand command = null;
246         
247     /************************************************************************/
248     /** how should we handle defaultcommand if using serialized descriptor **/
249     /************************************************************************/
250         if (serializeDescriptors == SERIALIZE_COMMANDS_TO_FILES)
251         {
252             command = getSerializedCommand(commandName);
253             if (command != null)
254             {
255                 return command;
256             }
257         }
258
259             //preserve serializedDescriptor setting so commands do not get serialized
260
//if command could not be found
261
int saveSerializedDescriptor = getSerializeDescriptorsProperty();
262         setSerializeDescriptorsProperty(DONT_SERIALIZE);
263         loadAllCommandsFromFilesOrDescriptors();
264             //put back setting for serizliedDescriptor
265
setSerializeDescriptorsProperty(saveSerializedDescriptor);
266         if (commandName != null)
267             return commandsList.getValidCommand(commandName);
268         else if (defaultCommand != null)
269             return commandsList.getValidCommand(defaultCommand);
270         else
271             throw new CommandValidationException(
272                 LocalStringsManagerFactory.getFrameworkLocalStringsManager().
273                 getString("CommandNotSpecified", null));
274
275     }
276
277     
278     /**
279      * Loads the specified serialized command from the file in the
280         SERIALIZED_COMMANDS_DIR
281      * @param commandFile file name of the command to be read
282      * @return returns the ValidCommand object
283      */

284     private ValidCommand getSerializedCommand(String JavaDoc commandName)
285                     throws CommandValidationException
286     {
287
288         ValidCommand command = null;
289         String JavaDoc encodedCommandName = null;
290         try{
291             encodedCommandName = URLEncoder.encode(commandName,"UTF-8");
292             }catch(UnsupportedEncodingException JavaDoc ue){
293                 encodedCommandName = commandName;
294             }
295         final InputStream JavaDoc in = CLIDescriptorsReader.class.getClassLoader().getResourceAsStream(serializeDir + "/." + encodedCommandName);
296         
297         if (in!=null)
298         {
299             command = getSerializedCommand(in);
300         }
301         else {
302             return null;
303         }
304          
305         /*
306         File fileName = new File(serializeDir + "/." + commandName);
307         if (fileName.exists())
308         {
309             command = getSerializedCommand(fileName);
310         }
311         */

312         
313         return command;
314     }
315  
316     
317     /**
318      * Loads the specified serialized command from the file in the
319         SERIALIZED_COMMANDS_DIR
320      * @param commandFile file name of the command to be read
321      */

322     private ValidCommand getSerializedCommand(InputStream JavaDoc commandFile)
323                             throws CommandValidationException
324     {
325         try
326         {
327             ValidCommand command = null;
328             ObjectInputStream JavaDoc in = new ObjectInputStream JavaDoc(commandFile);
329             
330                 //ObjectInputStream in = new ObjectInputStream(
331
// new FileInputStream(commandFile));
332

333             /** read CommandProperties to serialized file **/
334             defaultCommand = (String JavaDoc) in.readObject();
335             helpClass = (String JavaDoc) in.readObject();
336             properties = (Vector JavaDoc) in.readObject();
337
338             command = (ValidCommand) in.readObject();
339             CLILogger.getInstance().printDebugMessage("++++++++++++++++++++++++++++ Command loaded from file and it is " + command);
340             return command;
341         }
342         catch (Exception JavaDoc e)
343         {
344         throw new CommandValidationException(e);
345         }
346     }
347
348     
349     /**
350      *Initialize the commandsList based on the serializeDescriptors property
351      */

352     private void loadAllCommandsFromFilesOrDescriptors()
353                     throws CommandValidationException
354     {
355         if (serializeDescriptors == DONT_SERIALIZE)
356         {
357             readDescriptors();
358         }
359         else if (serializeDescriptors == SERIALIZE_COMMANDS_TO_FILES)
360         {
361             loadCommandsFromMultipleFiles();
362         }
363         else if (serializeDescriptors == SERIALIZE_COMMANDS_TO_FILE)
364         {
365             loadCommandsFromSingleFile();
366         }
367     }
368
369
370     /**
371      *
372      */

373     private void loadCommandsFromMultipleFiles()
374     throws CommandValidationException
375     {
376         File JavaDoc commandsDir = new File JavaDoc(serializeDir);
377
378         if ((commandsDir != null) && (commandsDir.exists()) &&
379               (getSerializedCommandsFileList(commandsDir).length > 0))
380         {
381             getDescriptors();
382             if (descriptors == null)
383             {
384         LocalStringsManager lsm =
385             LocalStringsManagerFactory.getFrameworkLocalStringsManager();
386         throw new CommandValidationException(lsm.getString("NoDescriptorsDefined"));
387             }
388             boolean isSerializedCommandsLatest = true;
389             for (int i = 0; (i < descriptors.size()) &&
390                             isSerializedCommandsLatest; i++)
391             {
392                 URL JavaDoc descriptorURL = (URL JavaDoc) descriptors.get(i);
393                 File JavaDoc descriptorFile = getDescriptorFile(descriptorURL);
394                 if ((descriptorFile != null) && (descriptorFile.exists()))
395                 {
396                     if (descriptorFile.lastModified() > commandsDir.lastModified())
397                     {
398                         isSerializedCommandsLatest = false;
399                         break;
400                     }
401                 }
402                 else
403                 {
404                   // should we throw a CommandValidationException?
405
}
406             }
407             if (isSerializedCommandsLatest)
408             {
409                 if (!loadSerializedCommands())
410                 {
411                     readDescriptors();
412                 }
413             }
414             else
415             {
416                 readDescriptors();
417             }
418         }
419         else
420         {
421             readDescriptors();
422         }
423     }
424    
425     
426     /**
427      *
428      */

429     private void loadCommandsFromSingleFile()
430                     throws CommandValidationException
431     {
432         File JavaDoc serializedDescriptorFile = getSerializedDescriptorFile();
433         if (serializedDescriptorFile.exists())
434             CLILogger.getInstance().printDebugMessage("Yes the file exists");
435         if (!((serializedDescriptorFile != null) &&
436               (serializedDescriptorFile.exists())))
437         {
438             readDescriptors();
439             return;
440         }
441
442         getDescriptors();
443         if (descriptors == null)
444         {
445         LocalStringsManager lsm =
446             LocalStringsManagerFactory.getFrameworkLocalStringsManager();
447         throw new CommandValidationException(lsm.getString("NoDescriptorsDefined"));
448         }
449         boolean isSerializedDescriptorLatest = true;
450         for (int i = 0; (i < descriptors.size()) &&
451                         isSerializedDescriptorLatest; i++)
452         {
453             URL JavaDoc descriptorURL = (URL JavaDoc) descriptors.get(i);
454             File JavaDoc descriptorFile = getDescriptorFile(descriptorURL);
455             if ((descriptorFile != null) && (descriptorFile.exists()))
456             {
457                 if (descriptorFile.lastModified() >
458                         serializedDescriptorFile.lastModified())
459                 {
460                     isSerializedDescriptorLatest = false;
461                     break;
462                 }
463             }
464             else
465             {
466               // should we throw a CommandValidationException?
467
}
468         }
469         if (isSerializedDescriptorLatest)
470         {
471             loadSerializedDescriptorFile();
472         }
473         else
474         {
475             readDescriptors();
476         }
477     }
478     
479     
480     /**
481         Parse and read the XML Descriptors file and populate it into
482         commandsList
483      */

484     private void readDescriptors() throws CommandValidationException
485     {
486         commandsList.removeAllCommands();
487         //DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
488
//factory.setValidating(true);
489
//factory.setNamespaceAware(true);
490
try
491         {
492             // setup schema processing
493
DOMParser parser = new DOMParser();
494             parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", true);
495             parser.setFeature( "http://xml.org/sax/features/validation", true );
496             parser.setFeature( "http://xml.org/sax/features/namespaces", true );
497             parser.setFeature( "http://apache.org/xml/features/validation/schema", true );
498             parser.setFeature ("http://apache.org/xml/features/dom/include-ignorable-whitespace", false);
499             parser.setEntityResolver(new CLIEntityResolver());
500
501             //factory.setValidating(true);
502
// CLILogger.getInstance().printDebugMessage("Validation against DTD is " + factory.isValidating());
503
//DocumentBuilder builder = factory.newDocumentBuilder();
504
if (descriptors == null)
505             {
506                 getDescriptors();
507                 if (descriptors == null)
508         {
509             LocalStringsManager lsm =
510             LocalStringsManagerFactory.getFrameworkLocalStringsManager();
511             throw new CommandValidationException(lsm.getString("NoDescriptorsDefined"));
512         }
513             }
514             for (int i = 0; i < descriptors.size(); i++)
515             {
516                 URL JavaDoc descriptorURL = (URL JavaDoc) descriptors.get(i);
517                 //InputSource is = new InputSource(descriptorURL.toString());
518
//Document document = builder.parse(is);
519
parser.parse(new InputSource JavaDoc(descriptorURL.toString()));
520                 Document JavaDoc document = parser.getDocument();
521                 generateOptionsAndCommands(document);
522             }
523                 //call this last after all descriptors have been read since we want to
524
//replace all the options with the options defined in ReplaceOptions
525
//element in the last XML in the list.
526
replaceOptionsInCommandsList(replaceOptions);
527             
528             if (serializeDescriptors == SERIALIZE_COMMANDS_TO_FILES)
529             {
530                 saveCommandsAsMultipleFiles();
531             }
532             else if (serializeDescriptors == SERIALIZE_COMMANDS_TO_FILE)
533             {
534                 saveCommandsAsSingleFile();
535             }
536
537         }
538         catch (SAXException JavaDoc sxe)
539         {
540            // Error generated during parsing)
541
Exception JavaDoc x = sxe;
542             if (sxe.getException() != null)
543                x = sxe.getException();
544         throw new CommandValidationException(x);
545         }
546         catch (IOException JavaDoc ioe)
547         {
548             // I/O error
549
throw new CommandValidationException(ioe);
550             //throw new CommandValidationException(ioe.getLocalizedMessage());
551
}
552     }
553    
554     
555     /**
556      *
557      */

558     private String JavaDoc[] getSerializedCommandsFileList(File JavaDoc commandsDir)
559     {
560         String JavaDoc[] commandFiles = commandsDir.list(new FilenameFilter JavaDoc() {
561             public boolean accept(File JavaDoc parentDir, String JavaDoc name) {
562                 return (name.startsWith("."));
563             }});
564         return commandFiles;
565     }
566     
567     /**
568      * Returns the File object of the single serialized file, containing all
569      * the commands
570      * @return File file object of the serialized file containing all commands
571      */

572     private File JavaDoc getSerializedDescriptorFile()
573     {
574         File JavaDoc file = null;
575         try
576         {
577             file = new File JavaDoc(serializeDir + "/" + SERIALIZED_DESCRIPTOR_FILE);
578         }
579         catch (NullPointerException JavaDoc npe)
580         {
581         }
582         
583         return file;
584     }
585     
586     
587     /**
588      * Returns the file object of the component
589      * @param descriptor the URL object of the component
590      * @return File file object of the descriptor
591      */

592     private File JavaDoc getDescriptorFile(URL JavaDoc descriptor)
593     {
594         File JavaDoc file = null;
595         try
596         {
597             file = new File JavaDoc(descriptor.getFile());
598             if (!file.exists())
599                 file = null;
600         }
601         catch (NullPointerException JavaDoc e)
602         {
603             
604         }
605         return file;
606     }
607     
608     
609     /**
610      * Loads the serialized commands from the files in the
611         SERIALIZED_COMMANDS_DIR
612      * @return true if loaded succesfully else false
613      */

614     private boolean loadSerializedCommands()
615                     throws CommandValidationException
616     {
617         File JavaDoc commandsDir = new File JavaDoc(serializeDir);
618
619         if (!((commandsDir != null) && (commandsDir.exists()) &&
620               (getSerializedCommandsFileList(commandsDir).length > 0)))
621         {
622             return false;
623         }
624
625         String JavaDoc[] commandFiles = getSerializedCommandsFileList(commandsDir);
626         
627         boolean loaded = true;
628         for (int i = 0; (i < commandFiles.length) && loaded; i++)
629         {
630             //File commandFile = new File(commandFiles[i]);
631
final InputStream JavaDoc in = CLIDescriptorsReader.class.getClassLoader().getResourceAsStream(serializeDir + "/." + commandFiles[i] );
632
633             try
634             {
635                 ValidCommand command = getSerializedCommand(in);
636                 //ValidCommand command = getSerializedCommand(commandFile);
637
if (command != null)
638                 {
639                     commandsList.addCommand(command);
640                 }
641                 else
642                 {
643                     loaded = false;
644                 }
645             }
646             catch (CommandValidationException e)
647             {
648                 loaded = false;
649                 break;
650             }
651         }
652         return loaded;
653     }
654     
655     
656     /**
657      * Loads the serialized commands from a single file which is
658         SERIALIZED_COMMANDS_FILE
659      */

660     private void loadSerializedDescriptorFile()
661     {
662         try
663         {
664             File JavaDoc fileName = getSerializedDescriptorFile();
665             // expecting the additional checking for validity of SERIALIZED_COMMANDS_FILE
666
// is already done prior to calling this method.
667
ObjectInputStream JavaDoc in = new ObjectInputStream JavaDoc(new FileInputStream JavaDoc(fileName));
668             
669             /** read CommandProperties to serialized file **/
670             defaultCommand = (String JavaDoc) in.readObject();
671             helpClass = (String JavaDoc) in.readObject();
672             properties = (Vector JavaDoc) in.readObject();
673
674             commandsList = (ValidCommandsList) in.readObject();
675             CLILogger.getInstance().printDebugMessage("++++++++++++++++++++++++++++ Commands loaded from file");
676         }
677         catch(FileNotFoundException JavaDoc fnfe)
678         {
679             
680         }
681         catch(IOException JavaDoc ioe)
682         {
683             
684         }
685         catch(ClassNotFoundException JavaDoc cnfe)
686         {
687             
688         }
689     }
690     
691     
692     /**
693         gets the descriptors
694      */

695     private Vector JavaDoc getDescriptors() throws CommandValidationException
696     {
697         if (descriptors != null)
698             return descriptors;
699         
700         try
701         {
702             String JavaDoc descriptor_file_name = System.getProperty("DESCRIPTOR_FILE");
703             if(descriptor_file_name == null)
704                 descriptor_file_name = DESCRIPTOR_FILE_NAME;
705             Enumeration JavaDoc urls = CLIDescriptorsReader.class.getClassLoader().getResources(
706                 descriptor_file_name);
707             if ((urls == null) || (!urls.hasMoreElements()))
708             {
709                 return descriptors;
710             }
711
712             while (urls.hasMoreElements())
713             {
714                 URL JavaDoc url = (URL JavaDoc) urls.nextElement();
715                 setDescriptor(url);
716             }
717         }
718         catch(IOException JavaDoc ioe)
719         {
720         LocalStringsManager lsm =
721         LocalStringsManagerFactory.getFrameworkLocalStringsManager();
722         CLILogger.getInstance().printMessage(lsm.getString("CouldNotLoadDescriptor"));
723         }
724         return descriptors;
725     }
726    
727     
728     /**
729         Sets the descriptor file
730     @param descriptor the descriptor file containing the command specifications
731      */

732     public void setDescriptor(URL JavaDoc descriptor)
733     {
734         if (descriptor != null)
735         {
736             if (descriptors == null)
737             {
738                 descriptors = new Vector JavaDoc();
739             }
740             descriptors.add(descriptor);
741             //reverse the order in the Vector so that the last CLIDescriptor.xml will be parsed first.
742
java.util.Collections.reverse(descriptors);
743         }
744     }
745
746     
747     /**
748         Sets the descriptor files (components)
749     @param descriptors the descriptor files containing the command specifications
750      */

751     public void setDescriptors(Vector JavaDoc descriptors)
752     {
753         this.descriptors = descriptors;
754     }
755
756     
757     /**
758         Get All the Valid, Required, Deprecated Options and the commands
759         from the descriptor file
760      */

761     private void generateOptionsAndCommands(Document JavaDoc document)
762     {
763         if (document != null)
764         {
765             for (Node JavaDoc nextKid = document.getDocumentElement().getFirstChild();
766                     nextKid != null; nextKid = nextKid.getNextSibling())
767             {
768                 String JavaDoc nodeName = nextKid.getNodeName();
769                 if (nodeName.equalsIgnoreCase("CommandProperties"))
770                 {
771                     Properties JavaDoc props = new Properties JavaDoc();
772                     for (Node JavaDoc grandKid = nextKid.getFirstChild();
773                        grandKid != null; grandKid = grandKid.getNextSibling())
774                     {
775                         String JavaDoc grandKidNodeName = grandKid.getNodeName();
776                         if (grandKidNodeName.equalsIgnoreCase("CommandProperty"))
777                         {
778                             NamedNodeMap JavaDoc nodeMap = grandKid.getAttributes();
779                             String JavaDoc nameAttr =
780                                     nodeMap.getNamedItem("name").getNodeValue();
781                             String JavaDoc valueAttr =
782                                     nodeMap.getNamedItem("value").getNodeValue();
783                             props.setProperty(nameAttr, valueAttr);
784                         }
785                     }
786             final NamedNodeMap JavaDoc commandPropertiesAttribute = nextKid.getAttributes();
787             if (commandPropertiesAttribute != null &&
788             commandPropertiesAttribute.getNamedItem("defaultcommand") != null )
789             defaultCommand = commandPropertiesAttribute.getNamedItem(
790                      "defaultcommand").getNodeValue();
791             if (commandPropertiesAttribute != null &&
792             commandPropertiesAttribute.getNamedItem("helpclass") != null )
793             helpClass = commandPropertiesAttribute.getNamedItem(
794                      "helpclass").getNodeValue();
795                                       
796                     properties.add(props);
797                 }
798                 else if (nodeName.equalsIgnoreCase("Options"))
799                 {
800                     for (Node JavaDoc grandKid = nextKid.getFirstChild();
801                        grandKid != null; grandKid = grandKid.getNextSibling())
802                     {
803                         String JavaDoc grandKidNodeName = grandKid.getNodeName();
804                         if (grandKidNodeName.equalsIgnoreCase("Option"))
805                         {
806                             ValidOption option = generateOption(document, grandKid);
807                             validOptions.put(option.getName(), option);
808                         }
809                         else if (grandKidNodeName.equalsIgnoreCase("ReplaceOption"))
810                         {
811                             ValidOption option = generateOption(document, grandKid);
812                             replaceOptions.put(option.getName(), option);
813                         }
814
815                     }
816                 }
817                 //Generates the Valid Commands List from the descriptor file by
818
// reading all the Valid Commands
819
else if (nodeName.equalsIgnoreCase("Commands"))
820                 {
821                     for (Node JavaDoc grandKid = nextKid.getFirstChild();
822                        grandKid != null; grandKid = grandKid.getNextSibling())
823                     {
824                         String JavaDoc grandKidNodeName = grandKid.getNodeName();
825                         if (grandKidNodeName.equalsIgnoreCase("Command"))
826                         {
827                             ValidCommand command = generateCommand(document, grandKid);
828                             commandsList.addCommand(command);
829                         }
830                     }
831                 }
832             }
833         }
834     }
835    
836     
837     /**
838      Generate a Valid Option by populating it with its name, value-required,
839      shortoption, default, help-text fields
840      @param document the Document object
841      @param grandKid the node in the xml document where the option need to be searched
842      @return returns a ValidOption
843      */

844     private ValidOption generateOption(Document JavaDoc document, Node JavaDoc grandKid)
845     {
846         ValidOption option = new ValidOption();
847         NamedNodeMap JavaDoc nodeMap = grandKid.getAttributes();
848         String JavaDoc nameAttr = nodeMap.getNamedItem("name").getNodeValue();
849         String JavaDoc typeAttr = nodeMap.getNamedItem("type").getNodeValue();
850         boolean valueReqdAttr = Boolean.valueOf(nodeMap.getNamedItem("value-required").getNodeValue()).booleanValue();
851         Node JavaDoc defaultAttrNode = nodeMap.getNamedItem("default");
852         String JavaDoc defaultAttr = null;
853         if (defaultAttrNode != null)
854             defaultAttr = defaultAttrNode.getNodeValue();
855         option.setName(nameAttr);
856         option.setType(typeAttr);
857         option.setRequired(valueReqdAttr?ValidOption.REQUIRED:ValidOption.OPTIONAL);
858         option.setDefaultValue(defaultAttr);
859         for (Node JavaDoc nextGrandKid = grandKid.getFirstChild(); nextGrandKid != null;
860                 nextGrandKid = nextGrandKid.getNextSibling())
861         {
862             String JavaDoc grandKidName = nextGrandKid.getNodeName();
863             if (grandKidName.equalsIgnoreCase("shortoption"))
864             {
865                 String JavaDoc shortOption = nextGrandKid.getFirstChild().getNodeValue();
866                 shortOption = shortOption.trim();
867                 if (shortOption != null)
868                 {
869                     option.setShortName(shortOption);
870                 }
871             }
872         }
873         return option;
874     }
875     
876     
877     /**
878      Generate a Valid Command by populating it with its name, numberofoperands,
879      classname, validoptions, requiredoptions, usage-text and help-text fields
880      @param document the Document object
881      @param grandKid, the node in the xml document tree where the command need to be searched
882      @return returns a ValidCommand
883      */

884     private ValidCommand generateCommand(Document JavaDoc document, Node JavaDoc grandKid)
885     {
886         ValidCommand command = new ValidCommand();
887
888         NamedNodeMap JavaDoc nodeMap = grandKid.getAttributes();
889         String JavaDoc nameAttr = nodeMap.getNamedItem("name").getNodeValue();
890         String JavaDoc classNameAttr = nodeMap.getNamedItem("classname").getNodeValue();
891         String JavaDoc numberOfOperandsAttr = nodeMap.getNamedItem("numberofoperands").getNodeValue();
892
893         String JavaDoc defaultOperandAttr = null;
894         if (nodeMap.getNamedItem("defaultoperand") != null)
895             defaultOperandAttr = nodeMap.getNamedItem("defaultoperand").getNodeValue();
896
897         Node JavaDoc usageTextNode = nodeMap.getNamedItem("usage-text");
898         String JavaDoc usageTextAttr = null;
899         if (usageTextNode != null)
900             usageTextAttr = usageTextNode.getNodeValue();
901         command.setName(nameAttr);
902         command.setNumberOfOperands(numberOfOperandsAttr);
903         command.setDefaultOperand(defaultOperandAttr);
904         command.setClassName(classNameAttr);
905         command.setUsageText(usageTextAttr);
906
907         for (Node JavaDoc nextGrandKid = grandKid.getFirstChild(); nextGrandKid != null;
908                 nextGrandKid = nextGrandKid.getNextSibling())
909         {
910             String JavaDoc grandKidName = nextGrandKid.getNodeName();
911             if (grandKidName.equalsIgnoreCase("ValidOption"))
912             {
913                 final NamedNodeMap JavaDoc validOptionNodeMap =
914                                 nextGrandKid.getAttributes();
915                 final String JavaDoc validOption =
916                         validOptionNodeMap.getNamedItem("name").getNodeValue();
917                 String JavaDoc deprecatedOption = null;
918                 if (validOptionNodeMap.getNamedItem("deprecatedoption") != null)
919                 {
920                     deprecatedOption = validOptionNodeMap.getNamedItem("deprecatedoption").getNodeValue();
921                 }
922                 String JavaDoc defaultValue = null;
923                 if (validOptionNodeMap.getNamedItem("defaultvalue") != null)
924                 {
925                     defaultValue = validOptionNodeMap.getNamedItem("defaultvalue").getNodeValue();
926                 }
927
928                 final ValidOption option = findOption(validOption);
929                 if (option == null)
930                 {
931                     CLILogger.getInstance().printDebugMessage("Valid option (" +
932                                   validOption +
933                                   ")is not found in xml : " +
934                                   command.getName());
935                     return command;
936                 }
937                 ValidOption newOption = new ValidOption(option);
938                 if (deprecatedOption != null)
939                     newOption.setDeprecatedOption(deprecatedOption);
940                 if (defaultValue != null)
941                     newOption.setDefaultValue(defaultValue);
942                 
943                 command.addValidOption(newOption);
944             }
945             else if (grandKidName.equalsIgnoreCase("RequiredOption"))
946             {
947                 final NamedNodeMap JavaDoc reqdOptionNodeMap =
948                                 nextGrandKid.getAttributes();
949                 final String JavaDoc reqdOption =
950                         reqdOptionNodeMap.getNamedItem("name").getNodeValue();
951                 String JavaDoc deprecatedOption = null;
952                 if (reqdOptionNodeMap.getNamedItem("deprecatedoption") != null)
953                 {
954                     deprecatedOption =
955                         reqdOptionNodeMap.getNamedItem("deprecatedoption").getNodeValue();
956                 }
957                 final ValidOption option = findOption(reqdOption);
958                 if (option == null)
959                 {
960                     CLILogger.getInstance().printDebugMessage("Required option (" +
961                                   reqdOption +
962                                   ")is not found in xml : " +
963                                   command.getName());
964                     return command;
965                 }
966                 if (deprecatedOption != null)
967                     option.setDeprecatedOption(deprecatedOption);
968                 command.addRequiredOption(new ValidOption(option));
969             }
970             else if (grandKidName.equalsIgnoreCase("DeprecatedOption"))
971             {
972                 final String JavaDoc deprecatedOption = nextGrandKid.getFirstChild().getNodeValue();
973                 final ValidOption option = findOption(deprecatedOption);
974                 if (option == null)
975                 {
976                     CLILogger.getInstance().printDebugMessage("Deprecated option (" +
977                                   deprecatedOption +
978                                   ")is not found in xml : " +
979                                   command.getName());
980                     return command;
981                 }
982                 command.addDeprecatedOption(option);
983             }
984             else if (grandKidName.equalsIgnoreCase("properties"))
985             {
986                 for (Node JavaDoc nextGreatGrandKid = nextGrandKid.getFirstChild();
987                         nextGreatGrandKid != null;
988                         nextGreatGrandKid = nextGreatGrandKid.getNextSibling())
989                 {
990                     String JavaDoc greatGrandKidName = nextGreatGrandKid.getNodeName();
991                     if (greatGrandKidName.equalsIgnoreCase("property"))
992                     {
993                         nodeMap = nextGreatGrandKid.getAttributes();
994                         String JavaDoc propertyNameAttr =
995                                     nodeMap.getNamedItem("name").getNodeValue();
996
997                         Vector JavaDoc values = new Vector JavaDoc();
998                         for (Node JavaDoc nextGreatGreatGrandKid = nextGreatGrandKid.getFirstChild();
999                                 nextGreatGreatGrandKid != null;
1000                                nextGreatGreatGrandKid = nextGreatGreatGrandKid.getNextSibling())
1001                        {
1002                            String JavaDoc greatGreatGrandKidName = nextGreatGreatGrandKid.getNodeName();
1003                            if (greatGreatGrandKidName.equalsIgnoreCase("value"))
1004                            {
1005                String JavaDoc value = null;
1006
1007                if (nextGreatGreatGrandKid.getFirstChild() != null)
1008                    value = nextGreatGreatGrandKid.getFirstChild().getNodeValue();
1009                                values.add(value);
1010                            }
1011                        
1012                        }
1013                        command.setProperty(propertyNameAttr, values);
1014                    }
1015                }
1016            }
1017        }
1018        
1019        return command;
1020    }
1021    
1022    
1023    /**
1024     find the option in the options list given the option name
1025     @param optionStr the name of the option
1026     @return ValidOption, the ValidOption if found else return null
1027     */

1028    private ValidOption findOption(String JavaDoc optionStr)
1029    {
1030        ValidOption option = null;
1031        option = (ValidOption) validOptions.get(optionStr);
1032        return option;
1033    }
1034    
1035    
1036    /**
1037     serialize the ValidCommandsList object to file named
1038     SERIALIZED_COMPONENTS_FILE
1039     */

1040    private void saveCommandsAsMultipleFiles() throws CommandValidationException
1041    {
1042        Iterator JavaDoc commands = commandsList.getCommands();
1043        while (commands.hasNext())
1044        {
1045            try
1046            {
1047                ValidCommand command = (ValidCommand) commands.next();
1048                File JavaDoc file = new File JavaDoc(serializeDir);
1049                if (!file.exists())
1050                {
1051                    file.mkdir();
1052                }
1053                String JavaDoc encodedCommandName = null;
1054                try{
1055                    encodedCommandName = URLEncoder.encode(command.getName(),"UTF-8");
1056                }catch(UnsupportedEncodingException JavaDoc ue){
1057                    encodedCommandName = command.getName();
1058                }
1059                ObjectOutputStream JavaDoc os = new ObjectOutputStream JavaDoc(
1060                                           new FileOutputStream JavaDoc(serializeDir +
1061                                                    "/."+ encodedCommandName));
1062                /** write CommandProperties to serialized file **/
1063                os.writeObject(defaultCommand);
1064                os.writeObject(helpClass);
1065                os.writeObject(properties);
1066                    
1067                os.writeObject(command);
1068            }
1069            catch(Exception JavaDoc e)
1070            {
1071        //do we want to escalate this exception or just print a message.
1072
LocalStringsManager lsm =
1073            LocalStringsManagerFactory.getFrameworkLocalStringsManager();
1074        CLILogger.getInstance().printWarning(lsm.getString(
1075                             "CouldNotWriteCommandToFile",
1076                             new Object JavaDoc[] {e.getMessage()} ));
1077            }
1078        }
1079    }
1080    
1081    /**
1082     serialize the ValidCommand objects to file with cli/.{command_name}
1083     */

1084    private void saveCommandsAsSingleFile() throws CommandValidationException
1085    {
1086        try
1087        {
1088            ObjectOutputStream JavaDoc os = new ObjectOutputStream JavaDoc(
1089                                       new FileOutputStream JavaDoc(serializeDir +
1090                                            "/"+ SERIALIZED_DESCRIPTOR_FILE));
1091            os.writeObject(defaultCommand);
1092            os.writeObject(helpClass);
1093            os.writeObject(properties);
1094                    
1095            os.writeObject(commandsList);
1096        }
1097        catch(Exception JavaDoc e)
1098        {
1099        //do we want to escalate this exception or just print a message.
1100
LocalStringsManager lsm =
1101        LocalStringsManagerFactory.getFrameworkLocalStringsManager();
1102        CLILogger.getInstance().printWarning(lsm.getString(
1103                         "CouldNotWriteComponentToFile",
1104                         new Object JavaDoc[] {e.getMessage()} ));
1105
1106        }
1107    }
1108    
1109    
1110    /**
1111     * returns the serializeDescriptors property
1112     */

1113    private int getSerializeDescriptorsProperty()
1114    {
1115        return serializeDescriptors;
1116    }
1117    
1118    /**
1119     * set the serializeDescriptors property.
1120     * DONT_SERIALIZE CLIDescriptor's will not be loaded from the file nor will
1121                        be saved (serialized) to a file
1122     * SERIALIZE_COMMANDS_TO_FILE CLIDescriptor's will be loaded/saved from/to a
1123                                single file (cli/.CLIDescriptors) if exists
1124     * SERIALIZE_COMMANDS_TO_FILES CLIDescriptor's will be loaded/saved from the
1125     * multiple files (cli/.{command_name's}) if exists
1126     */

1127    public void setSerializeDescriptorsProperty(int serializeDescriptors)
1128    {
1129        if ((serializeDescriptors <= 2) && (serializeDescriptors >=0))
1130            this.serializeDescriptors = serializeDescriptors;
1131    }
1132    
1133    /**
1134     * Returns the File object of the directory containing the multile
1135       serialized files, each containing a command
1136     * @return File file object of the directory containing all the command files
1137     */

1138    public String JavaDoc getSerializeDir()
1139    {
1140        return serializeDir;
1141    }
1142    
1143    
1144    /**
1145     *
1146     */

1147    private void setSerializeDir(String JavaDoc serializeDir)
1148                    throws CommandValidationException
1149    {
1150        try
1151        {
1152            File JavaDoc file = new File JavaDoc(serializeDir);
1153            if (file.exists())
1154            {
1155                this.serializeDir = serializeDir;
1156            }
1157            else
1158            {
1159        LocalStringsManager lsm =
1160            LocalStringsManagerFactory.getFrameworkLocalStringsManager();
1161        CLILogger.getInstance().printWarning(lsm.getString(
1162                             "InvalidFilePath",
1163                             new Object JavaDoc[] {serializeDir}));
1164            }
1165        }
1166        catch (NullPointerException JavaDoc npe)
1167        {
1168        LocalStringsManager lsm =
1169        LocalStringsManagerFactory.getFrameworkLocalStringsManager();
1170            throw new CommandValidationException(lsm.getString("CouldNoSetSerializeDirectory"),
1171                         npe);
1172        }
1173    }
1174
1175
1176    private void replaceOptionsInCommandsList(HashMap JavaDoc replaceOptions)
1177    {
1178        Iterator JavaDoc replaceOptionNames = replaceOptions.keySet().iterator();
1179        while (replaceOptionNames.hasNext())
1180        {
1181            final String JavaDoc replaceOptionName = (String JavaDoc) replaceOptionNames.next();
1182            Iterator JavaDoc commands = commandsList.getCommands();
1183            while (commands.hasNext())
1184            {
1185                ValidCommand command = (ValidCommand) commands.next();
1186                if ( command.hasValidOption(replaceOptionName) ||
1187                     command.hasRequiredOption(replaceOptionName) ||
1188                     command.hasDeprecatedOption(replaceOptionName) )
1189                {
1190                    command.replaceAllOptions((ValidOption)replaceOptions.get(replaceOptionName));
1191                }
1192            }
1193        }
1194    }
1195    
1196
1197    public String JavaDoc getEnvironmentPrefix(){
1198        if(properties != null){
1199            for(int i = 0 ; i < properties.size(); i++){
1200                Properties JavaDoc props = (Properties JavaDoc)properties.get(i);
1201                String JavaDoc prefix = props.getProperty(ENVIRONMENT_PREFIX);
1202                if(prefix != null)
1203                {
1204                    return prefix;
1205                }
1206            }
1207        }
1208        return null;
1209    }
1210
1211    
1212    public String JavaDoc getEnvironmentFileName(){
1213        if(properties != null){
1214        for(int i = 0 ; i < properties.size(); i++){
1215            Properties JavaDoc props = (Properties JavaDoc)properties.get(i);
1216            String JavaDoc file = props.getProperty(ENVIRONMENT_FILENAME);
1217            if(file != null)
1218            {
1219                return file;
1220            }
1221        }
1222        }
1223        return ".cliprefs";
1224    }
1225
1226    
1227    /**
1228     *main method to test if the functionality works
1229     */

1230    public static void main(String JavaDoc[] args)
1231    {
1232        try
1233        {
1234            //read CLI descriptor
1235
final CLIDescriptorsReader cliDescriptorsReader = CLIDescriptorsReader.getInstance();
1236
1237            //cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILE);
1238
cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.SERIALIZE_COMMANDS_TO_FILES);
1239            //cliDescriptorsReader.setSerializeDescriptorsProperty(CLIDescriptorsReader.DONT_SERIALIZE);
1240

1241            Iterator JavaDoc commands = cliDescriptorsReader.getCommandsList().getCommands();
1242
1243                /*
1244            while(commands.hasNext())
1245                System.out.println((ValidCommand)commands.next());
1246            Iterator propertiesList = cliDescriptorsReader.getProperties();
1247            System.out.println("Properties = ");
1248            while (propertiesList.hasNext())
1249            {
1250                Properties properties = (Properties) propertiesList.next();
1251                System.out.println(properties.toString());
1252            }
1253            System.out.println(cliDescriptorsReader.getCommand("deploy"));
1254                */

1255
1256        }
1257        catch(CommandValidationException cve)
1258        {
1259            System.out.println(cve.getLocalizedMessage());
1260        }
1261    }
1262}
1263
1264
1265class CLIEntityResolver implements EntityResolver JavaDoc {
1266
1267    /** Creates a new instance of CLIEntityResolver */
1268    public CLIEntityResolver() {
1269    }
1270
1271    public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId)
1272        throws org.xml.sax.SAXException JavaDoc, java.io.IOException JavaDoc {
1273        if (systemId.endsWith("CLISpecification.xsd")) {
1274            // return a special input source
1275
InputStream JavaDoc in = this.getClass().getClassLoader().getResourceAsStream(
1276                "com/sun/enterprise/cli/framework/CLISpecification.xsd");
1277            return new InputSource JavaDoc(in);
1278        } else {
1279            // use the default behaviour
1280
return null;
1281        }
1282    }
1283
1284}
1285
1286
Popular Tags