001    /*
002     * Common usable utilities
003     *
004     * Copyright (c) 2006 Petr Hadraba <hadrabap@gmail.com>
005     *
006     * Author: Petr Hadraba
007     *
008     * --
009     *
010     * XML Utilities
011     */
012    
013    package global.sandbox.xmlutilities.demo;
014    
015    import global.sandbox.xmlutilities.XmlTools;
016    import global.sandbox.xmlutilities.XmlUtilitiesException;
017    import java.io.IOException;
018    import java.io.InputStream;
019    import javax.xml.transform.Source;
020    import org.w3c.dom.Document;
021    
022    public class XmlLoading {
023    
024        public static Document loadXmlFromResourceAsDocument(Class<?> clazz, String name) throws NoSuchResourceException, XmlLoadingException {
025            InputStream is = clazz.getResourceAsStream(name);
026    
027            if (is == null) {
028                throw new NoSuchResourceException(name);
029            }
030    
031            try {
032                return XmlTools.loadDocumentFromStream(is);
033            } catch (XmlUtilitiesException ex) {
034                throw new XmlLoadingException(ex);
035            } finally {
036                try {
037                    is.close();
038                } catch (IOException ex) {
039                    throw new XmlLoadingException(ex);
040                }
041            }
042        }
043    
044        public static Source loadXmlFromResourceAsSource(Class<?> clazz, String name) throws NoSuchResourceException, XmlLoadingException {
045            return XmlTools.documentToDomSource(loadXmlFromResourceAsDocument(clazz, name));
046        }
047    
048        public static Document loadXmlFromResourceAsDocument12(Class<?> clazz, String name) throws XmlLoadingException {
049            try {
050                return XmlTools.loadDocumentFromResource(name, clazz);
051            } catch (XmlUtilitiesException ex) {
052                throw new XmlLoadingException(ex);
053            }
054        }
055    
056        public static Source loadXmlFromResourceAsSource12(Class<?> clazz, String name) throws XmlLoadingException {
057            return XmlTools.documentToDomSource(loadXmlFromResourceAsDocument12(clazz, name));
058        }
059    
060        public static class NoSuchResourceException extends Exception {
061    
062            private static final long serialVersionUID = 1L;
063    
064            public NoSuchResourceException(String resourceName) {
065                super(resourceName);
066            }
067    
068        }
069    
070        public static class XmlLoadingException extends Exception {
071    
072            private static final long serialVersionUID = 1L;
073    
074            public XmlLoadingException(Throwable cause) {
075                super(cause);
076            }
077    
078        }
079    
080    }