001package org.apache.maven.wagon.tck.http.fixture;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *   http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import javax.servlet.ServletException;
023import javax.servlet.http.HttpServlet;
024import javax.servlet.http.HttpServletRequest;
025import javax.servlet.http.HttpServletResponse;
026import java.io.IOException;
027
028/**
029 * 
030 */
031public class RedirectionServlet
032    extends HttpServlet
033{
034
035    private static final long serialVersionUID = 1L;
036
037    private final String targetPath;
038
039    private final int code;
040
041    private final int maxRedirects;
042
043    private int redirectCount = 0;
044
045    private final String myPath;
046
047    public RedirectionServlet( final int code, final String targetPath )
048    {
049        this.code = code;
050        this.targetPath = targetPath;
051        this.maxRedirects = 1;
052        this.myPath = null;
053    }
054
055    public RedirectionServlet( final int code, final String myPath, final String targetPath, final int maxRedirects )
056    {
057        this.code = code;
058        this.myPath = myPath;
059        this.targetPath = targetPath;
060        this.maxRedirects = maxRedirects;
061    }
062
063    public int getRedirectCount()
064    {
065        return redirectCount;
066    }
067
068    @Override
069    protected void service( final HttpServletRequest req, final HttpServletResponse resp )
070        throws ServletException, IOException
071    {
072        redirectCount++;
073
074        if ( myPath == null )
075        {
076            resp.setStatus( code );
077            resp.setHeader( "Location", targetPath );
078        }
079        else if ( maxRedirects < 0 )
080        {
081            resp.setStatus( code );
082            resp.setHeader( "Location", myPath );
083        }
084        else if ( redirectCount <= maxRedirects )
085        {
086            resp.setStatus( code );
087            resp.setHeader( "Location", myPath + "/" + redirectCount );
088        }
089        else
090        {
091            resp.setStatus( code );
092            resp.setHeader( "Location", targetPath );
093        }
094    }
095
096}