KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > xquark > fusion > Main


1 /*
2  * This file belongs to the XQuark distribution.
3  * Copyright (C) 2003 Universite de Versailles Saint-Quentin.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307.
18  * You can also get it at http://www.gnu.org/licenses/lgpl.html
19  *
20  * For more information on this software, see http://www.xquark.org.
21  */

22
23 package org.xquark.fusion;
24
25 import java.io.*;
26 import java.net.MalformedURLException JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30
31 import javax.xml.parsers.SAXParserFactory JavaDoc;
32
33 import org.apache.log4j.Level;
34 import org.apache.log4j.Logger;
35 import org.xml.sax.SAXException JavaDoc;
36 import org.xquark.mediator.Mediator;
37 import org.xquark.serialize.XMLSerializer;
38 import org.xquark.xml.xdbc.*;
39
40 /**
41  * This class is the command-line launcher for Fusion. It is mostly useful
42  * for test and demo purposes, as the JVM and connection setup overhead
43  * are prohibitive in most cases.
44  */

45 public class Main {
46     private static final String JavaDoc RCSRevision = "$Revision: 1.2 $";
47     private static final String JavaDoc RCSName = "$Name: $";
48
49     private static final String JavaDoc HELP_OPT1 = "-help";
50     private static final String JavaDoc HELP_OPT2 = "-?";
51     private static final String JavaDoc CONF_OPT = "-conf";
52     private static final String JavaDoc FILE_OPT1 = "-file";
53     private static final String JavaDoc FILE_OPT2 = "-f";
54     private static final String JavaDoc DEBUG_OPT = "-debug";
55
56     private static SAXParserFactory JavaDoc parserFactory;
57
58     static {
59         parserFactory = SAXParserFactory.newInstance();
60         parserFactory.setNamespaceAware(true);
61     }
62
63     private String JavaDoc configurationFile;
64     private Mediator mediator = null;
65
66     /** The constructor for the XQFusion object.
67      */

68     public Main() {
69     }
70     
71     /** The constructor for the XQFusion object.
72      * @param confFile the XQFusion configuration file
73      */

74     public Main(String JavaDoc confFile) {
75         if (confFile == null)
76             throw new NullPointerException JavaDoc("Illegal null value for configuration file");
77         configurationFile = confFile;
78     }
79     
80     private Mediator getMediator() throws XMLDBCException {
81         if (mediator == null) {
82             if (configurationFile != null) {
83                 mediator = new Mediator(configurationFile);
84             } else {
85                 mediator = new Mediator();
86             }
87         }
88         return mediator;
89     }
90     
91     public XMLConnection getConnection() throws XMLDBCException {
92         return getMediator().getConnection();
93     }
94
95     /* This part of the file deals with command-line execution */
96
97     /**
98      * The method called from the command line to run Fusion as a standalone program.
99      * Use the -help option to display a list of available options.
100      * @param args the command line parameters
101      */

102     public static void main(String JavaDoc[] args) {
103         String JavaDoc configFile = null;
104         String JavaDoc batchFile = null;
105         ArrayList JavaDoc parameters = new ArrayList JavaDoc();
106
107         for (int i = 0; i < args.length; i++) {
108             if (!args[i].startsWith("-")) {
109                 // not an option
110
parameters.add(args[i]);
111                 
112             } else {
113                 // Check options are in first position
114
if (parameters.size() > 0) {
115                     usage();
116                     System.err.println("Options must appear before the command parameters.");
117                     System.exit(-1);
118                 }
119                 // one-parameter option
120
if (HELP_OPT1.equals(args[i]) || HELP_OPT2.equals(args[i])) {
121                     usage();
122                     System.exit(0);
123                 } else {
124                     // two-parameter option
125
if (i + 1 == args.length) {
126                         System.err.println("Missing value for option " + args[i]);
127                         usage();
128                         System.exit(-1);
129                     } else if (DEBUG_OPT.equals(args[i])) {
130                         Logger.getRootLogger().setLevel(Level.DEBUG);
131                     } else if (CONF_OPT.equals(args[i])) {
132                         configFile = args[++i];
133                     } else if (FILE_OPT1.equals(args[i]) || FILE_OPT2.equals(args[i])) {
134                         batchFile = args[++i];
135                     } else {
136                         // Unknown option
137
System.err.println("Invalid option " + args[i]);
138                         usage();
139                         System.exit(-1);
140                     }
141                 }
142             }
143         }
144
145         List JavaDoc parametersList = null;
146         if (batchFile != null) {
147             parametersList = parseBatchFile(batchFile);
148         } else {
149             checkParameters(parameters);
150             parametersList = new ArrayList JavaDoc();
151             parametersList.add(parameters);
152         }
153
154         Main fusion = null;
155         if (configFile != null) {
156             try {
157                 configFile = new File(configFile).toURL().toString();
158                 fusion = new Main(configFile);
159             } catch (MalformedURLException JavaDoc ex) {
160                 System.err.println("Invalid configuration file specification.");
161                 printError(ex);
162                 System.exit(-1);
163             }
164         } else {
165             fusion = new Main();
166         }
167         
168 // try {
169
// PrintWriter writer = new PrintWriter(System.out, true);
170
// Iterator it = fusion.getMediator().getWrappers().values().iterator();
171
// while (it.hasNext()) {
172
// XMLDataSource s = ((XDBCWrapper) it.next()).getDataSource();
173
// s.setLogWriter(writer);
174
// }
175
// } catch (Exception e) {
176
// System.err.println("Error in trace.");
177
// printError(e);
178
// System.exit(-1);
179
// }
180

181         int result = fusion.executeQuery(parametersList);
182         System.exit(result);
183     }
184
185     private static void checkParameters(List JavaDoc params) {
186         int size = params.size();
187         if (size < 1 || size > 2) {
188             System.err.println("Wrong number of parameters.");
189             System.exit(-1);
190         }
191     }
192
193     private static List JavaDoc parseBatchFile(String JavaDoc batchFile) {
194         ArrayList JavaDoc result = new ArrayList JavaDoc();
195         BufferedReader reader = null;
196         try {
197             File f = new File(batchFile);
198             reader = new BufferedReader(new FileReader(f));
199         } catch (IOException ex) {
200             System.err.println("Could not find specified batch file");
201             System.exit(-1);
202         }
203         try {
204             while (true) {
205                 String JavaDoc line = reader.readLine();
206                 if (line == null)
207                     break;
208                 if (line.startsWith("#") || line.trim().length() == 0)
209                     continue;
210                 java.util.StringTokenizer JavaDoc it = new java.util.StringTokenizer JavaDoc(line);
211                 ArrayList JavaDoc params = new ArrayList JavaDoc();
212                 while (it.hasMoreTokens()) {
213                     params.add(it.nextToken());
214                 }
215                 checkParameters(params);
216                 result.add(params);
217             }
218         } catch (IOException e) {
219             System.err.println("Error while reading specified batch file");
220             System.exit(-1);
221         }
222         return result;
223     }
224
225     private static String JavaDoc readQueryFile(String JavaDoc fileName) {
226         try {
227             StringBuffer JavaDoc retVal = new StringBuffer JavaDoc();
228             String JavaDoc tmpStr;
229             BufferedReader in = new BufferedReader(new FileReader(fileName));
230             while ((tmpStr = in.readLine()) != null) {
231                 if (retVal.length() > 0)
232                     retVal.append('\n');
233                 retVal.append(tmpStr);
234             }
235             in.close();
236             return retVal.toString();
237         } catch (FileNotFoundException ex) {
238             System.err.println("Could not find query file " + fileName);
239         } catch (IOException ex) {
240             System.err.println("Error while reading query file " + fileName);
241         }
242         return null;
243     }
244
245     private int executeQuery(List JavaDoc parametersList) {
246         XMLConnection connection = null;
247         XMLStatement stat = null;
248         int result = 0;
249         try {
250             connection = getConnection();
251             stat = connection.createStatement();
252             Iterator JavaDoc it = parametersList.iterator();
253             while (it.hasNext()) {
254                 List JavaDoc params = (List JavaDoc) it.next();
255                 String JavaDoc queryFile = (String JavaDoc) params.get(0);
256                 String JavaDoc resultFile = null;
257                 if (params.size() > 1)
258                     resultFile = (String JavaDoc) params.get(1);
259                 String JavaDoc query = readQueryFile(queryFile);
260                 if (query != null) {
261                     OutputStream out = System.out;
262                     try {
263                         if (resultFile != null) {
264                             out = new BufferedOutputStream(new FileOutputStream(new File(resultFile)));
265                         }
266                     } catch (IOException ex) {
267                         out = null;
268                         System.err.println("Could not open result file " + resultFile);
269                         result = -1;
270                     }
271                     if (out != null) {
272                         try {
273                             stat.setBaseURI(new File(queryFile).toURL().toString());
274                             XMLResultSet rs = stat.executeQuery(query);
275                             XMLSerializer handler = new XMLSerializer(out);
276                             rs.setContentHandler(handler);
277                             handler.startDocument();
278                             while (rs.hasNext())
279                                 rs.nextAsSAX();
280                             handler.endDocument();
281                             rs.close();
282                             if (out != System.out)
283                                 out.close();
284                         } catch (SAXException JavaDoc ex) {
285                             System.err.println("Error while processing query result " + queryFile);
286                             printError(ex);
287                             result = -1;
288                         } catch (IOException ex) {
289                             System.err.println("Error while creating query result " + queryFile);
290                             printError(ex);
291                             result = -1;
292                         } catch (XMLDBCException ex) {
293                             System.err.println("Error while executing query " + queryFile);
294                             printError(ex);
295                             result = -1;
296                         }
297                     }
298                 }
299             }
300         } catch (XMLDBCException e) {
301             System.err.println("Could not create connection and statement");
302             printError(e);
303             System.exit(-1);
304         } finally {
305             try {
306                 if (stat != null) stat.close();
307                 if (connection != null) connection.close();
308             } catch (XMLDBCException e) {
309                 System.err.println("Could not close connection and statement");
310                 printError(e);
311                 System.exit(-1);
312             }
313         }
314         return result;
315     }
316
317     /**
318      * Print an error message to the standard error output.
319      */

320     private static void printError(Throwable JavaDoc e) {
321         XMLDBCException.printError(e, Logger.getRootLogger().isDebugEnabled());
322     }
323
324     private static void usage() {
325         System.out.println("Usage: java org.xquark.fusion.Main <options> [<file1> [<file2>]]");
326         System.out.println();
327         System.out.println("file1: XQuery file, required unless the -file option is used");
328         System.out.println("file2: optional output file, output to stdout by default");
329         System.out.println();
330         System.out.println("Options:");
331         System.out.println("-?, -help: this message");
332         System.out.println("-conf conffile: configuration file, required when accessing data sources.");
333         System.out.println(" It can be omitted when querying only documents.");
334         System.out.println("-f file: file containing a list of files to be processed.");
335         System.out.println(" Each line of the file has one query file and an optional output file.");
336         System.out.println(" Lines starting with # are comments");
337     }
338
339 }
340
Popular Tags