View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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.cms.util;
35  
36  import info.magnolia.cms.core.Path;
37  import org.apache.commons.collections.CollectionUtils;
38  import org.apache.commons.collections.Transformer;
39  import org.jdom.Document;
40  import org.jdom.Element;
41  import org.jdom.JDOMException;
42  import org.jdom.input.SAXBuilder;
43  import org.jdom.xpath.XPath;
44  
45  import java.io.File;
46  import java.io.IOException;
47  import java.io.InputStream;
48  import java.util.ArrayList;
49  import java.util.Collection;
50  import java.util.Iterator;
51  import java.util.List;
52  
53  
54  /**
55   * Contains utility methods to register or check for the existence of elements in web.xml.
56   *
57   * @author gjoseph
58   * @version $Revision: $ ($Author: $)
59   */
60  public class WebXmlUtil {
61      private final Document doc;
62  
63      public WebXmlUtil() {
64          final File source = new File(Path.getAppRootDir() + "/WEB-INF/web.xml");
65          if (!source.exists()) {
66              throw new IllegalStateException("Failed to locate web.xml : " + source.getAbsolutePath());
67          }
68          final SAXBuilder builder = new SAXBuilder();
69          try {
70              doc = builder.build(source);
71          } catch (JDOMException e) {
72              throw new RuntimeException(e); // TODO
73          } catch (IOException e) {
74              throw new RuntimeException(e); // TODO
75          }
76      }
77  
78      /**
79       * Test-friendly constructor.
80       */
81      public WebXmlUtil(InputStream inputStream) {
82          final SAXBuilder builder = new SAXBuilder();
83          try {
84              doc = builder.build(inputStream);
85          } catch (JDOMException e) {
86              throw new RuntimeException(e); // TODO
87          } catch (IOException e) {
88              throw new RuntimeException(e); // TODO
89          }
90      }
91  
92      public boolean isServletOrMappingRegistered(String servletName) {
93          return isServletRegistered(servletName) || isServletMappingRegistered(servletName);
94      }
95  
96      public boolean isServletRegistered(String servletName) {
97          return xpathMatches("/webxml:web-app/webxml:servlet[webxml:servlet-name='" + servletName + "']");
98      }
99  
100     public boolean isServletMappingRegistered(String servletName) {
101         return xpathMatches("/webxml:web-app/webxml:servlet-mapping[webxml:servlet-name='" + servletName + "']");
102     }
103 
104     public boolean isServletMappingRegistered(String servletName, String urlPattern) {
105         final String xpathExpr = "/webxml:web-app/webxml:servlet-mapping[webxml:servlet-name='"
106                 + servletName + "' and webxml:url-pattern='" + urlPattern + "']";
107         return xpathMatches(xpathExpr);
108     }
109 
110     public Collection getServletMappings(String servletName) {
111         final String servletMappingXPathExpr = "/webxml:web-app/webxml:servlet-mapping[webxml:servlet-name='" + servletName + "']/webxml:url-pattern";
112         final List servletMappings = getElementsFromXPath(servletMappingXPathExpr);
113 
114         return CollectionUtils.collect(servletMappings, new Transformer() {
115             public Object transform(Object input) {
116                 final Element servletMapping = (Element) input;
117                 return servletMapping.getText();
118             }
119         });
120     }
121 
122     public boolean isFilterRegistered(String filterClass) {
123         return getFilterElement(filterClass) != null;
124     }
125 
126     /**
127      * @deprecated since 3.6.4, use checkFilterDispatchersConfiguration()
128      */
129     public boolean areFilterDispatchersConfiguredProperly(String filterClass, List mandatoryDispatchers, List optionalDispatchers) {
130         return checkFilterDispatchersConfiguration(filterClass, mandatoryDispatchers, optionalDispatchers) >= 0;
131     }
132 
133     /**
134      * Returns:
135      * +1 if all mandatory dispatchers are present and no additional unsupported dispatcher is present, or this filter class isn't registered.
136      * 0  if all mandatory dispatchers are present but additional unsupported dispatchers are present.
137      * -1  if not all mandatory dispatchers are present.
138      */
139     public int checkFilterDispatchersConfiguration(String filterClass, List mandatoryDispatchers, List optionalDispatchers) {
140         final Element filterEl = getFilterElement(filterClass);
141         if (filterEl != null) {
142             final String filterName = filterEl.getTextNormalize();
143             final String filterMappingXPathExpr = "/webxml:web-app/webxml:filter-mapping[webxml:filter-name='" + filterName + "']/webxml:dispatcher";
144             final List dispatchersEl = getElementsFromXPath(filterMappingXPathExpr);
145             final List registeredDispatchers = new ArrayList();
146             final Iterator it = dispatchersEl.iterator();
147             while (it.hasNext()) {
148                 final Element dispatcherEl = (Element) it.next();
149                 registeredDispatchers.add(dispatcherEl.getTextNormalize());
150             }
151             registeredDispatchers.removeAll(optionalDispatchers);
152             if (CollectionUtils.isEqualCollection(mandatoryDispatchers, registeredDispatchers)) {
153                 return 1;
154             } else if (CollectionUtils.isSubCollection(mandatoryDispatchers, registeredDispatchers)) {
155                 return 0;
156             } else {
157                 return -1;
158             }
159 
160         }
161         return 1;
162     }
163 
164     public boolean isListenerRegistered(String deprecatedListenerClass) {
165         final String xpathExpr = "/webxml:web-app/webxml:listener[webxml:listener-class='" + deprecatedListenerClass + "']";
166         return xpathMatches(xpathExpr);
167     }
168 
169     private Element getFilterElement(String filterClass) {
170         final String filterXPathExpr = "/webxml:web-app/webxml:filter[webxml:filter-class='" + filterClass + "']/webxml:filter-name";
171 
172         return getElementFromXPath(filterXPathExpr);
173     }
174 
175     private List getElementsFromXPath(String xpathExpr) {
176         try {
177             final XPath xpath = XPath.newInstance(xpathExpr);
178             // must add the namespace and use it: there is no default namespace elsewise
179             xpath.addNamespace("webxml", doc.getRootElement().getNamespace().getURI());
180             return xpath.selectNodes(doc);
181         } catch (JDOMException e) {
182             throw new RuntimeException(e); // TODO
183         }
184     }
185 
186     private Element getElementFromXPath(String xpathExpr) {
187         final List list = getElementsFromXPath(xpathExpr);
188         return (Element) (list.size() > 0 ? list.get(0) : null);
189     }
190 
191     private boolean xpathMatches(String xpathExpr) {
192         return getElementsFromXPath(xpathExpr).size() > 0;
193     }
194 }