<commit_before>package org.apache.camel.component.resteasy.servlet;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.component.http.HttpConsumer;
import org.apache.camel.component.http.HttpMessage;
import org.apache.camel.component.http.HttpServletResolveConsumerStrategy;
import org.apache.camel.component.http.ServletResolveConsumerStrategy;
import org.apache.camel.component.http.helper.HttpHelper;
import org.apache.camel.component.resteasy.*;
import org.apache.camel.impl.DefaultExchange;

import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author : <NAME> (<EMAIL>)
 */
public class ResteasyCamelServlet extends HttpServletDispatcher {
    private HttpRegistry httpRegistry;

    private String servletName;

    private ServletResolveConsumerStrategy servletResolveConsumerStrategy = new HttpServletResolveConsumerStrategy();
    private final ConcurrentMap<String, HttpConsumer> consumers = new ConcurrentHashMap<String, HttpConsumer>();

    private static final Logger LOG = LoggerFactory.getLogger(ResteasyCamelServlet.class);



    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);

        String name = servletConfig.getServletName();
        if (httpRegistry == null) {
            httpRegistry = DefaultHttpRegistry.getHttpRegistry(name);
            ResteasyCamelServlet existing = httpRegistry.getCamelServlet(name);
            if (existing != null) {
                String msg = "Duplicate ServletName detected: " + name + ". Existing: " + existing + " This: " + this.toString()
                        + ". Its advised to use unique ServletName per Camel application.";
                // always log so people can see it easier
                LOG.info(msg);
            }
            httpRegistry.register(this);
        }


        for (Map.Entry<String, HttpConsumer> entry : consumers.entrySet())
        {
            String proxyClasses = ((ResteasyComponent)getServletEndpoint(entry.getValue()).getComponent()).getProxyConsumersClasses();
            if(proxyClasses != null){
                String[] classes = proxyClasses.split(",");
                LOG.debug("Proxy classes defined in the component {}" , Arrays.asList(classes));

                for(String clazz : classes){
                    try {
                        Class realClazz = Class.forName(clazz);
                        // Create dynamic proxy class implementing interface
                        InvocationHandler handler = new ResteasyInvocationHandler();
                        Object  proxy = Proxy.newProxyInstance(realClazz.getClassLoader(), new Class[]{realClazz}, handler);

                        // register new created proxy to the resteasy registry
                        getDispatcher().getRegistry().addSingletonResource(proxy);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return;
            }
        }
    }

    private ResteasyEndpoint getServletEndpoint(HttpConsumer consumer) {
        if (!(consumer.getEndpoint() instanceof ResteasyEndpoint)) {
            throw new RuntimeException("Invalid consumer type. Must be RESTEasyEndpoint but is "
                    + consumer.getClass().getName());
        }
        return (ResteasyEndpoint)consumer.getEndpoint();
    }

    @Override
    protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        // From camel servlet
        if (LOG.isTraceEnabled()) {
            LOG.trace("Service: {}", httpServletRequest);
        }

        // Is there a consumer registered for the request.
        HttpConsumer consumer = resolve(httpServletRequest);

        if (consumer == null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("No consumer to service request {}", httpServletRequest);
            }
            // No consumer found in routes let resteasy dispatcher process the request -> returning unchanged rest answer
            super.service(httpServletRequest, httpServletResponse);
            return;
        }
        // are we suspended?
        if (consumer.isSuspended()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Consumer suspended, cannot service request {}", httpServletRequest);
            }
            httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        // if its an OPTIONS request then return which method is allowed
        if ("OPTIONS".equals(httpServletRequest.getMethod())) {
            String s;
            if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
                s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
            } else {
                // allow them all
                s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
            }
            httpServletResponse.addHeader("Allow", s);
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        if ("TRACE".equals(httpServletRequest.getMethod()) && !consumer.isTraceEnabled()) {
            httpServletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        // create exchange and set data on it
        Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);
        if (consumer.getEndpoint().isBridgeEndpoint()) {
            exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
            exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE);
        }
        if (consumer.getEndpoint().isDisableStreamCache()) {
            exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
        }

        // camelProxy is set to true then don't process in servlet. Just continue to camel route
        // if camelProxy is true then check httpMethodRestrict
        if( getServletEndpoint(consumer).getCamelProxy()){
            if(! httpServletRequest.getMethod().equals(getServletEndpoint(consumer).getHttpMethodRestrict())){
                httpServletResponse.setStatus(405);
                return;
            }

        } else{
            super.service(httpServletRequest, httpServletResponse);
        }

        String response = "";

        if(getServletEndpoint(consumer).getProxy()){
            // Servlet is returning status code 204 if request was correct but there is no content -> if 204 continue to camel route
            if(httpServletResponse.getStatus() != 200 && httpServletResponse.getStatus() != 204){
                // If request wasn't successful in resteasy then stop processing and return created response from resteasy
                return;
            }

            // Proxy is set to true
            HttpHelper.setCharsetFromContentType(httpServletRequest.getContentType(), exchange);
            HttpMessage m = new HttpMessage(exchange, httpServletRequest, httpServletResponse);
<commit_msg>Repair small mistake in camel proxy consumer and httpMethodRestrict option<commit_after>package org.apache.camel.component.resteasy.servlet;

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.component.http.HttpConsumer;
import org.apache.camel.component.http.HttpMessage;
import org.apache.camel.component.http.HttpServletResolveConsumerStrategy;
import org.apache.camel.component.http.ServletResolveConsumerStrategy;
import org.apache.camel.component.http.helper.HttpHelper;
import org.apache.camel.component.resteasy.*;
import org.apache.camel.impl.DefaultExchange;

import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author : <NAME> (<EMAIL>)
 */
public class ResteasyCamelServlet extends HttpServletDispatcher {
    private HttpRegistry httpRegistry;

    private String servletName;

    private ServletResolveConsumerStrategy servletResolveConsumerStrategy = new HttpServletResolveConsumerStrategy();
    private final ConcurrentMap<String, HttpConsumer> consumers = new ConcurrentHashMap<String, HttpConsumer>();

    private static final Logger LOG = LoggerFactory.getLogger(ResteasyCamelServlet.class);



    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);

        String name = servletConfig.getServletName();
        if (httpRegistry == null) {
            httpRegistry = DefaultHttpRegistry.getHttpRegistry(name);
            ResteasyCamelServlet existing = httpRegistry.getCamelServlet(name);
            if (existing != null) {
                String msg = "Duplicate ServletName detected: " + name + ". Existing: " + existing + " This: " + this.toString()
                        + ". Its advised to use unique ServletName per Camel application.";
                // always log so people can see it easier
                LOG.info(msg);
            }
            httpRegistry.register(this);
        }


        for (Map.Entry<String, HttpConsumer> entry : consumers.entrySet())
        {
            String proxyClasses = ((ResteasyComponent)getServletEndpoint(entry.getValue()).getComponent()).getProxyConsumersClasses();
            if(proxyClasses != null){
                String[] classes = proxyClasses.split(",");
                LOG.debug("Proxy classes defined in the component {}" , Arrays.asList(classes));

                for(String clazz : classes){
                    try {
                        Class realClazz = Class.forName(clazz);
                        // Create dynamic proxy class implementing interface
                        InvocationHandler handler = new ResteasyInvocationHandler();
                        Object  proxy = Proxy.newProxyInstance(realClazz.getClassLoader(), new Class[]{realClazz}, handler);

                        // register new created proxy to the resteasy registry
                        getDispatcher().getRegistry().addSingletonResource(proxy);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return;
            }
        }
    }

    private ResteasyEndpoint getServletEndpoint(HttpConsumer consumer) {
        if (!(consumer.getEndpoint() instanceof ResteasyEndpoint)) {
            throw new RuntimeException("Invalid consumer type. Must be RESTEasyEndpoint but is "
                    + consumer.getClass().getName());
        }
        return (ResteasyEndpoint)consumer.getEndpoint();
    }

    @Override
    protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        // From camel servlet
        if (LOG.isTraceEnabled()) {
            LOG.trace("Service: {}", httpServletRequest);
        }

        // Is there a consumer registered for the request.
        HttpConsumer consumer = resolve(httpServletRequest);

        if (consumer == null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("No consumer to service request {}", httpServletRequest);
            }
            // No consumer found in routes let resteasy dispatcher process the request -> returning unchanged rest answer
            super.service(httpServletRequest, httpServletResponse);
            return;
        }
        // are we suspended?
        if (consumer.isSuspended()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Consumer suspended, cannot service request {}", httpServletRequest);
            }
            httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        // if its an OPTIONS request then return which method is allowed
        if ("OPTIONS".equals(httpServletRequest.getMethod())) {
            String s;
            if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
                s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
            } else {
                // allow them all
                s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
            }
            httpServletResponse.addHeader("Allow", s);
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        if ("TRACE".equals(httpServletRequest.getMethod()) && !consumer.isTraceEnabled()) {
            httpServletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            super.service(httpServletRequest, httpServletResponse);
            return;
        }

        // create exchange and set data on it
        Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);
        if (consumer.getEndpoint().isBridgeEndpoint()) {
            exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
            exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE);
        }
        if (consumer.getEndpoint().isDisableStreamCache()) {
            exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
        }

        // camelProxy is set to true then don't process in servlet. Just continue to camel route
        // if camelProxy is true then check httpMethodRestrict
        if( getServletEndpoint(consumer).getCamelProxy()){
            if(getServletEndpoint(consumer).getHttpMethodRestrict() != null && !httpServletRequest.getMethod().equals(getServletEndpoint(consumer).getHttpMethodRestrict())){
                httpServletResponse.setStatus(405);
                return;
            }

        } else{
            super.service(httpServletRequest, httpServletResponse);
        }

        String response = "";

        if(getServletEndpoint(consumer).getProxy()){
            // Servlet is returning status code 204 if request was correct but there is no content -> if 204 continue to camel route
            if(httpServletResponse.getStatus() != 200 && httpServletResponse.getStatus() != 204){
                // If request wasn't successful in resteasy then stop processing and return created response from resteasy
                return;
            }

            // Proxy is set to true
            HttpHelper.setCharsetFromContentType(httpServletRequest.getContentType(), exchange);
            HttpMessage m = new HttpMessage(exchange, httpServletRequest, httpServletResponse);

{'fraction_non_alphanumeric': 0.09072229140722292, 'fraction_numerical': 0.0021170610211706103, 'mean_word_length': 2.618972510139703, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1377375', 'n_tokens_mistral': 3972, 'n_tokens_neox': 3799, 'n_words': 892}