<commit_before>/*
 * Copyright 2003-2006 <NAME> <winstone-devel at lists sourceforge net>
 * Distributed under the terms of either:
 * - the common development and distribution license (CDDL), v1.0; or
 * - the GNU Lesser General Public License, v2.1 or later
 */
package net.winstone.core.listener;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import net.winstone.WinstoneException;

import net.winstone.core.HostGroup;
import net.winstone.core.ObjectPool;
import net.winstone.core.WebAppConfiguration;
import net.winstone.core.WinstoneInputStream;
import net.winstone.core.WinstoneOutputStream;
import net.winstone.core.WinstoneRequest;
import net.winstone.core.WinstoneResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.winstone.util.StringUtils;
import net.winstone.core.authentication.AuthenticationPrincipal;

/**
 * Implements the main listener daemon thread. This is the class that gets launched by the command line, and owns the server socket, etc.
 * 
 * @author mailto: <a href="<EMAIL>"><NAME></a>
 * @version $Id: Ajp13Listener.java,v 1.13 2008/09/05 02:39:47 rickknowles Exp $
 */
public class Ajp13Listener implements Listener, Runnable {

    protected static Logger logger = LoggerFactory.getLogger(Ajp13Listener.class);
    private final static int LISTENER_TIMEOUT = 5000; // every 5s reset the listener socket
    private final static int DEFAULT_PORT = 8009;
    private final static int CONNECTION_TIMEOUT = 60000;
    private final static int BACKLOG_COUNT = 1000;
    private final static int KEEP_ALIVE_TIMEOUT = -1;
    // private final static int KEEP_ALIVE_SLEEP = 50;
    // private final static int KEEP_ALIVE_SLEEP_MAX = 500;
    private final static String TEMPORARY_URL_STASH = "winstone.ajp13.TemporaryURLAttribute";
    private final HostGroup hostGroup;
    private final ObjectPool objectPool;
    private final int listenPort;
    private boolean interrupted;
    private final String listenAddress;

    /**
     * Constructor
     */
    public Ajp13Listener(final Map<String, String> args, final ObjectPool objectPool, final HostGroup hostGroup) {
        // Load resources
        this.hostGroup = hostGroup;
        this.objectPool = objectPool;

        this.listenPort = Integer.parseInt(StringUtils.stringArg(args, "ajp13Port", "" + DEFAULT_PORT));
        this.listenAddress = StringUtils.stringArg(args, "ajp13ListenAddress", null);
    }

    @Override
    public boolean start() {
        if (this.listenPort < 0) {
            return false;
        } else {
            this.interrupted = false;
            Thread thread = new Thread(this, StringUtils.replaceToken("ConnectorThread:[{}-[#1]]", "ajp13", Integer.toString(this.listenPort)));
            thread.setDaemon(true);
            thread.start();
            return true;
        }
    }

    /**
     * The main run method. This handles the normal thread processing.
     */
    @Override
    public void run() {
        try {
            ServerSocket ss = this.listenAddress == null ? new ServerSocket(this.listenPort, BACKLOG_COUNT) : new ServerSocket(this.listenPort, BACKLOG_COUNT, InetAddress.getByName(this.listenAddress));
            ss.setSoTimeout(LISTENER_TIMEOUT);
            logger.info("AJP13 Listener started: port={}", this.listenPort + "");

            // Enter the main loop
            while (!interrupted) {
                // Get the listener
                Socket s = null;
                try {
                    s = ss.accept();
                } catch (java.io.InterruptedIOException err) {
                    s = null;
                }

                // if we actually got a socket, process it. Otherwise go around
                // again
                if (s != null) {
                    this.objectPool.handleRequest(s, this);
                }
            }

            // Close server socket
            ss.close();
        } catch (Throwable err) {
            logger.error("Error during AJP13 listener init or shutdown", err);
        }

        logger.info("AJP13 Listener shutdown successfully");
    }

    /**
     * Interrupts the listener thread. This will trigger a listener shutdown once the so timeout has passed.
     */
    @Override
    public void destroy() {
        this.interrupted = true;
    }

    /**
     * Called by the request handler thread, because it needs specific setup code for this connection's protocol (ie construction of
     * request/response objects, in/out streams, etc). This implementation parses incoming AJP13 packets, and builds an outputstream that is
     * capable of writing back the response in AJP13 packets.
     */
    @Override
    public void allocateRequestResponse(Socket socket, InputStream inSocket, OutputStream outSocket, RequestHandlerThread handler, boolean iAmFirst) throws SocketException, IOException {
        WinstoneRequest request = this.objectPool.getRequestFromPool();
        WinstoneResponse response = this.objectPool.getResponseFromPool();
        response.setRequest(request);
        request.setHostGroup(this.hostGroup);
        // rsp.updateContentTypeHeader("text/html");
        handler.setRequest(request);
        handler.setResponse(response);

        if (iAmFirst || (KEEP_ALIVE_TIMEOUT == -1)) {
            socket.setSoTimeout(CONNECTION_TIMEOUT);
        }
        // Dead Code
        // else {
        // deallocateRequestResponse(handler, request, response, null, null);
        // }
        // else
        // socket.setSoTimeout(KEEP_ALIVE_TIMEOUT);
        Ajp13IncomingPacket headers = null;
        try {
            headers = new Ajp13IncomingPacket(inSocket, handler);
        } catch (InterruptedIOException err) {
            deallocateRequestResponse(handler, request, response, null, null);
            // keep alive timeout ? ignore if not first
            if (iAmFirst) {
                throw err;
            } else {
                return;
            }
        } catch (WinstoneException err) {
            deallocateRequestResponse(handler, request, response, null, null);
            throw err;
        } finally {
            try {<commit_msg>clean up import and remove bad usage<commit_after>/*
 * Copyright 2003-2006 <NAME> <winstone-devel at lists sourceforge net>
 * Distributed under the terms of either:
 * - the common development and distribution license (CDDL), v1.0; or
 * - the GNU Lesser General Public License, v2.1 or later
 */
package net.winstone.core.listener;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import net.winstone.WinstoneException;
import net.winstone.core.HostGroup;
import net.winstone.core.ObjectPool;
import net.winstone.core.WinstoneInputStream;
import net.winstone.core.WinstoneOutputStream;
import net.winstone.core.WinstoneRequest;
import net.winstone.core.WinstoneResponse;
import net.winstone.core.authentication.AuthenticationPrincipal;
import net.winstone.util.StringUtils;

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

/**
 * Implements the main listener daemon thread. This is the class that gets launched by the command line, and owns the server socket, etc.
 * 
 * @author mailto: <a href="<EMAIL>"><NAME></a>
 * @version $Id: Ajp13Listener.java,v 1.13 2008/09/05 02:39:47 rickknowles Exp $
 */
public class Ajp13Listener implements Listener, Runnable {

    protected static Logger logger = LoggerFactory.getLogger(Ajp13Listener.class);
    private final static int LISTENER_TIMEOUT = 5000; // every 5s reset the listener socket
    private final static int DEFAULT_PORT = 8009;
    private final static int CONNECTION_TIMEOUT = 60000;
    private final static int BACKLOG_COUNT = 1000;
    // private final static int KEEP_ALIVE_TIMEOUT = -1;
    // private final static int KEEP_ALIVE_SLEEP = 50;
    // private final static int KEEP_ALIVE_SLEEP_MAX = 500;
    private final static String TEMPORARY_URL_STASH = "winstone.ajp13.TemporaryURLAttribute";
    private final HostGroup hostGroup;
    private final ObjectPool objectPool;
    private final int listenPort;
    private boolean interrupted;
    private final String listenAddress;

    /**
     * Constructor
     */
    public Ajp13Listener(final Map<String, String> args, final ObjectPool objectPool, final HostGroup hostGroup) {
        // Load resources
        this.hostGroup = hostGroup;
        this.objectPool = objectPool;

        this.listenPort = Integer.parseInt(StringUtils.stringArg(args, "ajp13Port", "" + DEFAULT_PORT));
        this.listenAddress = StringUtils.stringArg(args, "ajp13ListenAddress", null);
    }

    @Override
    public boolean start() {
        if (this.listenPort < 0) {
            return false;
        } else {
            this.interrupted = false;
            Thread thread = new Thread(this, StringUtils.replaceToken("ConnectorThread:[{}-[#1]]", "ajp13", Integer.toString(this.listenPort)));
            thread.setDaemon(true);
            thread.start();
            return true;
        }
    }

    /**
     * The main run method. This handles the normal thread processing.
     */
    @Override
    public void run() {
        try {
            ServerSocket ss = this.listenAddress == null ? new ServerSocket(this.listenPort, BACKLOG_COUNT) : new ServerSocket(this.listenPort, BACKLOG_COUNT, InetAddress.getByName(this.listenAddress));
            ss.setSoTimeout(LISTENER_TIMEOUT);
            logger.info("AJP13 Listener started: port={}", this.listenPort + "");

            // Enter the main loop
            while (!interrupted) {
                // Get the listener
                Socket s = null;
                try {
                    s = ss.accept();
                } catch (java.io.InterruptedIOException err) {
                    s = null;
                }

                // if we actually got a socket, process it. Otherwise go around
                // again
                if (s != null) {
                    this.objectPool.handleRequest(s, this);
                }
            }

            // Close server socket
            ss.close();
        } catch (Throwable err) {
            logger.error("Error during AJP13 listener init or shutdown", err);
        }

        logger.info("AJP13 Listener shutdown successfully");
    }

    /**
     * Interrupts the listener thread. This will trigger a listener shutdown once the so timeout has passed.
     */
    @Override
    public void destroy() {
        this.interrupted = true;
    }

    /**
     * Called by the request handler thread, because it needs specific setup code for this connection's protocol (ie construction of
     * request/response objects, in/out streams, etc). This implementation parses incoming AJP13 packets, and builds an outputstream that is
     * capable of writing back the response in AJP13 packets.
     */
    @Override
    public void allocateRequestResponse(Socket socket, InputStream inSocket, OutputStream outSocket, RequestHandlerThread handler, boolean iAmFirst) throws SocketException, IOException {
        WinstoneRequest request = this.objectPool.getRequestFromPool();
        WinstoneResponse response = this.objectPool.getResponseFromPool();
        response.setRequest(request);
        request.setHostGroup(this.hostGroup);
        // rsp.updateContentTypeHeader("text/html");
        handler.setRequest(request);
        handler.setResponse(response);

        if (iAmFirst) {
            socket.setSoTimeout(CONNECTION_TIMEOUT);
        }
        // Dead Code
        // else {
        // deallocateRequestResponse(handler, request, response, null, null);
        // }
        // else
        // socket.setSoTimeout(KEEP_ALIVE_TIMEOUT);
        Ajp13IncomingPacket headers = null;
        try {
            headers = new Ajp13IncomingPacket(inSocket, handler);
        } catch (InterruptedIOException err) {
            deallocateRequestResponse(handler, request, response, null, null);
            // keep alive timeout ? ignore if not first
            if (iAmFirst) {
                throw err;
            } else {
                return;
            }
        } catch (WinstoneException err) {
            deallocateRequestResponse(handler, request, response, null, null);
            throw err;
        } finally {
            try {
{'fraction_non_alphanumeric': 0.0895737109108806, 'fraction_numerical': 0.01370485348678731, 'mean_word_length': 2.645597571073696, 'pattern_counts': {'":': 0, '<': 19, '<?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': '5273275', 'n_tokens_mistral': 3713, 'n_tokens_neox': 3478, 'n_words': 996}