package org.apache.turbine.pipeline;


/*
 * 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.
 */


import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.turbine.util.HttpUtils;
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.TurbineException;
import org.apache.turbine.util.uri.URIConstants;

/**
 * This valve is responsible for setting the 'action' property of RunData based
 * on request parameter. There is no default action, since a null action is
 * perfectly valid.
 *
 * @author <a href="mailto:james@jamestaylor.org">James Taylor</a>
 * @author <a href="mailto:peter@courcoux.biz">Peter Courcoux</a>
 */
public class DetermineActionValve
    implements Valve
{
    private static final Logger log
        = LogManager.getLogger(DetermineActionValve.class);

    /**
     * @see org.apache.turbine.pipeline.Valve#invoke(PipelineData, ValveContext)
     */
    @Override
    public void invoke(PipelineData pipelineData, ValveContext context)
        throws IOException, TurbineException
    {
        RunData data = pipelineData.getRunData();
        if (!data.hasAction())
        {
            String action =
                data.getParameters().getString(URIConstants.CGI_ACTION_PARAM);

            if (action != null)
            {
                if (HttpUtils.keyRequiresClean( action ))
                {
                    String testAction = HttpUtils.getCleanedKey( action );
                    String message = URIConstants.CGI_ACTION_PARAM + " has invalid characters. ";
                    log.warn("{}. Debug action key: {}.", message, testAction);
                    throw new TurbineException( message );
                }
                data.setAction(action);
                log.debug("Set action from request parameter");
            }
            else
            {
                log.debug("No action");
            }
        }

        log.debug("Action is now: {}", data::getAction);

        // Pass control to the next Valve in the Pipeline
        context.invokeNext(pipelineData);
    }
}
