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 */ 017 018package org.apache.commons.jxpath.servlet; 019 020import java.util.Enumeration; 021import java.util.HashSet; 022 023import javax.servlet.ServletContext; 024 025import org.apache.commons.jxpath.DynamicPropertyHandler; 026 027/** 028 * Implementation of the {@link DynamicPropertyHandler} interface that provides access to attributes of a {@link ServletContext}. 029 */ 030public class ServletContextHandler implements DynamicPropertyHandler { 031 032 private static final int DEFAULT_PROPERTY_COUNT = 16; 033 034 /** 035 * Constructs a new instance. 036 */ 037 public ServletContextHandler() { 038 // empty 039 } 040 041 /** 042 * Collect the property names from bean, storing in set. 043 * 044 * @param set destination 045 * @param bean to read 046 */ 047 protected void collectPropertyNames(final HashSet<String> set, Object bean) { 048 if (bean instanceof HttpSessionAndServletContext) { 049 bean = ((HttpSessionAndServletContext) bean).getServletContext(); 050 } 051 final Enumeration<String> e = ((ServletContext) bean).getAttributeNames(); 052 while (e.hasMoreElements()) { 053 set.add(e.nextElement()); 054 } 055 } 056 057 @Override 058 public Object getProperty(final Object context, final String property) { 059 return ((ServletContext) context).getAttribute(property); 060 } 061 062 @Override 063 public String[] getPropertyNames(final Object context) { 064 final HashSet<String> set = new HashSet<>(DEFAULT_PROPERTY_COUNT); 065 collectPropertyNames(set, context); 066 return set.toArray(new String[set.size()]); 067 } 068 069 @Override 070 public void setProperty(final Object context, final String property, final Object value) { 071 ((ServletContext) context).setAttribute(property, value); 072 } 073}