source: MDUTILS/src/eu/clarin/cmdi/mdservice/internal/Utils.java @ 1649

Last change on this file since 1649 was 1649, checked in by vronk, 12 years ago

correcting config-loading / -usage

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