001/* 002 * Copyright 2023 Web-Legacy 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.apache.tiles.request.jakarta.servlet.extractor; 017 018import java.util.Collections; 019import java.util.Enumeration; 020 021import org.apache.tiles.request.attribute.AttributeExtractor; 022 023import jakarta.servlet.http.HttpServletRequest; 024import jakarta.servlet.http.HttpSession; 025 026/** 027 * Extract attributes from session scope. 028 * 029 * <p>Copied from Apache tiles-request-servlet 1.0.7 and adapted for 030 * Jakarta EE 9.</p> 031 */ 032public class SessionScopeExtractor implements AttributeExtractor { 033 034 /** 035 * The servlet request. 036 */ 037 private HttpServletRequest request; 038 039 /** 040 * Constructor. 041 * 042 * @param request The servlet request. 043 */ 044 public SessionScopeExtractor(HttpServletRequest request) { 045 this.request = request; 046 } 047 048 /** 049 * Sets a value for the given key. 050 * 051 * @param name The key of the attribute. 052 * @param value The value of the attribute. 053 */ 054 @Override 055 public void setValue(String name, Object value) { 056 request.getSession().setAttribute(name, value); 057 } 058 059 /** 060 * Removes an attribute. 061 * 062 * @param name The key of the attribute to remove. 063 */ 064 @Override 065 public void removeValue(String name) { 066 HttpSession session = request.getSession(false); 067 if (session != null) { 068 session.removeAttribute(name); 069 } 070 } 071 072 /** 073 * The enumeration of the keys in the stored attributes. 074 * 075 * @return The keys. 076 */ 077 @Override 078 public Enumeration<String> getKeys() { 079 HttpSession session = request.getSession(false); 080 if (session != null) { 081 return session.getAttributeNames(); 082 } 083 084 return Collections.enumeration(Collections.<String>emptySet()); 085 } 086 087 /** 088 * Returns the value of the attribute with the given key. 089 * 090 * @param key The key of the attribute. 091 * 092 * @return The value. 093 */ 094 @Override 095 public Object getValue(String key) { 096 HttpSession session = request.getSession(false); 097 if (session != null) { 098 return session.getAttribute(key); 099 } 100 101 return null; 102 } 103}