001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.http.services;
014
015import java.io.IOException;
016import java.util.ArrayList;
017import java.util.List;
018
019import javax.servlet.http.HttpServletRequest;
020import javax.servlet.http.HttpServletResponse;
021
022import org.apache.tapestry5.http.CorsHandlerResult;
023import org.apache.tapestry5.ioc.annotations.UsesOrderedConfiguration;
024
025/**
026 * {@linkplain HttpServletRequestFilter} that handles CORS. Uses an ordered configuration of
027 * {@linkplain CorsHandler} instances.
028 * @see CorsHandler
029 * @since 5.8.2
030 */
031@UsesOrderedConfiguration(CorsHandler.class)
032public class CorsHttpServletRequestFilter implements HttpServletRequestFilter
033{
034
035    final List<CorsHandler> handlers;
036    
037    public CorsHttpServletRequestFilter(List<CorsHandler> handlers) 
038    {
039        this.handlers = new ArrayList<>(handlers);
040    }
041
042    @Override
043    public boolean service(HttpServletRequest request, HttpServletResponse response, HttpServletRequestHandler handler) throws IOException 
044    {
045        
046        boolean serviced = false;
047        for (CorsHandler corsHandler : handlers)
048        {
049            
050            final CorsHandlerResult result = corsHandler.handle(request, response);
051            if (result.equals(CorsHandlerResult.CONTINUE_REQUEST_PROCESSING)) 
052            {
053                break;
054            }
055            else if (result.equals(CorsHandlerResult.STOP_REQUEST_PROCESSING)) 
056            {
057                serviced = true;
058                break;
059            }
060            
061        }
062        
063        if (!serviced) 
064        {
065            serviced = handler.service(request, response);
066        }
067        
068        return serviced;
069    }
070
071}