001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.jxpath.servlet;
018
019import java.util.Enumeration;
020import java.util.HashSet;
021import java.util.Set;
022
023import javax.servlet.ServletContext;
024
025import org.apache.commons.jxpath.DynamicPropertyHandler;
026
027/**
028 * Implementation of the {@link DynamicPropertyHandler} interface that provides
029 * access to attributes of a {@link ServletContext}.
030 *
031 * @author Dmitri Plotnikov
032 * @version $Revision: 1190148 $ $Date: 2011-10-28 00:00:29 -0400 (Fri, 28 Oct 2011) $
033 */
034public class ServletContextHandler implements DynamicPropertyHandler {
035
036    private static final int DEFAULT_PROPERTY_COUNT = 16;
037
038    public String[] getPropertyNames(Object context) {
039        Set list = new HashSet(DEFAULT_PROPERTY_COUNT);
040        collectPropertyNames(list, context);
041        return (String[]) list.toArray(new String[list.size()]);
042    }
043
044    /**
045     * Collect the property names from bean, storing in set.
046     * @param set destination
047     * @param bean to read
048     */
049    protected void collectPropertyNames(Set set, Object bean) {
050        if (bean instanceof HttpSessionAndServletContext) {
051            bean = ((HttpSessionAndServletContext) bean).getServletContext();
052        }
053        Enumeration e = ((ServletContext) bean).getAttributeNames();
054        while (e.hasMoreElements()) {
055            set.add(e.nextElement());
056        }
057    }
058
059    public Object getProperty(Object context, String property) {
060        return ((ServletContext) context).getAttribute(property);
061    }
062
063    public void setProperty(Object context, String property, Object value) {
064        ((ServletContext) context).setAttribute(property, value);
065    }
066}