View Javadoc

1   /*
2    * @(#)$Id: XMLTool.java 736 2009-08-14 09:20:17Z kurmannu $
3    *
4    * Author       :   Ueli Kurmann, igesture@uelikurmann.ch
5    *
6    * Purpose      : 	Provides static methods with XML import/export 
7    * 					functionality.
8    *
9    * -----------------------------------------------------------------------
10   *
11   * Revision Information:
12   *
13   * Date             Who         Reason
14   *
15   * Dec 26, 2006     ukurmann    Initial Release
16   * Mar 23, 2007     bsigner     Cleanup
17   *
18   * -----------------------------------------------------------------------
19   *
20   * Copyright 1999-2009 ETH Zurich. All Rights Reserved.
21   *
22   * This software is the proprietary information of ETH Zurich.
23   * Use is subject to license terms.
24   * 
25   */
26  
27  
28  package org.ximtec.igesture.util;
29  
30  import java.io.File;
31  import java.io.FileInputStream;
32  import java.io.FileNotFoundException;
33  import java.io.FileOutputStream;
34  import java.io.FileReader;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.io.StringReader;
38  import java.io.StringWriter;
39  import java.util.ArrayList;
40  import java.util.HashSet;
41  import java.util.List;
42  import java.util.Set;
43  import java.util.logging.Level;
44  import java.util.logging.Logger;
45  
46  import javax.xml.transform.Transformer;
47  import javax.xml.transform.TransformerConfigurationException;
48  import javax.xml.transform.TransformerException;
49  import javax.xml.transform.TransformerFactory;
50  import javax.xml.transform.TransformerFactoryConfigurationError;
51  import javax.xml.transform.stream.StreamResult;
52  import javax.xml.transform.stream.StreamSource;
53  
54  import org.apache.commons.io.IOUtils;
55  import org.jdom.Document;
56  import org.jdom.Element;
57  import org.jdom.JDOMException;
58  import org.jdom.input.SAXBuilder;
59  import org.sigtec.jdom.JdomDocument;
60  import org.sigtec.jdom.id.Factory;
61  import org.sigtec.util.Constant;
62  import org.sigtec.util.FileHandler;
63  import org.ximtec.igesture.batch.BatchProcessContainer;
64  import org.ximtec.igesture.batch.BatchResultSet;
65  import org.ximtec.igesture.batch.core.jdom.JdomBatchAlgorithm;
66  import org.ximtec.igesture.batch.jdom.JdomBatchResultSet;
67  import org.ximtec.igesture.configuration.Configuration;
68  import org.ximtec.igesture.configuration.jdom.JdomConfiguration;
69  import org.ximtec.igesture.core.GestureClass;
70  import org.ximtec.igesture.core.GestureSet;
71  import org.ximtec.igesture.core.TestSet;
72  import org.ximtec.igesture.core.jdom.JdomGestureClass;
73  import org.ximtec.igesture.core.jdom.JdomGestureSet;
74  import org.ximtec.igesture.core.jdom.JdomTestSet;
75  import org.xml.sax.InputSource;
76  
77  
78  /**
79   * Provides static methods with XML import/export functionality.
80   * 
81   * @version 1.0, Dec 2006
82   * @author Ueli Kurmann, igesture@uelikurmann.ch
83   * @author Beat Signer, signer@inf.ethz.ch
84   */
85  public class XMLTool {
86  
87     private static final Logger LOGGER = Logger
88           .getLogger(XMLTool.class.getName());
89  
90     public static final String ROOT_TAG = "sets";
91     public static final String TEST_SETS_TAG = "testSets";
92  
93  
94     /**
95      * Imports a gesture set.
96      * 
97      * @param file the XML file.
98      * @return a list of gesture sets.
99      */
100    public static GestureSet importGestureSet(InputStream inputStream) {
101       Document document = importDocument(inputStream);
102       Element setElement = document.getRootElement().getChild(
103             JdomGestureSet.ROOT_TAG);
104       return (setElement != null) ? JdomGestureSet.unmarshal(setElement) : null;
105    } // importGestureSet
106 
107 
108    public static GestureSet importGestureSet(File file) {
109       try {
110          return importGestureSet(new FileInputStream(file));
111       }
112       catch (FileNotFoundException e) {
113          LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
114          return null;
115       }
116 
117    } // importGestureSet
118 
119 
120    /**
121     * Exports a gesture set.
122     * 
123     * @param set the gesture set to be exported.
124     * @param file the XML file.
125     */
126    public static void exportGestureSet(GestureSet set, File file) {
127       final List<GestureSet> list = new ArrayList<GestureSet>();
128       list.add(set);
129       exportGestureSet(list, file);
130    } // exportGestureSet
131 
132 
133    /**
134     * Exports a Gesture Set as Input Stream
135     * @param set
136     * @return
137     */
138    public static InputStream exportGestureSetAsStream(GestureSet set) {
139       List<GestureSet> list = new ArrayList<GestureSet>();
140       list.add(set);
141       return exportGestureSetsAsStream(list);
142    }
143 
144 
145    /**
146     * Exports a list of Gesture Sets as InputStream
147     * @param sets
148     * @return
149     */
150    public static InputStream exportGestureSetsAsStream(List<GestureSet> sets) {
151       JdomDocument igestureDocument = new JdomDocument(ROOT_TAG);
152       Set<GestureClass> hashSet = new HashSet<GestureClass>();
153 
154       for (final GestureSet set : sets) {
155          for (final GestureClass gestureClass : set.getGestureClasses()) {
156             hashSet.add(gestureClass);
157          }
158       }
159 
160       for (final GestureClass gestureClass : hashSet) {
161          igestureDocument.attach(new JdomGestureClass(gestureClass));
162       }
163 
164       for (final GestureSet set : sets) {
165          igestureDocument.attach(new JdomGestureSet(set));
166       }
167 
168       return IOUtils.toInputStream(igestureDocument.toXml());
169    }
170 
171 
172    /**
173     * Exports a list of gesture sets.
174     * 
175     * @param sets the gesture sets to be exported.
176     * @param file the XML file.
177     */
178    public static void exportGestureSet(List<GestureSet> sets, File file) {
179       try {
180          FileOutputStream outputStream = new FileOutputStream(file);
181          IOUtils.copy(exportGestureSetsAsStream(sets), outputStream);
182          outputStream.close();
183       }
184       catch (FileNotFoundException e) {
185          LOGGER.log(Level.SEVERE,
186                "Could not export Gesture Sets. Export File not found.", e);
187       }
188       catch (IOException e) {
189          LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e);
190       }
191    } // exportGestureSet
192 
193 
194    /**
195     * Exports a test set.
196     * 
197     * @param testSet the test set to be exported.
198     * @param file the XML file.
199     */
200    public static void exportTestSet(TestSet testSet, File file) {
201       final List<TestSet> list = new ArrayList<TestSet>();
202       list.add(testSet);
203       exportTestSet(list, file);
204    } // exportTestSet
205 
206 
207    /**
208     * Exports a list of test sets.
209     * 
210     * @param testSetList the list of test sets to be exported.
211     * @param file the XML file.
212     */
213    public static void exportTestSet(List<TestSet> testSetList, File file) {
214       final JdomDocument igestureDocument = new JdomDocument(ROOT_TAG);
215 
216       for (final TestSet set : testSetList) {
217          igestureDocument.attach(new JdomTestSet(set));
218       }
219 
220       FileHandler.writeFile(file.getPath(), igestureDocument.toXml());
221    } // exportTestSet
222 
223 
224    /**
225     * Imports a list of test sets.
226     * 
227     * @param file the XML File
228     * @return a list of GestureSets
229     */
230    public static TestSet importTestSet(File file) {
231       try {
232          return importTestSet(new FileInputStream(file));
233       }
234       catch (FileNotFoundException e) {
235          LOGGER.log(Level.SEVERE, file.getName()
236                + " not found. Could not import Testsets.", e);
237       }
238 
239       return null;
240    } // importTestSet
241 
242 
243    /**
244     * Imports a list of test sets from an XML document.
245     * @param inputStream the input stream of the XML document
246     * @return a list of test sets
247     */
248    public static TestSet importTestSet(InputStream inputStream) {
249       Document document = importDocument(inputStream);
250       Element testSetElement = document.getRootElement().getChild(
251             JdomTestSet.ROOT_TAG);
252       return (testSetElement != null) ? JdomTestSet.unmarshal(testSetElement) : null;
253    }// importTestSet
254 
255 
256    /**
257     * Imports a configuration.
258     * 
259     * @param file the XML file
260     * @return the configuration.
261     */
262    public static Configuration importConfiguration(InputStream inputStream) {
263       Configuration configuration = new Configuration();
264       final Document document = importDocument(inputStream);
265       configuration = (Configuration)JdomConfiguration.unmarshal(document
266             .getRootElement());
267       return configuration;
268    } // importConfiguration
269 
270 
271    /**
272     * Imports a configuration
273     * @param file
274     * @return
275     */
276    public static Configuration importConfiguration(File file) {
277       try {
278          return importConfiguration(new FileInputStream(file));
279       }
280       catch (FileNotFoundException e) {
281          LOGGER.severe("Configuration File not found.");
282       }
283       return null;
284    } // importConfiguration
285 
286 
287    /**
288     * Exports a configuration.
289     * 
290     * @param configuration the configuration to be exported.
291     * @param file the XML file.
292     */
293    public static void exportConfiguration(Configuration configuration, File file) {
294       JdomDocument document = new JdomDocument(new JdomConfiguration(
295             configuration));
296       FileHandler.writeFile(file.getPath(), document.toXml());
297    } // exportConfiguration
298 
299 
300    /**
301     * Exports a Configuration as XML Stream
302     * @param configuration
303     * @return a Configuration as XML InputStream
304     */
305    public static InputStream exportConfigurationAsStream(
306          Configuration configuration) {
307       JdomDocument document = new JdomDocument(new JdomConfiguration(
308             configuration));
309       return IOUtils.toInputStream(document.toXml());
310    } // exportConfiguration
311 
312 
313    /**
314     * Exports a Test Set as XML Stream
315     * @param testSet
316     * @return a TestSet as XML InputStreamd
317     */
318    public static InputStream exportTestSetAsStream(TestSet testSet) {
319       JdomDocument document = new JdomDocument(TEST_SETS_TAG);
320       document.attach(new JdomTestSet(testSet));
321 
322       return IOUtils.toInputStream(document.toXml());
323    } // exportConfiguration
324 
325 
326    /**
327     * Exports a batch result set.
328     * 
329     * @param resultSet the batch result set to be exported
330     * @param file the XML file
331     */
332    public static void exportBatchResultSet(BatchResultSet resultSet, File file) {
333       FileHandler.writeFile(file.getPath(), XMLTool
334             .exportBatchResultSet(resultSet));
335    } // exportBatchResultSet
336 
337 
338    /**
339     * Exports a batch result set to its XML representation.
340     * 
341     * @param resultSet the batch result set to be exported.
342     * @return the string containing the XML representation.
343     */
344    public static String exportBatchResultSet(BatchResultSet resultSet) {
345       final JdomDocument document = new JdomDocument(new JdomBatchResultSet(
346             resultSet));
347       return document.toXml();
348    } // exportBatchResultSet
349 
350 
351    /**
352     * Imports an XML document.
353     * 
354     * @param file the XML file.
355     * @return the JDOM document.
356     */
357    public static Document importDocument(InputStream inputStream) {
358       Document document = null;
359 
360       try {
361          final SAXBuilder builder = new SAXBuilder(false);
362          builder.setFactory(new Factory());
363          builder.setIgnoringElementContentWhitespace(true);
364          final InputSource is = new InputSource(inputStream);
365          document = builder.build(is);
366       }
367       catch (final IOException e) {
368          LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
369       }
370       catch (final JDOMException e) {
371          LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
372       }
373 
374       return document;
375    } // importDocument
376 
377 
378    /**
379     * Imports an XML Document from a file.
380     * @param file
381     * @return
382     */
383    public static Document importDocument(File file) {
384       try {
385          return importDocument(new FileInputStream(file));
386       }
387       catch (FileNotFoundException e) {
388          LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
389          return null;
390       }
391 
392    } // importDocument
393 
394 
395    /**
396     * Imports an XML File and builds up the object tree. The result is a list of
397     * batch algorithm instances.
398     * 
399     * @param file the XML file to be imported.
400     * @return list of batch algorithm instances.
401     */
402    @SuppressWarnings("unchecked")
403    public static BatchProcessContainer importBatchProcessContainer(File file) {
404       final BatchProcessContainer container = new BatchProcessContainer();
405       final Document document = importDocument(file);
406 
407       for (final Element elem : (List<Element>)document.getRootElement()
408             .getChildren(JdomBatchAlgorithm.ROOT_TAG)) {
409          container.addAlgorithm(JdomBatchAlgorithm.unmarshal(elem));
410       }
411 
412       for (final Element set : (List<Element>)document.getRootElement()
413             .getChildren(JdomGestureSet.ROOT_TAG)) {
414          container.addGestureSet(JdomGestureSet.unmarshal(set));
415       }
416 
417       return container;
418    } // importBatchProcessContainer
419 
420 
421    /**
422     * Transforms an XML Document using XSLT
423     * @param xmlDocument the XML Document
424     * @param xslFile the XSL Document
425     * @return a String containing the transformed document.
426     * @throws TransformerException
427     * @throws TransformerConfigurationException
428     * @throws TransformerFactoryConfigurationError
429     */
430    public static String transform(String xmlDocument, String xslFile)
431          throws TransformerException, TransformerConfigurationException,
432          TransformerFactoryConfigurationError {
433       final StringReader xmlSR = new StringReader(xmlDocument);
434       final StreamSource xmlIn = new StreamSource(xmlSR);
435       final StringWriter xmlSW = new StringWriter();
436       final StreamResult xmlOut = new StreamResult(xmlSW);
437       FileReader xslSR = null;
438 
439       try {
440          xslSR = new FileReader(new File(xslFile));
441       }
442       catch (final FileNotFoundException e) {
443          LOGGER.log(Level.SEVERE, Constant.EMPTY_STRING, e);
444       }
445 
446       final TransformerFactory tFactory = TransformerFactory.newInstance();
447       final Transformer transformer = tFactory.newTransformer(new StreamSource(
448             xslSR));
449       transformer.transform(xmlIn, xmlOut);
450 
451       return xmlSW.toString();
452    } // transform
453 
454 
455    /**
456     * XSL transformation.
457     * @param xmlDocument XML document (String)
458     * @param xsl XSL document (InputStream)
459     * @return the transformed XML document
460     * @throws TransformerException
461     * @throws TransformerConfigurationException
462     * @throws TransformerFactoryConfigurationError
463     */
464    public static String transform(String xmlDocument, InputStream xsl)
465          throws TransformerException, TransformerConfigurationException,
466          TransformerFactoryConfigurationError {
467       final StringReader xmlSR = new StringReader(xmlDocument);
468       final StreamSource xmlIn = new StreamSource(xmlSR);
469       
470       final StringWriter xmlSW = new StringWriter();
471       final StreamResult xmlOut = new StreamResult(xmlSW);
472       
473       StreamSource xslSR = new StreamSource(xsl);
474       final TransformerFactory tFactory = TransformerFactory.newInstance();
475       final Transformer transformer = tFactory.newTransformer(xslSR);
476       transformer.transform(xmlIn, xmlOut);
477       return xmlSW.toString();
478    } // transform
479 
480 }