View Javadoc

1   /**
2    * This file Copyright (c) 2011-2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.objectfactory.configuration;
35  
36  import java.beans.IntrospectionException;
37  import java.io.IOException;
38  import java.io.InputStreamReader;
39  import java.io.Reader;
40  import java.io.StringReader;
41  import java.io.StringWriter;
42  import java.net.URL;
43  import java.util.ArrayList;
44  import java.util.List;
45  import java.util.regex.Matcher;
46  import java.util.regex.Pattern;
47  
48  import org.apache.commons.betwixt.io.BeanReader;
49  import org.apache.commons.io.IOUtils;
50  import org.jdom.DocType;
51  import org.jdom.Document;
52  import org.jdom.JDOMException;
53  import org.jdom.input.SAXBuilder;
54  import org.jdom.output.XMLOutputter;
55  import org.xml.sax.SAXException;
56  import org.xml.sax.SAXParseException;
57  
58  import info.magnolia.module.model.ComponentsDefinition;
59  
60  /**
61   * Reads components defined in xml.
62   *
63   * @version $Id$
64   * @see ComponentsDefinition
65   */
66  public class ComponentConfigurationReader {
67  
68      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ComponentConfigurationReader.class);
69  
70      private static final String DTD = "/info/magnolia/module/model/components.dtd";
71  
72      private final String dtdUrl;
73      private final BeanReader beanReader;
74  
75      public ComponentConfigurationReader() {
76          final URL dtd = getClass().getResource(DTD);
77          if (dtd == null) {
78              throw new ComponentConfigurationException("DTD not found at " + DTD);
79          }
80          dtdUrl = dtd.toString();
81  
82          beanReader = new BeanReader();
83          try {
84              beanReader.setValidating(true);
85              beanReader.setErrorHandler(new ErrorHandler());
86              beanReader.registerBeanClass(ComponentsDefinition.class);
87          } catch (IntrospectionException e) {
88              throw new ComponentConfigurationException(e);
89          }
90      }
91  
92      public List<ComponentsDefinition> readAll(List<String> resourcePaths) {
93          List<ComponentsDefinition> componentsDefinitions = new ArrayList<ComponentsDefinition>();
94          for (String resourcePath : resourcePaths) {
95              log.debug("Parsing components file {}", resourcePath);
96              ComponentsDefinition componentsDefinition = readFromResource(resourcePath);
97              componentsDefinitions.add(componentsDefinition);
98          }
99          return componentsDefinitions;
100     }
101 
102     public ComponentsDefinition read(Reader in) {
103         try {
104             final Reader replacedDtd = replaceDtd(in);
105             return (ComponentsDefinition) beanReader.parse(replacedDtd);
106         } catch (IOException e) {
107             throw new ComponentConfigurationException("Can't read components definition file: " + e.getMessage(), e);
108         } catch (SAXException e) {
109             throw new ComponentConfigurationException(e.getMessage(), e);
110         }
111     }
112 
113     public ComponentsDefinition readFromResource(String resourcePath) {
114         final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath));
115         try {
116             return read(reader);
117         } finally {
118             try {
119                 reader.close();
120             } catch (IOException e) {
121                 log.error("Can't close input for " + resourcePath);
122             }
123         }
124     }
125 
126     /**
127      * @deprecated TODO very ugly hack to force documents to be validated against OUR DTD.
128      *             We could use an EntityResolver, but it seems that with SAX, the documents will only be
129      *             validated if they original have a doctype declaration.
130      *             We could also use http://doctypechanger.sourceforge.net/
131      *             ... or switch to XmlSchema.
132      */
133     private Reader replaceDtd(Reader reader) throws IOException {
134         String content = IOUtils.toString(reader);
135 
136         // remove doctype
137         Pattern pattern = Pattern.compile("<!DOCTYPE .*>");
138         Matcher matcher = pattern.matcher(content);
139         content = matcher.replaceFirst("");
140 
141         // set doctype to the dtd
142         try {
143             Document doc = new SAXBuilder().build(new StringReader(content));
144             doc.setDocType(new DocType("components", dtdUrl));
145             // write the xml to the string
146             XMLOutputter outputter = new XMLOutputter();
147             StringWriter writer = new StringWriter();
148             outputter.output(doc, writer);
149             final String replacedDtd = writer.toString();
150             return new StringReader(replacedDtd);
151         } catch (JDOMException e) {
152             throw new ComponentConfigurationException(e);
153         }
154     }
155 
156     private static class ErrorHandler implements org.xml.sax.ErrorHandler {
157 
158         @Override
159         public void warning(SAXParseException e) throws SAXException {
160             log.warn("Warning on components definition " + getSaxParseExceptionMessage(e));
161         }
162 
163         @Override
164         public void error(SAXParseException e) throws SAXException {
165             throw new SAXException("Invalid components definition file, error " + getSaxParseExceptionMessage(e), e);
166         }
167 
168         @Override
169         public void fatalError(SAXParseException e) throws SAXException {
170             throw new SAXException("Invalid components definition file, fatal error " + getSaxParseExceptionMessage(e), e);
171         }
172     }
173 
174     private static String getSaxParseExceptionMessage(SAXParseException e) {
175         return "at line " + e.getLineNumber() + " column " + e.getColumnNumber() + ": " + e.getMessage();
176     }
177 }