/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.myfaces.orchestra.requestParameterProvider;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * This wrapper intercepts encodeURL and pass it to the {@link RequestParameterProviderManager}
 * which attaches the url parameters
 */
public class RequestParameterResponseWrapper extends HttpServletResponseWrapper
{
    public RequestParameterResponseWrapper(HttpServletResponse httpServletResponse)
    {
        super(httpServletResponse);
    }

    /**
     * Override the inherited behaviour to add to the url any query parameters that have
     * been registered with the RequestParameterProviderManager.
     * <p>
     * Method ExternalContext.encodeActionURL will call this method. All JSF implementations
     * should invoke that method in the NavigationHandler implementation (on redirect), the
     * Form renderer and the commandLink renderer. This ensures that all the normal places
     * that send urls back to the client browser will insert the appropriate query-params.
     * <p>
     * Note however that ExternalContext.redirect does *not* call this method. And neither does
     * ViewHandler.getActionUrl(). Therefore custom code that uses redirect or emits "action urls"
     * itself should call ExternalContext.encodeActionURL (which in turn invokes this method).
     */
    public String encodeURL(String url)
    {
        if (url != null)
        {
            url = RequestParameterProviderManager.getInstance().encodeAndAttachParameters(url);
        }

        return super.encodeURL(url);
    }

    /**
     * Override deprecated form of this method, in case users call it.
     * <p>
     * The inherited implementation of this method calls super.encodeUrl(url)
     * directly, which would bypass our custom code.
     * 
     * @since 1.1
     * @deprecated
     */
    public String encodeUrl(String url)
    {
        return encodeURL(url);
    }
}
