<commit_before>package org.apache.xmlrpc;

/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "XML-RPC" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact <EMAIL>.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.EmptyStackException;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * A minimal web server that exclusively handles XML-RPC requests.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Id$
 */
public class WebServer implements Runnable
{
    protected XmlRpcServer xmlrpc;

    protected ServerSocket serverSocket;
    protected Thread listener;
    protected Vector accept, deny;
    protected Stack threadpool;
    protected ThreadGroup runners;

    // Inputs to setupServerSocket()
    private InetAddress address;
    private int port;

    private boolean paranoid;

    protected static final byte[] ctype =
        toHTTPBytes("Content-Type: text/xml\r\n");
    protected static final byte[] clength =
        toHTTPBytes("Content-Length: ");
    protected static final byte[] newline = toHTTPBytes("\r\n");
    protected static final byte[] doubleNewline = toHTTPBytes("\r\n\r\n");
    protected static final byte[] conkeep =
        toHTTPBytes("Connection: Keep-Alive\r\n");
    protected static final byte[] conclose =
        toHTTPBytes("Connection: close\r\n");
    protected static final byte[] ok = toHTTPBytes(" 200 OK\r\n");
    protected static final byte[] server =
        toHTTPBytes("Server: Apache XML-RPC 1.0\r\n");

    private static final String HTTP_11 = "HTTP/1.1";
    private static final String STAR = "*";

    /**
     * This <em>can</em> be called from command line, but you'll have to edit
     * and recompile to change the server port or handler objects. By default,
     * it sets up the following responders:
     * <ul>
     *   <li> A java.lang.String object </li>
     *   <li> The java.lang.Math class (making its static methods callable via
     *        XML-RPC) </li>
     *   <li> An Echo handler that returns the argument array </li>
     * </ul>
     *
     * @see #addDefaultHandlers()
     */
    public static void main(String[] argv)
    {
        int p = determinePort(argv, 8080);
        // XmlRpc.setDebug (true);
        XmlRpc.setKeepAlive(true);
        WebServer webserver = new WebServer(p);

        try
        {
            webserver.addDefaultHandlers();
            webserver.start();
        }
        catch (Exception e)
        {
            System.err.println("Error running web server");
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Examines command line arguments from <code>argv</code>.  If a
     * port may have been provided, parses that port (exiting with
     * error status if the port cannot be parsed).  If no port is
     * specified, defaults to <code>defaultPort</code>.
     *
     * @param defaultPort The port to use if none was specified.
     */
    protected static int determinePort(String[] argv, int defaultPort)
    {
        int port = defaultPort;
        if (argv.length > 0)
        {
            try
            {
                port = Integer.parseInt(argv[0]);
            }
            catch (NumberFormatException nfx)
            {
                System.err.println("Error parsing port number: " + argv[0]);
                System.err.println("Usage: java " + WebServer.class.getName()
                                   + " [port]");
                System.exit(1);
            }
        }
        return port;
    }

    /**
     * Creates a Web server at the specified port number.
     */
    public WebServer(int port)
    {
        this(port, null);
    }

    /**
     * Creates a Web server at the specified port number and IP address.
     */
    public WebServer(int port, InetAddress addr)
    {
        this.address = addr;
        this.port = port;
        xmlrpc = new XmlRpcServer();
        accept = new Vector();
        deny = new Vector();
        threadpool = new Stack();
        runners = new ThreadGroup("XML-RPC Runner");
    }

    /**
     * Returns the US-ASCII encoded byte representation of text for
     * HTTP use (as per section 2.2 of RFC 2068).
     */
    protected static final byte[] toHTTPBytes(String text)
    {
        try
        {
            return text.getBytes("US-ASCII");
        }
        catch (UnsupportedEncodingException e)
        {
            throw new Error(e.getMessage() +
                            ": HTTP requires US-ASCII encoding");
        }
    }

    /**
     * Factory method to manufacture the server socket.  Useful as a
     * hook method for subclasses to override when they desire
     * different flavor of socket (i.e. a <code>SSLServerSocket</code>).
     *
     * @exception Exception Error creating listener socket.
     */
    protected ServerSocket createServerSocket(int port, int backlog,
            InetAddress addr)
            throws Exception
    {
        return new ServerSocket(port, backlog, addr);
    }

    /**
     * Initializes this server's listener socket with the specified
     * attributes, assuring that a socket timeout has been set.  The
     * {@link #createServerSocket(int, int, InetAddress)} method can
     * be overridden to change the flavor of socket used.
     *
     * @see #createServerSocket(int, int, InetAddress)
     */
    private synchronized void setupServerSocket(int backlog)
            throws Exception
    {
        InetAddress addr = address;
        if (addr == null)
        {
            addr = InetAddress.getLocalHost();
        }

        // Since we can't reliably set SO_REUSEADDR until JDK 1.4 is
        // the standard, try to (re-)open the server socket several
        // times.  Some OSes (Linux and Solaris, for example), hold on
        // to listener sockets for a brief period of time for security
        // reasons before relinquishing their hold.
        int attempt = 1;
        while (serverSocket == null)
        {
            try
            {
                serverSocket = createServerSocket(port, backlog, addr);
            }
            catch (BindException e)
            {
                if (attempt == 10)
                {
                    throw e;
                }

                attempt++;
                Thread.sleep(1000);
            }
        }


        if (XmlRpc.debug)
        {
            StringBuffer msg = new StringBuffer();
            msg.append("Opened XML-RPC server socket for ");
            msg.append(addr.getHostName()).append(':').append(port);
            if (attempt > 1)
            {
                msg.append(" after ").append(attempt).append(" tries");
            }
            System.out.println(msg.toString());
        }

        // A socket timeout must be set.
        if (serverSocket.getSoTimeout() <= 0)
        {
            serverSocket.setSoTimeout(4096);
        }
    }

    /**
     * Spawns a new thread which binds this server to the port it's
     * configured to accept connections on.
     *
     * @see #run()
     */
    public void start()
    {
        // The listener reference is released upon shutdown().
        if (listener == null)
        {
            listener = new Thread(this, "XML-RPC Weblistener");
            // Not marked as daemon thread since run directly via main().
            listener.start();
        }
    }

    /**
     * Register a handler object with this name. Methods of this objects will be
     * callable over XML-RPC as "name.method".
     */
    public void addHandler(String name, Object target)
    {
        xmlrpc.addHandler(name, target);
    }

    /**
     * Adds the bundled handlers to the server.  Called by {@link
     * #main(String[])}.
     */
    protected void addDefaultHandlers()
        throws Exception
    {
        // webserver.setParanoid (true);
        // webserver.acceptClient ("192.168.*.*");
        addHandler("string", "Welcome to XML-RPC!");
        addHandler("math", Math.class);
        addHandler("auth", new AuthDemo());
        addHandler("$default", new Echo());
        // XmlRpcClients can be used as Proxies in XmlRpcServers which is a
        // cool feature for applets.
        String url = "http://www.mailtothefuture.com:80/RPC2";
        addHandler("mttf", new XmlRpcClient(url));
    }

    /**
     * Remove a handler object that was previously registered with this server.
     */
    public void removeHandler(String name)<commit_msg>addDefaultHandlers(): Added <NAME>'s <<EMAIL>> SystemHandler as a default handler.<commit_after>package org.apache.xmlrpc;

/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "XML-RPC" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact <EMAIL>.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.EmptyStackException;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * A minimal web server that exclusively handles XML-RPC requests.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Id$
 */
public class WebServer implements Runnable
{
    protected XmlRpcServer xmlrpc;

    protected ServerSocket serverSocket;
    protected Thread listener;
    protected Vector accept, deny;
    protected Stack threadpool;
    protected ThreadGroup runners;

    // Inputs to setupServerSocket()
    private InetAddress address;
    private int port;

    private boolean paranoid;

    protected static final byte[] ctype =
        toHTTPBytes("Content-Type: text/xml\r\n");
    protected static final byte[] clength =
        toHTTPBytes("Content-Length: ");
    protected static final byte[] newline = toHTTPBytes("\r\n");
    protected static final byte[] doubleNewline = toHTTPBytes("\r\n\r\n");
    protected static final byte[] conkeep =
        toHTTPBytes("Connection: Keep-Alive\r\n");
    protected static final byte[] conclose =
        toHTTPBytes("Connection: close\r\n");
    protected static final byte[] ok = toHTTPBytes(" 200 OK\r\n");
    protected static final byte[] server =
        toHTTPBytes("Server: Apache XML-RPC 1.0\r\n");

    private static final String HTTP_11 = "HTTP/1.1";
    private static final String STAR = "*";

    /**
     * This <em>can</em> be called from command line, but you'll have to edit
     * and recompile to change the server port or handler objects. By default,
     * it sets up the following responders:
     * <ul>
     *   <li> A java.lang.String object </li>
     *   <li> The java.lang.Math class (making its static methods callable via
     *        XML-RPC) </li>
     *   <li> An Echo handler that returns the argument array </li>
     * </ul>
     *
     * @see #addDefaultHandlers()
     */
    public static void main(String[] argv)
    {
        int p = determinePort(argv, 8080);
        // XmlRpc.setDebug (true);
        XmlRpc.setKeepAlive(true);
        WebServer webserver = new WebServer(p);

        try
        {
            webserver.addDefaultHandlers();
            webserver.start();
        }
        catch (Exception e)
        {
            System.err.println("Error running web server");
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Examines command line arguments from <code>argv</code>.  If a
     * port may have been provided, parses that port (exiting with
     * error status if the port cannot be parsed).  If no port is
     * specified, defaults to <code>defaultPort</code>.
     *
     * @param defaultPort The port to use if none was specified.
     */
    protected static int determinePort(String[] argv, int defaultPort)
    {
        int port = defaultPort;
        if (argv.length > 0)
        {
            try
            {
                port = Integer.parseInt(argv[0]);
            }
            catch (NumberFormatException nfx)
            {
                System.err.println("Error parsing port number: " + argv[0]);
                System.err.println("Usage: java " + WebServer.class.getName()
                                   + " [port]");
                System.exit(1);
            }
        }
        return port;
    }

    /**
     * Creates a Web server at the specified port number.
     */
    public WebServer(int port)
    {
        this(port, null);
    }

    /**
     * Creates a Web server at the specified port number and IP address.
     */
    public WebServer(int port, InetAddress addr)
    {
        this.address = addr;
        this.port = port;
        xmlrpc = new XmlRpcServer();
        accept = new Vector();
        deny = new Vector();
        threadpool = new Stack();
        runners = new ThreadGroup("XML-RPC Runner");
    }

    /**
     * Returns the US-ASCII encoded byte representation of text for
     * HTTP use (as per section 2.2 of RFC 2068).
     */
    protected static final byte[] toHTTPBytes(String text)
    {
        try
        {
            return text.getBytes("US-ASCII");
        }
        catch (UnsupportedEncodingException e)
        {
            throw new Error(e.getMessage() +
                            ": HTTP requires US-ASCII encoding");
        }
    }

    /**
     * Factory method to manufacture the server socket.  Useful as a
     * hook method for subclasses to override when they desire
     * different flavor of socket (i.e. a <code>SSLServerSocket</code>).
     *
     * @exception Exception Error creating listener socket.
     */
    protected ServerSocket createServerSocket(int port, int backlog,
            InetAddress addr)
            throws Exception
    {
        return new ServerSocket(port, backlog, addr);
    }

    /**
     * Initializes this server's listener socket with the specified
     * attributes, assuring that a socket timeout has been set.  The
     * {@link #createServerSocket(int, int, InetAddress)} method can
     * be overridden to change the flavor of socket used.
     *
     * @see #createServerSocket(int, int, InetAddress)
     */
    private synchronized void setupServerSocket(int backlog)
            throws Exception
    {
        InetAddress addr = address;
        if (addr == null)
        {
            addr = InetAddress.getLocalHost();
        }

        // Since we can't reliably set SO_REUSEADDR until JDK 1.4 is
        // the standard, try to (re-)open the server socket several
        // times.  Some OSes (Linux and Solaris, for example), hold on
        // to listener sockets for a brief period of time for security
        // reasons before relinquishing their hold.
        int attempt = 1;
        while (serverSocket == null)
        {
            try
            {
                serverSocket = createServerSocket(port, backlog, addr);
            }
            catch (BindException e)
            {
                if (attempt == 10)
                {
                    throw e;
                }

                attempt++;
                Thread.sleep(1000);
            }
        }


        if (XmlRpc.debug)
        {
            StringBuffer msg = new StringBuffer();
            msg.append("Opened XML-RPC server socket for ");
            msg.append(addr.getHostName()).append(':').append(port);
            if (attempt > 1)
            {
                msg.append(" after ").append(attempt).append(" tries");
            }
            System.out.println(msg.toString());
        }

        // A socket timeout must be set.
        if (serverSocket.getSoTimeout() <= 0)
        {
            serverSocket.setSoTimeout(4096);
        }
    }

    /**
     * Spawns a new thread which binds this server to the port it's
     * configured to accept connections on.
     *
     * @see #run()
     */
    public void start()
    {
        // The listener reference is released upon shutdown().
        if (listener == null)
        {
            listener = new Thread(this, "XML-RPC Weblistener");
            // Not marked as daemon thread since run directly via main().
            listener.start();
        }
    }

    /**
     * Register a handler object with this name. Methods of this objects will be
     * callable over XML-RPC as "name.method".
     */
    public void addHandler(String name, Object target)
    {
        xmlrpc.addHandler(name, target);
    }

    /**
     * Adds the bundled handlers to the server.  Called by {@link
     * #main(String[])}.
     */
    protected void addDefaultHandlers()
        throws Exception
    {
        // webserver.setParanoid (true);
        // webserver.acceptClient ("192.168.*.*");
        addHandler("string", "Welcome to XML-RPC!");
        addHandler("math", Math.class);
        addHandler("auth", new AuthDemo());
        addHandler("$default", new Echo());
        // XmlRpcClients can be used as Proxies in XmlRpcServers which is a
        // cool feature for applets.
        String url = "http://www.mailtothefuture.com:80/RPC2";
        addHandler("mttf", new XmlRpcClient(url));
        addHandler("system", new SystemHandler(xmlrpc));
    }

    /**
     * Remove a handler object that was previously registered with this server.
     */
    public void removeHandler(String name)
{'fraction_non_alphanumeric': 0.10025582215949189, 'fraction_numerical': 0.005204657727593508, 'mean_word_length': 2.2769186298598063, 'pattern_counts': {'":': 2, '<': 68, '<?xml version=': 0, '>': 70, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 11}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7379654', 'n_tokens_mistral': 6173, 'n_tokens_neox': 5838, 'n_words': 2144}