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

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

minor

File size: 11.9 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        public static Properties getConfig() {
132                if (config==null)  {
133                        loadConfig(config_path);
134                }
135                return config;
136        }
137        public static Properties getAppConfig(String appname){
138                return config_hashtable.get(appname);
139        }
140/**
141 * convenience function to get a config property value
142 * @param key
143 * @return
144 */
145        public static String getConfig(String key) {
146       
147                        //return getConfig().getProperty(key);
148                       
149                        Enumeration keys = config_hashtable.keys();
150                while (keys.hasMoreElements()) {
151                String _key = (String) keys.nextElement();
152                if (((Properties)config_hashtable.get(_key)).getProperty(key) != null){
153                        return ((Properties)config_hashtable.get(_key)).getProperty(key);
154                }
155                }
156                        return null;
157                                       
158        }
159       
160       
161        /**
162         * Creates error message string from exception data.
163         *
164         * @param e - The exception object.
165         * @return
166         */
167        public static String errorMessage(Exception e){
168                String message = e.getStackTrace()[0].getFileName() + ":" + String.valueOf(e.getStackTrace()[0].getLineNumber()) + "  "+ e.getClass() + ": " + e.getLocalizedMessage();
169               
170                return message;
171        }
172       
173        /**
174         * Creates error message string from error data.
175         *
176         * @param e - The error object.
177         * @return
178         */
179        public static String errorMessage(Error e){
180                String message = e.getStackTrace()[0].getFileName() + ":" + String.valueOf(e.getStackTrace()[0].getLineNumber()) + "  "+ e.getClass() + ": " + e.getLocalizedMessage();
181               
182                return message;
183        }
184       
185        /**
186         * Loads data from filename.
187         *
188         * @param path
189         * @return
190         */
191        public static InputStream load2Stream (String path) {   
192                return load2Stream(path,Utils.class.getClassLoader());
193        }
194       
195        public static InputStream load2Stream (String path, ClassLoader loader) {
196               
197                InputStream file=null;
198                if (loader == null){
199                        loader = Utils.class.getClassLoader();
200                }
201                try {                   
202                        file = loader.getResourceAsStream(path);
203                        if (file == null) {
204                            log.error("File not found!: " + path);
205                        } else {
206                                log.debug("Reading in: " + loader.getResource(path));
207                        }
208                }   catch (Exception e) {
209                        log.error(Utils.errorMessage(e));
210                } 
211               
212                return file;
213        }
214       
215       
216        /**
217         * Writes data from stream to file.
218         *
219         * @param path - The filename, where the data will be write.
220         * @param in - The InputStream to be written into file.
221         */
222        public static File write2File (String path, InputStream in) {   
223        try
224            {
225                        File f=new File(path);     
226                    OutputStream out=new FileOutputStream(f);
227                    copyStreams(in,out);           
228                    out.close();           
229                    return f;
230            }
231            catch (Exception e){
232                log.error(Utils.errorMessage(e));
233            }
234
235            return null;
236           
237        }
238
239        /**
240         * Loads data from file to XMLDocument.
241         *
242         * @param path
243         * @return
244         */
245        public static Document load2Document(String path)
246        //public static Document readFSLS(String infile)
247        {
248                Document document = null;
249                try {
250                    DocumentBuilderFactory factory = 
251                    DocumentBuilderFactory.newInstance();
252                    DocumentBuilder builder = factory.newDocumentBuilder();
253                    InputStream doc_is = load2Stream(path); 
254                    document = builder.parse(doc_is);               
255                   
256                }
257                catch (FactoryConfigurationError e) {
258                    // unable to get a document builder factory
259                        log.error(Utils.errorMessage(e));
260                } 
261                catch (ParserConfigurationException e) {
262                    // parser was unable to be configured
263                        log.error(Utils.errorMessage(e));                       
264                }
265                catch (IOException e) {
266                    // i/o error
267                        log.error(Utils.errorMessage(e));                       
268                } catch (SAXException e) {
269                        log.error(Utils.errorMessage(e));
270                }
271               
272                return document;
273        }
274
275        /**
276         * Copies inputstream in to outputstream out.
277         *
278         * @param in
279         * @param out
280         * @throws IOException
281         * @throws InterruptedException
282         */
283        public static void copyStreams (InputStream in, OutputStream out) throws IOException, InterruptedException {           
284               
285                byte[] buffer = new byte[1024];
286                int len = in.read(buffer);
287                while (len != -1) {
288                    out.write(buffer, 0, len);
289                    len = in.read(buffer);
290                    if (Thread.interrupted()) {
291                        throw new InterruptedException();
292                    }
293                }
294        }       
295
296        /**
297         * Converts stream to XML document.
298         *
299         * @param is
300         * @return
301         */
302        public static Document stream2Document(InputStream is){
303        //public static Document getDocument(InputStream is){
304                Document doc = null;
305                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
306        DocumentBuilder docBuilder;
307                try {
308                        docBuilder = docFactory.newDocumentBuilder();
309                        doc = docBuilder.parse(is);
310               
311                }catch (FactoryConfigurationError e) {
312                            // unable to get a document builder factory
313                                log.error(Utils.errorMessage(e));
314                        } 
315                        catch (ParserConfigurationException e) {
316                            // parser was unable to be configured
317                                log.error(Utils.errorMessage(e));                       
318                        }
319                        catch (IOException e) {
320                            // i/o error
321                                log.error(Utils.errorMessage(e));                       
322                        } catch (SAXException e) {
323                                log.error(Utils.errorMessage(e));
324                        }
325                       
326                return doc;
327        }
328
329        /**
330         * Returns string value  from XML stream  according to XPath expression.
331         *
332         * @param is
333         * @param expression
334         * @return
335         */
336        public static String getXPathData(InputStream is, String expression){
337        //public static String getDocumentData(InputStream is, String expression){
338                String data = "";
339       
340                XPathFactory factory = XPathFactory.newInstance(); 
341            XPath xpath = factory.newXPath(); 
342            XPathExpression expr;
343                try {
344                        expr = xpath.compile(expression);
345                        data = (String) expr.evaluate(stream2Document(is), XPathConstants.STRING);
346                } catch (XPathExpressionException e) {
347                        log.error(Utils.errorMessage(e));       
348                }
349                       
350                return data;
351               
352        }
353       
354        /**
355         * Creates simple XML document with given rootlement name.
356         *
357         * @param rootelemname
358         * @return
359         */
360        public static Document createDocument(String rootelemname){
361                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
362        DocumentBuilder docBuilder;
363        Document doc = null;
364                try {
365                        docBuilder = docFactory.newDocumentBuilder();
366                        doc = docBuilder.newDocument();
367                        // append root tag <index >
368                        Element root = (Element) doc.createElement(rootelemname);
369                        doc.appendChild(root);
370                } catch (Exception e){
371                        log.error(Utils.errorMessage(e));       
372                }
373                return doc;
374        }
375       
376        /**
377         * Converts stream to string.
378         *
379         * @param is
380         * @return
381         */
382        public  static String streamToString(InputStream is) { 
383               
384                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
385                StringBuilder sb = new StringBuilder(); 
386                String line = null; 
387               
388                try {
389                        while ((line = reader.readLine()) != null) { 
390                                         sb.append(line + "\n"); 
391                        }
392                } catch (IOException e) {
393                        log.error(Utils.errorMessage(e));
394                }  finally {
395                        try {
396                                is.close();
397                        } catch (IOException e) {
398                                log.error(Utils.errorMessage(e));
399                        }
400                        try {
401                                is.reset();
402                        } catch (IOException e) {
403                                log.error(Utils.errorMessage(e));
404                        }
405                }
406                 
407               
408                return sb.toString(); 
409        }
410
411
412        /**
413         * Converts XML document to stream.
414         *
415         * @param node
416         * @return
417         * @throws TransformerConfigurationException
418         * @throws TransformerException
419         * @throws TransformerFactoryConfigurationError
420         */
421        public static InputStream document2Stream(Node node) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError{
422               
423                InputStream is = null;
424                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
425                Source xmlSource;
426               
427                try{
428                        //if (node == null) {
429                        //      xmlSource = new DOMSource(workspace_doc);
430                        //} else {
431                                xmlSource = new DOMSource(node);
432                        //}
433                        Result outputTarget = new StreamResult(outputStream); 
434                        TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget); 
435                        is = new ByteArrayInputStream(outputStream.toByteArray()); 
436
437                } catch (Exception e){
438                        log.error(Utils.errorMessage(e));
439                }
440               
441                return is;
442        }
443       
444        public static Document append2Document(Document sourcedoc,String parenttagname, Document appenddoc){
445
446                Node r_element=  sourcedoc.getElementsByTagName(parenttagname).item(0); 
447                Node d_element = appenddoc.getElementsByTagName("diagnostics").item(0);
448                sourcedoc.adoptNode(d_element);
449                r_element.appendChild(d_element);
450               
451                return sourcedoc;
452        }
453        public static void testJSON() {
454                String str = "{'name':'JSON','integer':1,'double':2.0,'boolean':true,'nested':{'id':42},'array':[1,2,3]}";
455                //Query q = new Query("dc.title=dino or dinosaur", Query.RECORDSET);
456        JSON json = JSONSerializer.toJSON( str); 
457        XMLSerializer xmlSerializer = new XMLSerializer(); 
458        String xml = xmlSerializer.write( json ); 
459        log.debug(xml);
460        }
461
462}
463
464
Note: See TracBrowser for help on using the repository browser.