KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > chaperon > adapter > cli > Main


1 /*
2  * Copyright (C) Chaperon. All rights reserved.
3  * -------------------------------------------------------------------------
4  * This software is published under the terms of the Apache Software License
5  * version 1.1, a copy of which has been included with this distribution in
6  * the LICENSE file.
7  */

8
9 package net.sourceforge.chaperon.adapter.cli;
10
11 import net.sourceforge.chaperon.build.Automaton;
12 import net.sourceforge.chaperon.common.ConsoleLog;
13 import net.sourceforge.chaperon.model.grammar.*;
14 import net.sourceforge.chaperon.process.GeneralParserProcessor;
15
16 import org.apache.commons.cli.CommandLine;
17 import org.apache.commons.cli.Option;
18 import org.apache.commons.cli.Options;
19 import org.apache.commons.cli.ParseException;
20 import org.apache.commons.cli.PosixParser;
21
22 //import org.xml.sax.ContentHandler;
23
import org.xml.sax.SAXParseException JavaDoc;
24 import org.xml.sax.XMLReader JavaDoc;
25
26 import java.io.File JavaDoc;
27
28 import java.util.Properties JavaDoc;
29
30 import javax.xml.parsers.SAXParserFactory JavaDoc;
31 import javax.xml.transform.OutputKeys JavaDoc;
32 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
33 import javax.xml.transform.sax.TransformerHandler JavaDoc;
34 import javax.xml.transform.stream.StreamResult JavaDoc;
35
36 public class Main
37 {
38   public static final String JavaDoc LEXICON_OPT = "l";
39   public static final String JavaDoc LEXICON_OPT_LONG = "lexicon";
40   public static final String JavaDoc GRAMMAR_OPT = "g";
41   public static final String JavaDoc GRAMMAR_OPT_LONG = "grammar";
42   public static final String JavaDoc IN_OPT = "i";
43   public static final String JavaDoc IN_OPT_LONG = "in";
44   public static final String JavaDoc OUT_OPT = "o";
45   public static final String JavaDoc OUT_OPT_LONG = "out";
46   private File JavaDoc lexiconFile = null;
47   private File JavaDoc grammarFile = null;
48   private File JavaDoc cacheDir = null;
49   private String JavaDoc parserFactory = null;
50   private SAXParserFactory JavaDoc parserFactoryImpl = null;
51   private String JavaDoc transformerFactory = null;
52   private SAXTransformerFactory JavaDoc transformerFactoryImpl = null;
53   private String JavaDoc encoding = "ISO-8859-1";
54   private boolean indent = false;
55
56   //private boolean flatten = false;
57
//private String inputtype = "text";
58
private ConsoleLog log = new ConsoleLog();
59
60   /*private ParserHandlerAdapter parseradapter = null;
61   private ParserAutomaton parserautomaton = null;
62   private ParserProcessor parser = null;*/

63   /*private LexicalHandlerAdapter lexicaladapter = null;
64   private LexicalAutomaton lexicalautomaton = null;
65   private LexicalProcessor lexer = null;*/

66   private Automaton parserautomaton = null;
67   private GeneralParserProcessor parser = null;
68
69   /**
70    * Set the lexicon, which should be used.
71    *
72    * @param lexiconFile Lexicon file.
73    */

74   public void setLexicon(File JavaDoc lexiconFile)
75   {
76     this.lexiconFile = lexiconFile;
77   }
78
79   /**
80    * Set the grammar, which should be used.
81    *
82    * @param grammarFile Grammar file.
83    */

84   public void setGrammar(File JavaDoc grammarFile)
85   {
86     this.grammarFile = grammarFile;
87   }
88
89   private void process(File JavaDoc inFile, File JavaDoc outFile) throws Exception JavaDoc
90   {
91     if (!inFile.exists())
92       throw new Exception JavaDoc("File "+inFile+" doesn't exists");
93
94     if (inFile.lastModified()>outFile.lastModified())
95     {
96       ensureDirectoryFor(outFile);
97       System.out.println("Parsing file "+inFile+" to "+outFile); //info
98

99       /*if ((this.parserautomaton!=null) && (this.parseradapter==null))
100       {
101         this.parseradapter = new ParserHandlerAdapter();
102         this.parseradapter.setFlatten(this.flatten);
103         if (inputtype.equalsIgnoreCase("xml"))
104           this.parseradapter.setEmbedded(true);
105       }
106
107       if ((this.parserautomaton==null) && (this.lexicaladapter==null))
108       {
109         this.lexicaladapter = new LexicalHandlerAdapter();
110       }
111
112       if ((this.parserautomaton!=null) && (this.parser==null))
113       {
114         this.parser = new ParserProcessor();
115         this.parser.setLog(log);
116         this.parser.setParserAutomaton(this.parserautomaton);
117         this.parser.setParserHandler(this.parseradapter);
118       }
119
120       if (this.lexer==null)
121       {
122         this.lexer = new LexicalProcessor();
123         this.lexer.setLog(log);
124         this.lexer.setLexicalAutomaton(this.lexicalautomaton);
125         if (this.parserautomaton!=null)
126           this.lexer.setLexicalHandler(this.parser);
127         else
128           this.lexer.setLexicalHandler(this.lexicaladapter);
129       }*/

130       this.parser = new GeneralParserProcessor();
131       this.parser.setLog(log);
132       this.parser.setParserAutomaton(this.parserautomaton);
133
134       Properties JavaDoc format = new Properties JavaDoc();
135
136       format.put(OutputKeys.ENCODING, encoding);
137       if (indent)
138         format.put(OutputKeys.INDENT, "yes");
139
140       format.put(OutputKeys.METHOD, "xml");
141
142       SAXTransformerFactory JavaDoc factory = getTransformerFactory();
143
144       TransformerHandler JavaDoc serializer = factory.newTransformerHandler();
145       serializer.getTransformer().setOutputProperties(format);
146       serializer.setResult(new StreamResult JavaDoc(outFile));
147
148       /*if (this.parserautomaton!=null)
149         this.parseradapter.setContentHandler(serializer);
150       else
151         this.lexicaladapter.setContentHandler(serializer);*/

152       this.parser.setContentHandler(serializer);
153
154       /*if ( !inputtype.equalsIgnoreCase("xml"))
155         pushTextFile(inFile);
156       else*/

157       pushXMLFile(inFile);
158     }
159   }
160
161   private void buildAutomata(File JavaDoc lexiconFile, File JavaDoc grammarFile)
162     throws Exception JavaDoc
163   {
164     if ((cacheDir!=null) && (!cacheDir.exists()))
165       throw new Exception JavaDoc("Cache directory "+cacheDir+" doesn't exist");
166
167     /*
168     // Lexicon
169     String filename = lexiconFile.getName();
170
171     File cacheFile = null;
172     if (cacheDir!=null)
173       cacheFile = new File(cacheDir, filename+".obj");
174
175     if ((cacheFile!=null) && (cacheFile.exists()) && (cacheFile.lastModified()>lexiconFile.lastModified()))
176     {
177       System.out.println("Reading lexicon from cache "+cacheFile); //debug
178       ObjectInputStream in = new ObjectInputStream(new FileInputStream(cacheFile));
179       this.lexicalautomaton = (LexicalAutomaton)in.readObject();
180       in.close();
181     }
182     else
183     {
184       System.out.println("Building lexicon from "+lexiconFile); //info
185       SAXParserFactory factory = getParserFactory();
186
187       factory.setNamespaceAware(true);
188       XMLReader parser = factory.newSAXParser().getXMLReader();
189
190       NamespacedSAXConfigurationHandler handler = new NamespacedSAXConfigurationHandler();
191
192       parser.setContentHandler(handler);
193       try
194       {
195         parser.parse(lexiconFile.toString());
196       }
197       catch (SAXParseException se)
198       {
199         throw new Exception("Couldn't parse file "+lexiconFile+": "+se.getMessage());
200       }
201       Configuration lexiconconfig = handler.getConfiguration();
202       Lexicon lexicon = LexiconFactory.createLexicon(lexiconconfig);
203
204       this.lexicalautomaton = (new LexicalAutomatonBuilder(lexicon,
205           log)).getLexicalAutomaton();
206
207       if (cacheFile!=null)
208       {
209         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cacheFile));
210         out.writeObject(this.lexicalautomaton);
211         out.flush();
212         out.close();
213       }
214     }*/

215     if (grammarFile!=null)
216     {
217       // Grammar
218
//String filename = grammarFile.getName();
219

220       /*cacheFile = null;
221       if (cacheDir!=null)
222         cacheFile = new File(cacheDir, filename+".obj");*/

223       /*if ((cacheFile!=null) && (cacheFile.exists()) && (cacheFile.lastModified()>grammarFile.lastModified()))
224       {
225         System.out.println("Reading grammar from cache "+cacheFile); //debug
226         ObjectInputStream in = new ObjectInputStream(new FileInputStream(cacheFile));
227         this.parserautomaton = (ParserAutomaton)in.readObject();
228         in.close();
229       }
230       else
231       {*/

232       System.out.println("Building grammar from "+grammarFile); //info
233

234       SAXParserFactory JavaDoc factory = getParserFactory();
235
236       factory.setNamespaceAware(true);
237
238       XMLReader JavaDoc parser = factory.newSAXParser().getXMLReader();
239
240       //NamespacedSAXConfigurationHandler handler = new NamespacedSAXConfigurationHandler();
241
GrammarFactory grammarfactory = new GrammarFactory();
242       parser.setContentHandler(grammarfactory);
243       try
244       {
245         parser.parse(grammarFile.toString());
246       }
247       catch (SAXParseException JavaDoc se)
248       {
249         throw new Exception JavaDoc("Couldn't parse file "+lexiconFile+": "+se.getMessage());
250       }
251
252       //Configuration grammarconfig = handler.getConfiguration();
253
//Grammar grammar = GrammarFactory.createGrammar(grammarconfig);
254
Grammar grammar = grammarfactory.getGrammar();
255
256       /*this.parserautomaton = (new ParserAutomatonBuilder(grammar,
257           log)).getParserAutomaton();*/

258       this.parserautomaton = new Automaton(grammar, log);
259
260       /*if (cacheFile!=null)
261       {
262         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cacheFile));
263         out.writeObject(this.parserautomaton);
264         out.flush();
265         out.close();
266       }*/

267
268       //}
269
}
270   }
271
272   /*private void pushTextFile(File inFile) throws Exception
273   {
274     try
275     {
276       TextLocator locator = new TextLocator();
277
278       locator.setURI(inFile.toURL().toString());
279       locator.setLineNumber(1);
280       locator.setColumnNumber(1);
281
282       this.lexer.handleLocator(locator);
283       this.lexer.handleStartDocument();
284
285       LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(inFile)));
286
287       String line, newline = null;
288       String separator = System.getProperty("line.separator");
289
290       while (true)
291       {
292         if (newline==null)
293           line = reader.readLine();
294         else
295           line = newline;
296
297         if (line==null)
298           break;
299
300         newline = reader.readLine();
301
302         line = (newline!=null) ? line+separator : line;
303
304         locator.setLineNumber(reader.getLineNumber());
305         locator.setColumnNumber(1);
306         this.lexer.handleText(line);
307
308         if (newline==null)
309           break;
310       }
311
312       reader.close();
313
314       this.lexer.handleEndDocument();
315     }
316     catch (SAXParseException se)
317     {
318       throw new Exception("Exception occurs during parsing file "+inFile+
319                                " at line "+se.getLineNumber()+" column "+
320                                se.getColumnNumber()+": "+se.getMessage());
321     }
322
323   }*/

324   private void pushXMLFile(File JavaDoc inFile) throws Exception JavaDoc
325   {
326     SAXParserFactory JavaDoc parserfactory = getParserFactory();
327
328     parserfactory.setNamespaceAware(true);
329
330     XMLReader JavaDoc parser = parserfactory.newSAXParser().getXMLReader();
331
332     /*LexicalProcessorAdapter handler = new LexicalProcessorAdapter();
333
334     handler.setLexicalProcessor(this.lexer);
335     handler.setContentHandler(serializer);
336
337     parser.setContentHandler(handler);*/

338     parser.setContentHandler(this.parser);
339     try
340     {
341       parser.parse(inFile.toString());
342     }
343     catch (SAXParseException JavaDoc se)
344     {
345       throw new Exception JavaDoc("Exception occurs during parsing file "+inFile+" at line "+
346                           se.getLineNumber()+" column "+se.getColumnNumber()+": "+se.getMessage());
347     }
348   }
349
350   private void ensureDirectoryFor(File JavaDoc targetFile) throws Exception JavaDoc
351   {
352     File JavaDoc directory = new File JavaDoc(targetFile.getParent());
353
354     if ((!directory.exists()) && (!directory.mkdirs()))
355       throw new Exception JavaDoc("Unable to create directory: "+directory.getAbsolutePath());
356   }
357
358   private SAXParserFactory JavaDoc getParserFactory() throws Exception JavaDoc
359   {
360     if (parserFactoryImpl==null)
361     {
362       try
363       {
364         if (parserFactory==null)
365           parserFactoryImpl = SAXParserFactory.newInstance();
366         else
367           parserFactoryImpl = (SAXParserFactory JavaDoc)Class.forName(parserFactory).newInstance();
368       }
369       catch (Exception JavaDoc e)
370       {
371         throw new Exception JavaDoc("Could not load parser factory: "+e.getMessage());
372       }
373     }
374
375     return parserFactoryImpl;
376   }
377
378   private SAXTransformerFactory JavaDoc getTransformerFactory()
379     throws Exception JavaDoc
380   {
381     if (transformerFactoryImpl==null)
382     {
383       try
384       {
385         if (transformerFactory==null)
386           transformerFactoryImpl = (SAXTransformerFactory JavaDoc)SAXTransformerFactory.newInstance();
387         else
388           transformerFactoryImpl =
389             (SAXTransformerFactory JavaDoc)Class.forName(transformerFactory).newInstance();
390       }
391       catch (Exception JavaDoc e)
392       {
393         throw new Exception JavaDoc("Could not load transformer factory: "+e.getMessage());
394       }
395     }
396
397     return transformerFactoryImpl;
398   }
399
400   public static void main(String JavaDoc[] args)
401   {
402     Options options = new Options();
403
404     options.addOption(new Option(LEXICON_OPT, LEXICON_OPT_LONG, true,
405                                  "specify lexicon, which should be used"));
406
407     options.addOption(new Option(GRAMMAR_OPT, GRAMMAR_OPT_LONG, true,
408                                  "specify grammar, which should be used"));
409
410     options.addOption(new Option(IN_OPT, IN_OPT_LONG, true, "Input file"));
411
412     options.addOption(new Option(OUT_OPT, OUT_OPT_LONG, true, "Output file"));
413
414     CommandLine line = null;
415     try
416     {
417       line = new PosixParser().parse(options, args);
418     }
419     catch (ParseException pe)
420     {
421       System.err.println(pe.getMessage());
422       return;
423     }
424
425     if (!line.hasOption(LEXICON_OPT))
426     {
427       System.err.println("Lexicon is not specified");
428       return;
429     }
430
431     if (!line.hasOption(GRAMMAR_OPT))
432     {
433       System.err.println("Grammar is not specified");
434       return;
435     }
436
437     if (!line.hasOption(IN_OPT))
438     {
439       System.err.println("Input file is not specified");
440       return;
441     }
442
443     if (!line.hasOption(OUT_OPT))
444     {
445       System.err.println("Output file is not specified");
446       return;
447     }
448
449     Main main = new Main();
450     main.setLexicon(new File JavaDoc(line.getOptionValue(LEXICON_OPT)));
451     main.setGrammar(new File JavaDoc(line.getOptionValue(GRAMMAR_OPT)));
452
453     try
454     {
455       main.process(new File JavaDoc(line.getOptionValue(IN_OPT)), new File JavaDoc(line.getOptionValue(OUT_OPT)));
456     }
457     catch (Exception JavaDoc e)
458     {
459       System.err.println(e.getMessage());
460     }
461   }
462 }
463
Popular Tags