<commit_before>/*
 * Copyright 2014
 *
 * Licensed 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.mule.modules.cors;

import org.mule.DefaultMuleEvent;
import org.mule.NonBlockingVoidMuleEvent;
import org.mule.OptimizedRequestContext;
import org.mule.api.MessagingException;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.store.ObjectStoreException;
import org.mule.api.transport.ReplyToHandler;
import org.mule.processor.AbstractRequestResponseMessageProcessor;

import org.apache.commons.lang.StringUtils;

public class ValidateMessageProcessor extends AbstractRequestResponseMessageProcessor {

    private boolean publicResource;
    private boolean acceptsCredentials;
    private CorsConfig config;

    @Override
    protected MuleEvent processRequest(MuleEvent event) throws MuleException {
        if (publicResource && acceptsCredentials) {
            throw new IllegalArgumentException("Resource may not be public and accept credentials at the same time");
        }

        //read the origin
        String origin = event.getMessage().getInboundProperty(Constants.ORIGIN);

        //if origin is not present, then not a CORS request
        if (StringUtils.isEmpty(origin)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Request is not a CORS request.");
            }
            return event;
        }

        //read headers including those of the preflight
        String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD);

        //decide if we want to invoke the flow.
        if (shouldInvokeFlow(origin, method, publicResource)) {
            return event;
        }

        //setting the response to null.
        event.getMessage().setPayload(null);
        //Set next message processor to null to stop further processing
        setListener(null);

        return event;
    }

    protected MuleEvent processResponse(final String origin, final String method, final String requestMethod, final String requestHeaders, MuleEvent event) throws MuleException
    {
        MuleMessage message = event.getMessage();

        if(StringUtils.isEmpty(origin)) {
            return event;
        }

        boolean isPreflight = StringUtils.equals(Constants.PREFLIGHT_METHOD, method);

        //if the resource is public then we don't check
        if (publicResource) {
            message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

            //and if it is a preflight call
            if (isPreflight) {
                message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, requestMethod);
                message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);<commit_msg>- Add proper logic to stop further processing of the event but still enable the process response method to add headers to the response.<commit_after>/*
 * Copyright 2014
 *
 * Licensed 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.mule.modules.cors;

import org.mule.DefaultMuleEvent;
import org.mule.NonBlockingVoidMuleEvent;
import org.mule.OptimizedRequestContext;
import org.mule.VoidMuleEvent;
import org.mule.api.MessagingException;
import org.mule.api.MuleEvent;
import org.mule.api.MuleException;
import org.mule.api.MuleMessage;
import org.mule.api.config.MuleProperties;
import org.mule.api.store.ObjectStoreException;
import org.mule.api.transport.PropertyScope;
import org.mule.api.transport.ReplyToHandler;
import org.mule.processor.AbstractRequestResponseMessageProcessor;

import org.apache.commons.lang.StringUtils;

public class ValidateMessageProcessor extends AbstractRequestResponseMessageProcessor {

    private static final String STOP_PROCESSING_FLAG = MuleProperties.PROPERTY_PREFIX + "__stopProcessing";

    private boolean publicResource;
    private boolean acceptsCredentials;
    private CorsConfig config;

    @Override
    protected MuleEvent processRequest(MuleEvent event) throws MuleException {
        if (publicResource && acceptsCredentials) {
            throw new IllegalArgumentException("Resource may not be public and accept credentials at the same time");
        }

        //read the origin
        String origin = event.getMessage().getInboundProperty(Constants.ORIGIN);

        //if origin is not present, then not a CORS request
        if (StringUtils.isEmpty(origin)) {
            if (logger.isDebugEnabled()) {
                logger.debug("Request is not a CORS request.");
            }
            return event;
        }

        //read headers including those of the preflight
        String method = event.getMessage().getInboundProperty(Constants.HTTP_METHOD);

        //decide if we want to invoke the flow.
        if (shouldInvokeFlow(origin, method, publicResource)) {
            return event;
        }

        //setting the response to null.
        event.getMessage().setPayload(null);
        //Set flag to stop further processing. I need this workaround because there are some headers
        //that might be set on the response and returning null or VoidMuleEvent won't allow it.
        event.getMessage().setInvocationProperty(STOP_PROCESSING_FLAG, true);

        return event;
    }

    @Override
    protected MuleEvent processNext(MuleEvent event) throws MuleException
    {
        if(event != null && !VoidMuleEvent.getInstance().equals(event)
                && Boolean.TRUE.equals(event.getMessage().getInvocationProperty(STOP_PROCESSING_FLAG))) {
            event.getMessage().removeProperty(STOP_PROCESSING_FLAG, PropertyScope.INVOCATION);
            return event;
        }

        return super.processNext(event);
    }

    protected MuleEvent processResponse(final String origin, final String method, final String requestMethod, final String requestHeaders, MuleEvent event) throws MuleException
    {
        MuleMessage message = event.getMessage();

        if(StringUtils.isEmpty(origin)) {
            return event;
        }

        boolean isPreflight = StringUtils.equals(Constants.PREFLIGHT_METHOD, method);

        //if the resource is public then we don't check
        if (publicResource) {
            message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

            //and if it is a preflight call
            if (isPreflight) {
                message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_METHODS, requestMethod);
                message.setOutboundProperty(Constants.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
{'fraction_non_alphanumeric': 0.07509568430777352, 'fraction_numerical': 0.0021116536887950377, 'mean_word_length': 3.191371681415929, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7660125', 'n_tokens_mistral': 1938, 'n_tokens_neox': 1900, 'n_words': 607}