View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 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.module.model.reader;
35  
36  import info.magnolia.cms.util.ClasspathResourcesUtil;
37  import info.magnolia.module.ModuleManagementException;
38  import info.magnolia.module.model.ModuleDefinition;
39  import info.magnolia.module.model.Version;
40  import org.apache.commons.betwixt.io.BeanReader;
41  import org.apache.commons.io.IOUtils;
42  import org.jdom.DocType;
43  import org.jdom.Document;
44  import org.jdom.JDOMException;
45  import org.jdom.input.SAXBuilder;
46  import org.jdom.output.XMLOutputter;
47  import org.xml.sax.SAXException;
48  import org.xml.sax.SAXParseException;
49  
50  import java.beans.IntrospectionException;
51  import java.io.IOException;
52  import java.io.InputStreamReader;
53  import java.io.Reader;
54  import java.io.StringReader;
55  import java.io.StringWriter;
56  import java.net.URL;
57  import java.util.HashMap;
58  import java.util.Map;
59  import java.util.regex.Matcher;
60  import java.util.regex.Pattern;
61  import javax.inject.Singleton;
62  
63  /**
64   * This implementation of ModuleDefinitionReader uses Betwixt to read and convert module
65   * descriptor files.
66   *
67   * @author gjoseph
68   * @version $Revision: $ ($Author: $)
69   */
70  @Singleton
71  public class BetwixtModuleDefinitionReader implements ModuleDefinitionReader {
72      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BetwixtModuleDefinitionReader.class);
73  
74      private static final String DTD = "/info/magnolia/module/model/module.dtd";
75  
76      private final String dtdUrl;
77      private final BeanReader beanReader;
78  
79      public BetwixtModuleDefinitionReader() {
80          final URL dtd = getClass().getResource(DTD);
81          if (dtd == null) {
82              throw new IllegalStateException("DTD not found at " + DTD);
83          }
84          dtdUrl = dtd.toString();
85  
86          final BetwixtBindingStrategy bindingStrategy = new BetwixtBindingStrategy();
87          bindingStrategy.registerConverter(Version.class, new VersionConverter());
88  
89          beanReader = new BeanReader();
90          try {
91              beanReader.getXMLIntrospector().getConfiguration().setTypeBindingStrategy(bindingStrategy);
92              beanReader.setValidating(true);
93              beanReader.setErrorHandler(new ErrorHandler());
94              beanReader.registerBeanClass(ModuleDefinition.class);
95          } catch (IntrospectionException e) {
96              throw new RuntimeException(e); // TODO
97          }
98      }
99  
100     @Override
101     public Map<String, ModuleDefinition> readAll() throws ModuleManagementException {
102         final Map<String, ModuleDefinition> moduleDefinitions = new HashMap<String, ModuleDefinition>();
103 
104         final String[] defResources = findModuleDescriptors();
105 
106         for (final String resourcePath : defResources) {
107             log.debug("Parsing module file {}", resourcePath);
108             final ModuleDefinition def = readFromResource(resourcePath);
109             moduleDefinitions.put(def.getName(), def);
110         }
111         return moduleDefinitions;
112     }
113 
114     protected String[] findModuleDescriptors() {
115         return ClasspathResourcesUtil.findResources(new ClasspathResourcesUtil.Filter() {
116             @Override
117             public boolean accept(String name) {
118                 return name.startsWith("/META-INF/magnolia/") && name.endsWith(".xml");
119             }
120         });
121     }
122 
123     @Override
124     public ModuleDefinition read(Reader in) throws ModuleManagementException {
125         try {
126             final Reader replacedDtd = replaceDtd(in);
127             return (ModuleDefinition) beanReader.parse(replacedDtd);
128         } catch (IOException e) {
129             throw new ModuleManagementException("Can't read module definition file: " + e.getMessage(), e);
130         } catch (SAXException e) {
131             throw new ModuleManagementException(e.getMessage(), e);
132         }
133     }
134 
135     @Override
136     public ModuleDefinition readFromResource(String resourcePath) throws ModuleManagementException {
137         final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(resourcePath));
138         try {
139             return read(reader);
140         } finally {
141             try {
142                 reader.close();
143             } catch (IOException e) {
144                 log.error("Can't close input for " + resourcePath);
145             }
146         }
147     }
148 
149     /**
150      * @deprecated TODO very ugly hack to force documents to be validated against OUR DTD.
151      * We could use an EntityResolver, but it seems that with SAX, the documents will only be
152      * validated if they original have a doctype declaration.
153      * We could also use http://doctypechanger.sourceforge.net/
154      * ... or switch to XmlSchema.
155      */
156     private Reader replaceDtd(Reader reader) throws IOException {
157         String content = IOUtils.toString(reader);
158 
159         // remove doctype
160         Pattern pattern = Pattern.compile("<!DOCTYPE .*>");
161         Matcher matcher = pattern.matcher(content);
162         content = matcher.replaceFirst("");
163 
164         // set doctype to the dtd
165         try {
166             Document doc = new SAXBuilder().build(new StringReader(content));
167             doc.setDocType(new DocType("module", dtdUrl));
168             // write the xml to the string
169             XMLOutputter outputter = new XMLOutputter();
170             StringWriter writer = new StringWriter();
171             outputter.output(doc, writer);
172             final String replacedDtd = writer.toString();
173             return new StringReader(replacedDtd);
174         } catch (JDOMException e) {
175             throw new RuntimeException(e); // TODO
176         }
177     }
178 
179     private static class ErrorHandler implements org.xml.sax.ErrorHandler {
180         // TODO -- pass source (url, content, ...) for each parse ?
181         @Override
182         public void warning(SAXParseException e) throws SAXException {
183             log.warn("Warning on module definition " + getSaxParseExceptionMessage(e));
184         }
185 
186         @Override
187         public void error(SAXParseException e) throws SAXException {
188             throw new SAXException("Invalid module definition file, error " + getSaxParseExceptionMessage(e), e);
189         }
190 
191         @Override
192         public void fatalError(SAXParseException e) throws SAXException {
193             throw new SAXException("Invalid module definition file, fatal error " + getSaxParseExceptionMessage(e), e);
194         }
195     }
196 
197     private static String getSaxParseExceptionMessage(SAXParseException e) {
198         return "at line " + e.getLineNumber() + " column " + e.getColumnNumber() + ": " + e.getMessage();
199     }
200 }