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.Enumeration;
019
020import org.apache.tiles.request.attribute.EnumeratedValuesExtractor;
021
022import jakarta.servlet.http.HttpServletRequest;
023import jakarta.servlet.http.HttpServletResponse;
024
025/**
026 * Extract header values from an HTTP request.
027 *
028 * <p>Copied from Apache tiles-request-servlet 1.0.7 and adapted for
029 * Jakarta EE 9.</p>
030 */
031public class HeaderExtractor implements EnumeratedValuesExtractor {
032
033    /**
034     * The request.
035     */
036    private HttpServletRequest request;
037
038    /**
039     * The response.
040     */
041    private HttpServletResponse response;
042
043    /**
044     * Constructor.
045     *
046     * @param request  The request.
047     * @param response The response.
048     */
049    public HeaderExtractor(HttpServletRequest request,
050            HttpServletResponse response) {
051
052        this.request = request;
053        this.response = response;
054    }
055
056    /**
057     * The enumeration of the keys in the stored attributes.
058     *
059     * @return The keys.
060     */
061    @Override
062    public Enumeration<String> getKeys() {
063        return request.getHeaderNames();
064    }
065
066    /**
067     * Returns the value of the attribute with the given key.
068     *
069     * @param key The key of the attribute.
070     *
071     * @return The value.
072     */
073    @Override
074    public String getValue(String key) {
075        return request.getHeader(key);
076    }
077
078    /**
079     * Returns the values stored at the given key.
080     *
081     * @param key The key of the attribute.
082     *
083     * @return The values of the attribute.
084     */
085    @Override
086    public Enumeration<String> getValues(String key) {
087        return request.getHeaders(key);
088    }
089
090    /**
091     * Sets a value for the given key.
092     *
093     * @param key The key of the attribute.
094     *
095     * @param value The value of the attribute.
096     */
097    @Override
098    public void setValue(String key, String value) {
099        response.setHeader(key, value);
100    }
101}