KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > beans > config > FilterManager


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.beans.config;
14
15 import info.magnolia.cms.core.Content;
16 import info.magnolia.cms.core.ItemType;
17 import info.magnolia.cms.util.ClassUtil;
18 import info.magnolia.cms.util.ContentUtil;
19 import info.magnolia.cms.util.FactoryUtil;
20 import info.magnolia.cms.util.ObservationUtil;
21 import info.magnolia.context.MgnlContext;
22
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.Collections JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32
33 import javax.jcr.RepositoryException;
34 import javax.jcr.observation.EventIterator;
35 import javax.jcr.observation.EventListener;
36 import javax.servlet.Filter JavaDoc;
37 import javax.servlet.FilterConfig JavaDoc;
38 import javax.servlet.ServletContext JavaDoc;
39 import javax.servlet.ServletException JavaDoc;
40
41 import org.apache.commons.lang.ArrayUtils;
42 import org.apache.commons.lang.StringUtils;
43 import org.apache.commons.lang.builder.CompareToBuilder;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47
48 /**
49  * Manages configuration of webapp filters, stored in jcr. Configured filters are loaded and used by
50  * {@link info.magnolia.cms.filters.MagnoliaManagedFilter}.
51  * @author Fabrizio Giustina
52  * @version $Revision: 6893 $ ($Author: philipp $)
53  */

54 public final class FilterManager {
55
56     /**
57      * Name for the config node that contains filter initialization parameters.
58      */

59     private static final String JavaDoc PARAM_CONFIG = "config";
60
61     /**
62      * Name for the parameters that contains the priority.
63      */

64     private static final String JavaDoc PARAM_PRIORITY = "priority";
65
66     /**
67      * Name for the parameters that contains the filter class.
68      */

69     private static final String JavaDoc PARAM_FILTERCLASS = "class";
70
71     /**
72      * config path
73      */

74     private static final String JavaDoc SERVER_FILTERS = "/server/filters";
75
76     /**
77      * Logger
78      */

79     protected Logger log = LoggerFactory.getLogger(getClass());
80
81     private Filter JavaDoc[] filterChain;
82
83     /**
84      * Array of filter definitions.
85      */

86     private FilterDefinition[] filterDefinitions;
87
88     /**
89      * Filterconfig set by the *real* filter.
90      */

91     private FilterConfig JavaDoc filterConfig;
92
93     /**
94      * Do not instantiate yourself
95      */

96     public FilterManager() {
97         init();
98         ObservationUtil.registerChangeListener(ContentRepository.CONFIG, SERVER_FILTERS, new EventListener() {
99
100             public void onEvent(EventIterator arg0) {
101                 MgnlContext.setInstance(MgnlContext.getSystemContext());
102                 init();
103             }
104         });
105     }
106
107     /**
108      * Returns the FilterManager instance.
109      * @return FilterManager instance.
110      */

111     public static FilterManager getInstance() {
112         return (FilterManager) FactoryUtil.getSingleton(FilterManager.class);
113     }
114
115     /**
116      * @return array of filters as configured
117      */

118     public Filter JavaDoc[] getFilters() {
119         return filterChain;
120     }
121
122     /**
123      * Getter for <code>filterDefinitions</code>.
124      * @return Returns the filterDefinitions.
125      */

126     public FilterDefinition[] getFilterDefinitions() {
127         return this.filterDefinitions;
128     }
129
130     /**
131      * initialized filter chain
132      */

133     protected void init() {
134
135         extractDefinitions();
136
137         this.filterChain = new Filter JavaDoc[filterDefinitions.length];
138
139         for (int j = 0; j < filterDefinitions.length; j++) {
140             FilterDefinition definition = filterDefinitions[j];
141             try {
142                 Filter JavaDoc filter = (Filter JavaDoc) ClassUtil.newInstance(definition.getClassName());
143                 this.filterChain[j] = filter;
144             }
145             catch (Throwable JavaDoc e) {
146                 log.error("Failed to instantiate filter [ " + definition.getClassName() + " ]", e);
147
148                 // remove definition!
149
filterDefinitions = (FilterDefinition[]) ArrayUtils.remove(filterDefinitions, j);
150                 j--;
151             }
152         }
153
154         // the first initialization is done by the filter, but this is needed for reload
155
// not quite a clean design, but working...
156
if (filterConfig != null) {
157             initFilters(filterConfig);
158         }
159     }
160
161     /**
162      *
163      */

164     private void extractDefinitions() {
165         List JavaDoc definitionList = new ArrayList JavaDoc();
166
167         Content node = ContentUtil.getContent(ContentRepository.CONFIG, SERVER_FILTERS);
168
169         if (node != null) {
170
171             Collection JavaDoc children = node.getChildren(ItemType.CONTENT);
172
173             Iterator JavaDoc childIterator = children.iterator();
174
175             while (childIterator.hasNext()) {
176                 Content child = (Content) childIterator.next();
177
178                 String JavaDoc filterClass = child.getNodeData(PARAM_FILTERCLASS).getString();
179
180                 if (StringUtils.isNotEmpty(filterClass)) {
181                     FilterDefinition definition = new FilterDefinition();
182                     definition.setClassName(filterClass);
183                     definition.setPriority(child.getNodeData(PARAM_PRIORITY).getLong());
184
185                     try {
186                         if (child.hasContent(PARAM_CONFIG)) {
187                             Content config = child.getContent(PARAM_CONFIG);
188                             definition.setParameters(ContentUtil.toMap(config));
189                         }
190                     }
191                     catch (RepositoryException e) {
192                         log.error("Unable to read config parameters for filter {} due to a ", filterClass, e
193                             .getClass()
194                             .getName());
195                     }
196
197                     log.debug("Adding filter [{}] to managed filter list", filterClass);
198
199                     definitionList.add(definition);
200
201                 }
202             }
203         }
204
205         Collections.sort(definitionList);
206
207         filterDefinitions = (FilterDefinition[]) definitionList.toArray(new FilterDefinition[definitionList.size()]);
208     }
209
210     /**
211      * @param filterConfig
212      * @throws ServletException
213      */

214     public void initFilters(FilterConfig JavaDoc filterConfig) {
215         this.filterConfig = filterConfig;
216         for (int j = 0; j < getFilterDefinitions().length; j++) {
217             FilterDefinition filter = getFilterDefinitions()[j];
218             FilterManager.CustomFilterConfig customFilterConfig = new FilterManager.CustomFilterConfig(
219                 filterConfig,
220                 filter.getParameters());
221
222             try {
223                 getFilters()[j].init(customFilterConfig);
224             }
225             catch (ServletException JavaDoc e) {
226                 log.error("Error initializing filter " + filter.getClassName(), e);
227             }
228
229             log.info("Initializing filter {}", filter.getClassName());
230         }
231     }
232
233     /**
234      * Represents a configured filter.
235      * @author fgiust
236      * @version $Revision: 6893 $ ($Author: philipp $)
237      */

238     public static class FilterDefinition implements Comparable JavaDoc {
239
240         /**
241          * Filter class name.
242          */

243         private String JavaDoc className;
244
245         /**
246          * Priority, lower is first.
247          */

248         private long priority;
249
250         /**
251          * Optional parameters.
252          */

253         private Map JavaDoc parameters;
254
255         /**
256          * Getter for <code>className</code>.
257          * @return Returns the className.
258          */

259         public String JavaDoc getClassName() {
260             return this.className;
261         }
262
263         /**
264          * Setter for <code>className</code>.
265          * @param className The className to set.
266          */

267         public void setClassName(String JavaDoc className) {
268             this.className = className;
269         }
270
271         /**
272          * Getter for <code>parameters</code>.
273          * @return Returns the parameters.
274          */

275         public Map JavaDoc getParameters() {
276             return this.parameters;
277         }
278
279         /**
280          * Setter for <code>parameters</code>.
281          * @param parameters The parameters to set.
282          */

283         public void setParameters(Map JavaDoc parameters) {
284             this.parameters = parameters;
285         }
286
287         /**
288          * Getter for <code>priority</code>.
289          * @return Returns the priority.
290          */

291         public long getPriority() {
292             return this.priority;
293         }
294
295         /**
296          * Setter for <code>priority</code>.
297          * @param priority The priority to set.
298          */

299         public void setPriority(long priority) {
300             this.priority = priority;
301         }
302
303         /**
304          * {@inheritDoc}
305          */

306         public int compareTo(Object JavaDoc object) {
307             FilterDefinition myClass = (FilterDefinition) object;
308             return new CompareToBuilder().append(this.priority, myClass.priority).toComparison();
309         }
310
311     }
312
313     public static class CustomFilterConfig implements FilterConfig JavaDoc {
314
315         private Map JavaDoc parameters;
316
317         private FilterConfig JavaDoc parent;
318
319         /**
320          * @param parameters
321          */

322         public CustomFilterConfig(FilterConfig JavaDoc parent, Map JavaDoc parameters) {
323             super();
324             this.parent = parent;
325             if (parameters != null) {
326                 this.parameters = parameters;
327             }
328             else {
329                 this.parameters = new HashMap JavaDoc();
330             }
331         }
332
333         /**
334          * @see javax.servlet.FilterConfig#getFilterName()
335          */

336         public String JavaDoc getFilterName() {
337             return parent.getFilterName();
338         }
339
340         /**
341          * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
342          */

343         public String JavaDoc getInitParameter(String JavaDoc name) {
344             return (String JavaDoc) parameters.get(name);
345         }
346
347         /**
348          * @see javax.servlet.FilterConfig#getInitParameterNames()
349          */

350         public Enumeration JavaDoc getInitParameterNames() {
351             return new Hashtable JavaDoc(parameters).keys();
352         }
353
354         /**
355          * @see javax.servlet.FilterConfig#getServletContext()
356          */

357         public ServletContext JavaDoc getServletContext() {
358             return parent.getServletContext();
359         }
360
361     }
362
363 }
364
Popular Tags