source: MDService2/branches/MDService_simple3/src/eu/clarin/cmdi/mdservice/internal/Utils.java @ 1613

Last change on this file since 1613 was 1613, checked in by vronk, 13 years ago

various small changes, clean up code

File size: 10.5 KB
Line 
1package eu.clarin.cmdi.mdservice.internal;
2
3import java.io.BufferedReader;
4import java.io.ByteArrayInputStream;
5import java.io.ByteArrayOutputStream;
6import java.io.File;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.InputStreamReader;
11import java.io.OutputStream;
12import java.util.Properties;
13
14import javax.xml.parsers.DocumentBuilder;
15import javax.xml.parsers.DocumentBuilderFactory;
16import javax.xml.parsers.FactoryConfigurationError;
17import javax.xml.parsers.ParserConfigurationException;
18import javax.xml.transform.Result;
19import javax.xml.transform.Source;
20import javax.xml.transform.TransformerConfigurationException;
21import javax.xml.transform.TransformerException;
22import javax.xml.transform.TransformerFactory;
23import javax.xml.transform.TransformerFactoryConfigurationError;
24import javax.xml.transform.dom.DOMSource;
25import javax.xml.transform.stream.StreamResult;
26import javax.xml.xpath.XPath;
27import javax.xml.xpath.XPathConstants;
28import javax.xml.xpath.XPathExpression;
29import javax.xml.xpath.XPathExpressionException;
30import javax.xml.xpath.XPathFactory;
31
32import org.w3c.dom.Document;
33import org.w3c.dom.Element;
34import org.w3c.dom.Node;
35import org.xml.sax.SAXException;
36
37import net.sf.json.JSON;
38import net.sf.json.JSONSerializer;
39import net.sf.json.xml.XMLSerializer;
40
41import org.apache.log4j.Logger;
42
43/**
44 * Helper class provides reading of configuration properties and contains
45 * all other helper and conversion functions.
46 *
47 * @author
48 *
49 */
50
51public class Utils {
52
53        public static Logger log = Logger.getLogger("Utils");
54
55        /**
56         * Constant filename of application properties file.
57         */
58        private static String config_path = "mdservice.properties";
59        private static Properties  config;     
60
61
62        /**
63         * Loads application configuration properties from filename in class constant config_path.
64         */
65        public static void loadConfig() {
66                loadConfig(config_path);
67        }
68
69        /**
70         * Loads application configuration properties from properties file configPath.
71         *
72         * @param configPath - pathname string of java properties file.
73         */
74        public static void loadConfig(String configPath) {
75               
76                System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
77                InputStream config_file;
78                 
79                try {                   
80                        config_file = Utils.class.getClassLoader().getResourceAsStream(configPath);
81                        if (config_file == null) {
82                            log.error("CONFIGURATION ERROR: Properties file not found!");
83                        } else {
84                                log.debug("Reading configuration from: " + Utils.class.getClassLoader().getResource(configPath));
85                                config = new Properties();
86                                config.load(config_file);       
87                        }
88                       
89                } catch (Exception e) {
90                        log.error("CONFIGURATION LOAD ERROR: " + e.getLocalizedMessage());
91                } 
92        }
93       
94        /**
95         * Returns application configuration properties.
96         *
97         * @return
98         */
99        public static Properties getConfig() {
100                if (config==null)  {
101                        loadConfig(config_path);
102                }
103                return config;
104        }
105
106        /**
107         * convenience function to get a config property value
108         * @param key
109         * @return
110         */
111                public static String getConfig(String key) {
112                                return getConfig().getProperty(key);           
113                }
114               
115       
116        /**
117         * Creates error message string from exception data.
118         *
119         * @param e - The exception object.
120         * @return
121         */
122        public static String errorMessage(Exception e){
123                String message = e.getStackTrace()[0].getFileName() + ":" + String.valueOf(e.getStackTrace()[0].getLineNumber()) + "  "+ e.getClass() + ": " + e.getLocalizedMessage();
124               
125                return message;
126        }
127       
128        /**
129         * Creates error message string from error data.
130         *
131         * @param e - The error object.
132         * @return
133         */
134        public static String errorMessage(Error e){
135                String message = e.getStackTrace()[0].getFileName() + ":" + String.valueOf(e.getStackTrace()[0].getLineNumber()) + "  "+ e.getClass() + ": " + e.getLocalizedMessage();
136               
137                return message;
138        }
139       
140        /**
141         * Loads data from filename.
142         *
143         * @param path
144         * @return
145         */
146        public static InputStream load2Stream (String path) {
147               
148                InputStream file=null;
149                 
150                try {                   
151                        file = Utils.class.getClassLoader().getResourceAsStream(path);
152                        if (file == null) {
153                            log.error("File not found!: " + path);
154                        } else {
155                                log.debug("Reading in: " + Utils.class.getClassLoader().getResource(path));
156                        }
157                }   catch (Exception e) {
158                        log.error(Utils.errorMessage(e));
159                } 
160               
161                return file;
162        }
163       
164        /**
165         * Writes data from stream to file.
166         *
167         * @param path - The filename, where the data will be write.
168         * @param in - The InputStream to be written into file.
169         */
170        public static void write2File (String path, InputStream in) {   
171        try
172            {
173                        File f=new File(path);     
174                    OutputStream out=new FileOutputStream(f);
175                    copyStreams(in,out);           
176                    out.close();           
177            }
178            catch (Exception e){
179                log.error(Utils.errorMessage(e));
180            }
181        }
182
183        /**
184         * Loads data from file to XMLDocument.
185         *
186         * @param path
187         * @return
188         */
189        public static Document load2Document(String path)
190        //public static Document readFSLS(String infile)
191        {
192                Document document = null;
193                try {
194                    DocumentBuilderFactory factory = 
195                    DocumentBuilderFactory.newInstance();
196                    DocumentBuilder builder = factory.newDocumentBuilder();
197                    InputStream doc_is = load2Stream(path); 
198                    document = builder.parse(doc_is);               
199                   
200                }
201                catch (FactoryConfigurationError e) {
202                    // unable to get a document builder factory
203                        log.error(Utils.errorMessage(e));
204                } 
205                catch (ParserConfigurationException e) {
206                    // parser was unable to be configured
207                        log.error(Utils.errorMessage(e));                       
208                }
209                catch (IOException e) {
210                    // i/o error
211                        log.error(Utils.errorMessage(e));                       
212                } catch (SAXException e) {
213                        log.error(Utils.errorMessage(e));
214                }
215               
216                return document;
217        }
218
219        /**
220         * Copies inputstream in to outputstream out.
221         *
222         * @param in
223         * @param out
224         * @throws IOException
225         * @throws InterruptedException
226         */
227        public static void copyStreams (InputStream in, OutputStream out) throws IOException, InterruptedException {           
228               
229                byte[] buffer = new byte[1024];
230                int len = in.read(buffer);
231                while (len != -1) {
232                    out.write(buffer, 0, len);
233                    len = in.read(buffer);
234                    if (Thread.interrupted()) {
235                        throw new InterruptedException();
236                    }
237                }
238        }       
239
240        /**
241         * Converts stream to XML document.
242         *
243         * @param is
244         * @return
245         */
246        public static Document stream2Document(InputStream is){
247        //public static Document getDocument(InputStream is){
248                Document doc = null;
249                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
250        DocumentBuilder docBuilder;
251                try {
252                        docBuilder = docFactory.newDocumentBuilder();
253                        doc = docBuilder.parse(is);
254               
255                }catch (FactoryConfigurationError e) {
256                            // unable to get a document builder factory
257                                log.error(Utils.errorMessage(e));
258                        } 
259                        catch (ParserConfigurationException e) {
260                            // parser was unable to be configured
261                                log.error(Utils.errorMessage(e));                       
262                        }
263                        catch (IOException e) {
264                            // i/o error
265                                log.error(Utils.errorMessage(e));                       
266                        } catch (SAXException e) {
267                                log.error(Utils.errorMessage(e));
268                        }
269                       
270                return doc;
271        }
272
273        /**
274         * Returns string value  from XML stream  according to XPath expression.
275         *
276         * @param is
277         * @param expression
278         * @return
279         */
280        public static String getXPathData(InputStream is, String expression){
281        //public static String getDocumentData(InputStream is, String expression){
282                String data = "";
283       
284                XPathFactory factory = XPathFactory.newInstance(); 
285            XPath xpath = factory.newXPath(); 
286            XPathExpression expr;
287                try {
288                        expr = xpath.compile(expression);
289                        data = (String) expr.evaluate(stream2Document(is), XPathConstants.STRING);
290                } catch (XPathExpressionException e) {
291                        log.error(Utils.errorMessage(e));       
292                }
293                       
294                return data;
295               
296        }
297       
298        /**
299         * Creates simple XML document with given rootlement name.
300         *
301         * @param rootelemname
302         * @return
303         */
304        public static Document createDocument(String rootelemname){
305                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
306        DocumentBuilder docBuilder;
307        Document doc = null;
308                try {
309                        docBuilder = docFactory.newDocumentBuilder();
310                        doc = docBuilder.newDocument();
311                        // append root tag <index >
312                        Element root = (Element) doc.createElement(rootelemname);
313                        doc.appendChild(root);
314                } catch (Exception e){
315                        log.error(Utils.errorMessage(e));       
316                }
317                return doc;
318        }
319       
320        /**
321         * Converts stream to string.
322         *
323         * @param is
324         * @return
325         */
326        public  static String streamToString(InputStream is) { 
327               
328                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
329                StringBuilder sb = new StringBuilder(); 
330                String line = null; 
331               
332                try {
333                        while ((line = reader.readLine()) != null) { 
334                                         sb.append(line + "\n"); 
335                        }
336                } catch (IOException e) {
337                        log.error(Utils.errorMessage(e));
338                }  finally {
339                        try {
340                                is.close();
341                        } catch (IOException e) {
342                                log.error(Utils.errorMessage(e));
343                        }
344                        try {
345                                is.reset();
346                        } catch (IOException e) {
347                                log.error(Utils.errorMessage(e));
348                        }
349                }
350                 
351               
352                return sb.toString(); 
353        }
354
355
356        /**
357         * Converts XML document to stream.
358         *
359         * @param node
360         * @return
361         * @throws TransformerConfigurationException
362         * @throws TransformerException
363         * @throws TransformerFactoryConfigurationError
364         */
365        public static InputStream document2Stream(Node node) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{
366               
367                InputStream is = null;
368                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
369                Source xmlSource;
370               
371                try{
372                        //if (node == null) {
373                        //      xmlSource = new DOMSource(workspace_doc);
374                        //} else {
375                                xmlSource = new DOMSource(node);
376                        //}
377                        Result outputTarget = new StreamResult(outputStream); 
378                        TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); 
379                        is = new ByteArrayInputStream(outputStream.toByteArray()); 
380
381                } catch (Exception e){
382                        log.error(Utils.errorMessage(e));
383                }
384               
385                return is;
386        }
387       
388        public static Document append2Document(Document sourcedoc,String parenttagname, Document appenddoc){
389
390                Node r_element=  sourcedoc.getElementsByTagName(parenttagname).item(0); 
391                Node d_element = appenddoc.getElementsByTagName("diagnostics").item(0);
392                sourcedoc.adoptNode(d_element);
393                r_element.appendChild(d_element);
394               
395                return sourcedoc;
396        }
397        public static void testJSON() {
398                String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
399                //Query q = new Query("dc.title=dino or dinosaur", Query.RECORDSET);
400        JSON json = JSONSerializer.toJSON( str); 
401        XMLSerializer xmlSerializer = new XMLSerializer(); 
402        String xml = xmlSerializer.write( json ); 
403        log.debug(xml);
404        }
405
406}
407
408
Note: See TracBrowser for help on using the repository browser.