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.http.HttpSession;
022
023import org.apache.commons.jxpath.JXPathException;
024
025/**
026 * Implementation of the {@link org.apache.commons.jxpath.DynamicPropertyHandler}
027 * interface that provides access to attributes of a @{link HttpSession}.
028 *
029 * @author Dmitri Plotnikov
030 * @version $Revision: 652845 $ $Date: 2008-05-02 19:46:46 +0200 (Fr, 02 Mai 2008) $
031 */
032public class HttpSessionHandler extends ServletContextHandler {
033
034    protected void collectPropertyNames(HashSet set, Object bean) {
035        HttpSessionAndServletContext handle =
036            (HttpSessionAndServletContext) bean;
037        super.collectPropertyNames(set, handle.getServletContext());
038        HttpSession session = handle.getSession();
039        if (session != null) {
040            Enumeration e = session.getAttributeNames();
041            while (e.hasMoreElements()) {
042                set.add(e.nextElement());
043            }
044        }
045    }
046
047    public Object getProperty(Object bean, String property) {
048        HttpSessionAndServletContext handle =
049            (HttpSessionAndServletContext) bean;
050        HttpSession session = handle.getSession();
051        if (session != null) {
052            Object object = session.getAttribute(property);
053            if (object != null) {
054                return object;
055            }
056        }
057        return super.getProperty(handle.getServletContext(), property);
058    }
059
060    public void setProperty(Object bean, String property, Object value) {
061        HttpSessionAndServletContext handle =
062            (HttpSessionAndServletContext) bean;
063        HttpSession session = handle.getSession();
064        if (session != null) {
065            session.setAttribute(property, value);
066        }
067        else {
068            throw new JXPathException("Cannot set session attribute: "
069                    + "there is no session");
070        }
071    }
072}