1/*
2 * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package com.sun.net.httpserver;
27
28import java.net.*;
29import java.io.*;
30import java.nio.*;
31import java.security.*;
32import java.nio.channels.*;
33import java.util.*;
34import java.util.concurrent.*;
35import javax.net.ssl.*;
36import com.sun.net.httpserver.spi.HttpServerProvider;
37
38/**
39 * This class implements a simple HTTP server. A HttpServer is bound to an IP address
40 * and port number and listens for incoming TCP connections from clients on this address.
41 * The sub-class {@link HttpsServer} implements a server which handles HTTPS requests.
42 * <p>
43 * One or more {@link HttpHandler} objects must be associated with a server
44 * in order to process requests. Each such HttpHandler is registered
45 * with a root URI path which represents the
46 * location of the application or service on this server. The mapping of a handler
47 * to a HttpServer is encapsulated by a {@link HttpContext} object. HttpContexts
48 * are created by calling {@link #createContext(String,HttpHandler)}.
49 * Any request for which no handler can be found is rejected with a 404 response.
50 * Management of threads can be done external to this object by providing a
51 * {@link java.util.concurrent.Executor} object. If none is provided a default
52 * implementation is used.
53 * <p>
54 * <a id="mapping_description"></a>
55 * <b>Mapping request URIs to HttpContext paths</b><p>
56 * When a HTTP request is received,
57 * the appropriate HttpContext (and handler) is located by finding the context
58 * whose path is the longest matching prefix of the request URI's path.
59 * Paths are matched literally, which means that the strings are compared
60 * case sensitively, and with no conversion to or from any encoded forms.
61 * For example. Given a HttpServer with the following HttpContexts configured.
62 * <table class="striped"><caption style="display:none">description</caption>
63 * <thead>
64 * <tr><th scope="col"><i>Context</i></th><th scope="col"><i>Context path</i></th></tr>
65 * </thead>
66 * <tbody>
67 * <tr><th scope="row">ctx1</th><td>"/"</td></tr>
68 * <tr><th scope="row">ctx2</th><td>"/apps/"</td></tr>
69 * <tr><th scope="row">ctx3</th><td>"/apps/foo/"</td></tr>
70 * </tbody>
71 * </table>
72 * <p>
73 * the following table shows some request URIs and which, if any context they would
74 * match with.
75 * <table class="striped"><caption style="display:none">description</caption>
76 * <thead>
77 * <tr><th scope="col"><i>Request URI</i></th><th scope="col"><i>Matches context</i></th></tr>
78 * </thead>
79 * <tbody>
80 * <tr><th scope="row">"http://foo.com/apps/foo/bar"</th><td>ctx3</td></tr>
81 * <tr><th scope="row">"http://foo.com/apps/Foo/bar"</th><td>no match, wrong case</td></tr>
82 * <tr><th scope="row">"http://foo.com/apps/app1"</th><td>ctx2</td></tr>
83 * <tr><th scope="row">"http://foo.com/foo"</th><td>ctx1</td></tr>
84 * </tbody>
85 * </table>
86 * <p>
87 * <b>Note about socket backlogs</b><p>
88 * When binding to an address and port number, the application can also specify an integer
89 * <i>backlog</i> parameter. This represents the maximum number of incoming TCP connections
90 * which the system will queue internally. Connections are queued while they are waiting to
91 * be accepted by the HttpServer. When the limit is reached, further connections may be
92 * rejected (or possibly ignored) by the underlying TCP implementation. Setting the right
93 * backlog value is a compromise between efficient resource usage in the TCP layer (not setting
94 * it too high) and allowing adequate throughput of incoming requests (not setting it too low).
95 * @since 1.6
96 */
97
98public abstract class HttpServer {
99
100    /**
101     */
102    protected HttpServer () {
103    }
104
105    /**
106     * creates a HttpServer instance which is initially not bound to any local address/port.
107     * The HttpServer is acquired from the currently installed {@link HttpServerProvider}
108     * The server must be bound using {@link #bind(InetSocketAddress,int)} before it can be used.
109     * @throws IOException
110     */
111    public static HttpServer create () throws IOException {
112        return create (null, 0);
113    }
114
115    /**
116     * Create a <code>HttpServer</code> instance which will bind to the
117     * specified {@link java.net.InetSocketAddress} (IP address and port number)
118     *
119     * A maximum backlog can also be specified. This is the maximum number of
120     * queued incoming connections to allow on the listening socket.
121     * Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
122     * The HttpServer is acquired from the currently installed {@link HttpServerProvider}
123     *
124     * @param addr the address to listen on, if <code>null</code> then bind() must be called
125     *  to set the address
126     * @param backlog the socket backlog. If this value is less than or equal to zero,
127     *          then a system default value is used.
128     * @throws BindException if the server cannot bind to the requested address,
129     *          or if the server is already bound.
130     * @throws IOException
131     */
132
133    public static HttpServer create (
134        InetSocketAddress addr, int backlog
135    ) throws IOException {
136        HttpServerProvider provider = HttpServerProvider.provider();
137        return provider.createHttpServer (addr, backlog);
138    }
139
140    /**
141     * Binds a currently unbound HttpServer to the given address and port number.
142     * A maximum backlog can also be specified. This is the maximum number of
143     * queued incoming connections to allow on the listening socket.
144     * Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
145     * @param addr the address to listen on
146     * @param backlog the socket backlog. If this value is less than or equal to zero,
147     *          then a system default value is used.
148     * @throws BindException if the server cannot bind to the requested address or if the server
149     *          is already bound.
150     * @throws NullPointerException if addr is <code>null</code>
151     */
152    public abstract void bind (InetSocketAddress addr, int backlog) throws IOException;
153
154    /**
155     * Starts this server in a new background thread. The background thread
156     * inherits the priority, thread group and context class loader
157     * of the caller.
158     */
159    public abstract void start () ;
160
161    /**
162     * sets this server's {@link java.util.concurrent.Executor} object. An
163     * Executor must be established before {@link #start()} is called.
164     * All HTTP requests are handled in tasks given to the executor.
165     * If this method is not called (before start()) or if it is
166     * called with a <code>null</code> Executor, then
167     * a default implementation is used, which uses the thread
168     * which was created by the {@link #start()} method.
169     * @param executor the Executor to set, or <code>null</code> for  default
170     *          implementation
171     * @throws IllegalStateException if the server is already started
172     */
173    public abstract void setExecutor (Executor executor);
174
175
176    /**
177     * returns this server's Executor object if one was specified with
178     * {@link #setExecutor(Executor)}, or <code>null</code> if none was
179     * specified.
180     * @return the Executor established for this server or <code>null</code> if not set.
181     */
182    public abstract Executor getExecutor () ;
183
184    /**
185     * stops this server by closing the listening socket and disallowing
186     * any new exchanges from being processed. The method will then block
187     * until all current exchange handlers have completed or else when
188     * approximately <i>delay</i> seconds have elapsed (whichever happens
189     * sooner). Then, all open TCP connections are closed, the background
190     * thread created by start() exits, and the method returns.
191     * Once stopped, a HttpServer cannot be re-used.
192     *
193     * @param delay the maximum time in seconds to wait until exchanges have finished.
194     * @throws IllegalArgumentException if delay is less than zero.
195     */
196    public abstract void stop (int delay);
197
198    /**
199     * Creates a HttpContext. A HttpContext represents a mapping from a
200     * URI path to a exchange handler on this HttpServer. Once created, all requests
201     * received by the server for the path will be handled by calling
202     * the given handler object. The context is identified by the path, and
203     * can later be removed from the server using this with the {@link #removeContext(String)} method.
204     * <p>
205     * The path specifies the root URI path for this context. The first character of path must be
206     * '/'. <p>
207     * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
208     * to HttpContext instances.
209     * @param path the root URI path to associate the context with
210     * @param handler the handler to invoke for incoming requests.
211     * @throws IllegalArgumentException if path is invalid, or if a context
212     *          already exists for this path
213     * @throws NullPointerException if either path, or handler are <code>null</code>
214     */
215    public abstract HttpContext createContext (String path, HttpHandler handler) ;
216
217    /**
218     * Creates a HttpContext without initially specifying a handler. The handler must later be specified using
219     * {@link HttpContext#setHandler(HttpHandler)}.  A HttpContext represents a mapping from a
220     * URI path to an exchange handler on this HttpServer. Once created, and when
221     * the handler has been set, all requests
222     * received by the server for the path will be handled by calling
223     * the handler object. The context is identified by the path, and
224     * can later be removed from the server using this with the {@link #removeContext(String)} method.
225     * <p>
226     * The path specifies the root URI path for this context. The first character of path must be
227     * '/'. <p>
228     * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
229     * to HttpContext instances.
230     * @param path the root URI path to associate the context with
231     * @throws IllegalArgumentException if path is invalid, or if a context
232     *          already exists for this path
233     * @throws NullPointerException if path is <code>null</code>
234     */
235    public abstract HttpContext createContext (String path) ;
236
237    /**
238     * Removes the context identified by the given path from the server.
239     * Removing a context does not affect exchanges currently being processed
240     * but prevents new ones from being accepted.
241     * @param path the path of the handler to remove
242     * @throws IllegalArgumentException if no handler corresponding to this
243     *          path exists.
244     * @throws NullPointerException if path is <code>null</code>
245     */
246    public abstract void removeContext (String path) throws IllegalArgumentException ;
247
248    /**
249     * Removes the given context from the server.
250     * Removing a context does not affect exchanges currently being processed
251     * but prevents new ones from being accepted.
252     * @param context the context to remove
253     * @throws NullPointerException if context is <code>null</code>
254     */
255    public abstract void removeContext (HttpContext context) ;
256
257    /**
258     * returns the address this server is listening on
259     * @return the address/port number the server is listening on
260     */
261    public abstract InetSocketAddress getAddress() ;
262}
263