View Javadoc

1   /*
2    * EDI-Knight Integration and Transformation Platform
3    * Copyright (C) 2006-2007 Holger Joest <hjoest@users.sourceforge.net>
4    *
5    * This program is free software; you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation; either version 2 of the License, or
8    * (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
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  package net.sf.ediknight;
21  
22  import java.io.BufferedInputStream;
23  import java.io.BufferedOutputStream;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileOutputStream;
27  import java.io.FilenameFilter;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.OutputStream;
31  import java.net.MalformedURLException;
32  import java.net.URL;
33  import java.net.URLClassLoader;
34  import java.util.Properties;
35  
36  import javax.xml.transform.OutputKeys;
37  import javax.xml.transform.Result;
38  import javax.xml.transform.Source;
39  import javax.xml.transform.Transformer;
40  import javax.xml.transform.TransformerException;
41  import javax.xml.transform.TransformerFactory;
42  import javax.xml.transform.sax.SAXResult;
43  import javax.xml.transform.sax.SAXSource;
44  import javax.xml.transform.stream.StreamResult;
45  
46  import org.apache.commons.cli.CommandLine;
47  import org.apache.commons.cli.CommandLineParser;
48  import org.apache.commons.cli.GnuParser;
49  import org.apache.commons.cli.HelpFormatter;
50  import org.apache.commons.cli.Option;
51  import org.apache.commons.cli.OptionGroup;
52  import org.apache.commons.cli.Options;
53  import org.eclipse.osgi.baseadaptor.BaseAdaptor;
54  import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
55  import org.eclipse.osgi.framework.internal.core.FrameworkProperties;
56  import org.eclipse.osgi.framework.internal.core.OSGi;
57  import org.osgi.framework.Bundle;
58  import org.osgi.framework.BundleContext;
59  import org.osgi.framework.BundleException;
60  import org.xml.sax.ContentHandler;
61  import org.xml.sax.InputSource;
62  import org.xml.sax.SAXException;
63  import org.xml.sax.XMLReader;
64  import org.xml.sax.ext.LexicalHandler;
65  
66  
67  /***
68   *
69   */
70  public final class Server {
71  
72      /*** */
73      private static final String TRANSFORMER_CLASS_STX =
74          "net.sf.joost.trax.TransformerFactoryImpl";
75  
76  
77      /***
78       * No instantiation.
79       */
80      private Server() {
81      }
82  
83  
84      /***
85       * @param args the command line arguments
86       */
87      public static void main(String[] args) {
88          try {
89              File rootDir = getRootDirectory();
90              Properties properties = FrameworkProperties.getProperties();
91              String rootPath = rootDir.getAbsolutePath();
92              properties.setProperty("osgi.install.area", rootPath);
93              String confPath = new File(rootDir, "config").getAbsolutePath();
94              properties.setProperty("osgi.configuration.area", confPath);
95  //            ClassLoader classLoader = getProcessClassLoader();
96  //            Thread thread = Thread.currentThread();
97  //            thread.setContextClassLoader(classLoader);
98              FrameworkAdaptor adaptor = new BaseAdaptor(args);
99              OSGi osgi = new OSGi(adaptor);
100             osgi.launch();
101             BundleContext context = osgi.getBundleContext();
102             for (URL url : listBundleJars()) {
103                 String location = url.toString();
104                 if (!location.endsWith("/osgi-3.3.0-v20070530.jar")) {
105                 	System.err.println("Installing " + location);
106                     context.installBundle(location);
107                 }
108             }
109             Bundle[] bundles = context.getBundles();
110             for (Bundle bundle : bundles) {
111             	System.err.println("Starting " + bundle.getSymbolicName());
112                 bundle.start();
113             }
114             CommandLine cmd = parseCommandLine(args);
115             ConverterFactory factory =
116                 ConverterFactory.newInstance();
117             Converter converter =
118                 factory.createConverter("default");
119             InputStream in = null;
120             String optionIn = cmd.getOptionValue("in");
121             if (optionIn == null) {
122                 in = System.in;
123             } else {
124                 in = new FileInputStream(optionIn);
125             }
126             in = converter.recognize(in);
127             Transformer transformer = null;
128             boolean indent = true;
129             String optionXsl = cmd.getOptionValue("xsl");
130             if (optionXsl == null) {
131                 optionXsl = cmd.getOptionValue("stx");
132                 if (optionXsl != null) {
133                     indent = false;
134                     System.setProperty(
135                             "javax.xml.transform.TransformerFactory",
136                             TRANSFORMER_CLASS_STX);
137                 }
138             }
139             TransformerFactory transformerFactory =
140                 TransformerFactory.newInstance();
141             if (optionXsl == null) {
142                 transformer = transformerFactory.newTransformer();
143             } else {
144                 InputStream xsl =
145                     new BufferedInputStream(new FileInputStream(optionXsl));
146                 InputSource input = new InputSource(xsl);
147                 Source source = new SAXSource(input);
148                 transformer = transformerFactory.newTransformer(source);
149             }
150             if (indent) {
151                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
152             }
153             if (cmd.hasOption("text") || cmd.hasOption("html")) {
154                 transformer.setOutputProperty(
155                         OutputKeys.OMIT_XML_DECLARATION, "yes");
156             }
157             Parser<Format> parser = converter.getParser();
158             XMLReader reader = parser.getXMLReader();
159             InputSource input = new InputSource(in);
160             Source source = new SAXSource(reader, input);
161             OutputStream out = null;
162             String optionOut = cmd.getOptionValue("out");
163             if (optionOut == null) {
164                 out = System.out;
165             } else {
166                 out = new BufferedOutputStream(new FileOutputStream(optionOut));
167             }
168             String optionFormat = cmd.getOptionValue("format");
169             ContentHandler contentHandler =
170                 converter.getContentHandler(optionFormat, out);
171             try {
172                 Result result = null;
173                 if (contentHandler != null) {
174                     result = new SAXResult(contentHandler);
175                     if (contentHandler instanceof LexicalHandler) {
176                         ((SAXResult) result).setLexicalHandler(
177                                 (LexicalHandler) contentHandler);
178                     }
179                 } else {
180                     result = new StreamResult(out);
181                 }
182                 transformer.transform(source, result);
183             } finally {
184                 out.close();
185             }
186             System.exit(0);
187         } catch (IOException ex) {
188             System.err.println(ex.getMessage());
189         } catch (TransformerException ex) {
190             Throwable contained = ex.getException();
191             if (contained instanceof SAXException) {
192                 SAXException saxException = (SAXException) contained;
193                 contained = saxException.getException();
194                 if (contained instanceof ParseException) {
195                     ParseException parseException =
196                         (ParseException) contained;
197                     System.err.println(parseException.getMessage());
198                     System.exit(-1);
199                 }
200             }
201             System.err.println(ex.getMessage());
202         } catch (ConfigurationException ex) {
203             System.err.println(ex.getMessage());
204         } catch (BundleException ex) {
205             System.err.println(ex.getMessage());
206             ex.printStackTrace();
207         } catch (Exception ex) {
208             ex.printStackTrace();
209         }
210         System.exit(-1);
211     }
212 
213 
214     /***
215      * @param args the command line arguments as a string array
216      * @return the command line
217      */
218     private static CommandLine parseCommandLine(String[] args) {
219         Options options = new Options();
220         options.addOption("in", true, "input edifact url");
221         options.addOption("out", true, "output file");
222         OptionGroup trafosGroup = new OptionGroup();
223         try {
224             ClassLoader classLoader =
225                 Thread.currentThread().getContextClassLoader();
226             classLoader.loadClass(TRANSFORMER_CLASS_STX);
227             Option stxOption =
228                 new Option("stx", true, "stx transformation script");
229             trafosGroup.addOption(stxOption);
230         } catch (ClassNotFoundException ex) { }
231         Option xslOption =
232             new Option("xsl", true, "xsl transformation script");
233         trafosGroup.addOption(xslOption);
234         options.addOptionGroup(trafosGroup);
235         Option formatOption =
236             new Option("format", true, "the output formatter");
237         options.addOption(formatOption);
238         CommandLineParser parser = new GnuParser();
239         CommandLine cmd = null;
240         try {
241             cmd = parser.parse(options, args);
242         } catch (Exception exp) {
243             System.err.println(exp.getMessage());
244             HelpFormatter formatter = new HelpFormatter();
245             formatter.printHelp("ediknight", options);
246             System.exit(1);
247         }
248         return cmd;
249     }
250 
251 
252     /***
253      * Creates a classloader that scans the <it>lib</it>
254      * directory for JAR files.
255      *
256      * @return the classloader
257      */
258     private static ClassLoader getProcessClassLoader() {
259         URL[] urls = listStandardJars();
260         ClassLoader parent =
261             Thread.currentThread().getContextClassLoader();
262         return new URLClassLoader(urls, parent);
263     }
264 
265 
266     /***
267      * Returns the bundle locations.
268      *
269      * @return the bundles
270      */
271     private static URL[] listStandardJars() {
272         File ediknightHome = getRootDirectory();
273         File ediknightLib = new File(ediknightHome, "lib");
274         FilenameFilter filter = new FilenameFilter() {
275 
276             public boolean accept(File dir, String name) {
277                 if (name.endsWith(".jar")) {
278                 	if (name.contains("xstream")) {
279                 		return true;
280                 	}
281                 }
282                 return false;
283             }
284 
285         };
286         File[] jars = ediknightLib.listFiles(filter);
287         URL[] urls = new URL[jars.length];
288         for (int k = 0; k < urls.length; ++k) {
289             try {
290                 urls[k] = jars[k].toURI().toURL();
291             } catch (MalformedURLException ex) {
292                 throw new RuntimeException(ex.toString(), ex);
293             }
294         }
295         return urls;
296     }
297 
298 
299     /***
300      * Returns the bundle locations.
301      *
302      * @return the bundles
303      */
304     private static URL[] listBundleJars() {
305         File ediknightHome = getRootDirectory();
306         File ediknightLib = new File(ediknightHome, "lib");
307         FilenameFilter filter = new FilenameFilter() {
308 
309             public boolean accept(File dir, String name) {
310                 return name.endsWith(".jar");
311             }
312 
313         };
314         File[] jars = ediknightLib.listFiles(filter);
315         URL[] urls = new URL[jars.length];
316         for (int k = 0; k < urls.length; ++k) {
317             try {
318                 urls[k] = jars[k].toURI().toURL();
319             } catch (MalformedURLException ex) {
320                 throw new RuntimeException(ex.toString(), ex);
321             }
322         }
323         return urls;
324     }
325 
326 
327     /***
328      * Returns the root directory of this EDI-Knight installation.
329      *
330      * @return the installation directory
331      */
332     private static File getRootDirectory() {
333         String ediknightHomePath =
334             System.getProperty("net.sf.ediknight.home");
335         if (ediknightHomePath == null
336                 || ediknightHomePath.trim().length() == 0) {
337             throw new RuntimeException(
338                     "Property 'net.sf.ediknight.home' must"
339                     + " point to the installation directory"
340                     + " of EDI Knight");
341         }
342         File ediknightHome = new File(ediknightHomePath);
343         if (!ediknightHome.isDirectory()) {
344             throw new RuntimeException(
345                     "The file '" + ediknightHomePath + "'"
346                     + " doesn't exist or isn't a directory."
347                     + " Please check the value of the property"
348                     + " 'net.sf.ediknight.home'.");
349         }
350         return ediknightHome;
351     }
352 
353 }
354