1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.jxpath.servlet;
18
19 import java.util.Enumeration;
20 import java.util.HashSet;
21 import java.util.Set;
22
23 import javax.servlet.ServletContext;
24
25 import org.apache.commons.jxpath.DynamicPropertyHandler;
26
27 /**
28 * Implementation of the {@link DynamicPropertyHandler} interface that provides
29 * access to attributes of a {@link ServletContext}.
30 *
31 * @author Dmitri Plotnikov
32 * @version $Revision: 1190148 $ $Date: 2011-10-28 00:00:29 -0400 (Fri, 28 Oct 2011) $
33 */
34 public class ServletContextHandler implements DynamicPropertyHandler {
35
36 private static final int DEFAULT_PROPERTY_COUNT = 16;
37
38 public String[] getPropertyNames(Object context) {
39 Set list = new HashSet(DEFAULT_PROPERTY_COUNT);
40 collectPropertyNames(list, context);
41 return (String[]) list.toArray(new String[list.size()]);
42 }
43
44 /**
45 * Collect the property names from bean, storing in set.
46 * @param set destination
47 * @param bean to read
48 */
49 protected void collectPropertyNames(Set set, Object bean) {
50 if (bean instanceof HttpSessionAndServletContext) {
51 bean = ((HttpSessionAndServletContext) bean).getServletContext();
52 }
53 Enumeration e = ((ServletContext) bean).getAttributeNames();
54 while (e.hasMoreElements()) {
55 set.add(e.nextElement());
56 }
57 }
58
59 public Object getProperty(Object context, String property) {
60 return ((ServletContext) context).getAttribute(property);
61 }
62
63 public void setProperty(Object context, String property, Object value) {
64 ((ServletContext) context).setAttribute(property, value);
65 }
66 }