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 javax.servlet.ServletRequest;
022
023/**
024 * Implementation of the {@link org.apache.commons.jxpath.DynamicPropertyHandler}
025 * interface that provides access to attributes and parameters
026 * of a {@link ServletRequest}.
027 *
028 * @author Dmitri Plotnikov
029 * @version $Revision: 652848 $ $Date: 2008-05-02 19:53:50 +0200 (Fr, 02 Mai 2008) $
030 */
031public class ServletRequestHandler extends HttpSessionHandler {
032
033    protected void collectPropertyNames(HashSet set, Object bean) {
034        super.collectPropertyNames(set, bean);
035        ServletRequestAndContext handle = (ServletRequestAndContext) bean;
036        ServletRequest servletRequest = handle.getServletRequest();
037        Enumeration e = servletRequest.getAttributeNames();
038        while (e.hasMoreElements()) {
039            set.add(e.nextElement());
040        }
041        e = servletRequest.getParameterNames();
042        while (e.hasMoreElements()) {
043            set.add(e.nextElement());
044        }
045    }
046
047    public Object getProperty(Object bean, String property) {
048        ServletRequestAndContext handle = (ServletRequestAndContext) bean;
049        ServletRequest servletRequest = handle.getServletRequest();
050        String[] strings = servletRequest.getParameterValues(property);
051
052        if (strings != null) {
053            if (strings.length == 0) {
054                return null;
055            }
056            if (strings.length == 1) {
057                return strings[0];
058            }
059            return strings;
060        }
061
062        Object object = servletRequest.getAttribute(property);
063        if (object != null) {
064            return object;
065        }
066
067        return super.getProperty(bean, property);
068    }
069
070    public void setProperty(Object request, String property, Object value) {
071        ((ServletRequestAndContext) request).getServletRequest().setAttribute(property, value);
072    }
073}