feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,129 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* Authenticator represents an implementation of an HTTP authentication
* mechanism. Sub-classes provide implementations of specific mechanisms
* such as Digest or Basic auth. Instances are invoked to provide verification
* of the authentication information provided in all incoming requests.
* Note. This implies that any caching of credentials or other authentication
* information must be done outside of this class.
*/
@jdk.Exported
public abstract class Authenticator {
/**
* Base class for return type from authenticate() method
*/
public abstract static class Result {}
/**
* Indicates an authentication failure. The authentication
* attempt has completed.
*/
@jdk.Exported
public static class Failure extends Result {
private int responseCode;
public Failure (int responseCode) {
this.responseCode = responseCode;
}
/**
* returns the response code to send to the client
*/
public int getResponseCode() {
return responseCode;
}
}
/**
* Indicates an authentication has succeeded and the
* authenticated user principal can be acquired by calling
* getPrincipal().
*/
@jdk.Exported
public static class Success extends Result {
private HttpPrincipal principal;
public Success (HttpPrincipal p) {
principal = p;
}
/**
* returns the authenticated user Principal
*/
public HttpPrincipal getPrincipal() {
return principal;
}
}
/**
* Indicates an authentication must be retried. The
* response code to be sent back is as returned from
* getResponseCode(). The Authenticator must also have
* set any necessary response headers in the given HttpExchange
* before returning this Retry object.
*/
@jdk.Exported
public static class Retry extends Result {
private int responseCode;
public Retry (int responseCode) {
this.responseCode = responseCode;
}
/**
* returns the response code to send to the client
*/
public int getResponseCode() {
return responseCode;
}
}
/**
* called to authenticate each incoming request. The implementation
* must return a Failure, Success or Retry object as appropriate :-
* <p>
* Failure means the authentication has completed, but has failed
* due to invalid credentials.
* <p>
* Sucess means that the authentication
* has succeeded, and a Principal object representing the user
* can be retrieved by calling Sucess.getPrincipal() .
* <p>
* Retry means that another HTTP exchange is required. Any response
* headers needing to be sent back to the client are set in the
* given HttpExchange. The response code to be returned must be provided
* in the Retry object. Retry may occur multiple times.
*/
public abstract Result authenticate (HttpExchange exch);
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.util.Base64;
/**
* BasicAuthenticator provides an implementation of HTTP Basic
* authentication. It is an abstract class and must be extended
* to provide an implementation of {@link #checkCredentials(String,String)}
* which is called to verify each incoming request.
*/
@jdk.Exported
public abstract class BasicAuthenticator extends Authenticator {
protected String realm;
/**
* Creates a BasicAuthenticator for the given HTTP realm
* @param realm The HTTP Basic authentication realm
* @throws NullPointerException if the realm is an empty string
*/
public BasicAuthenticator (String realm) {
this.realm = realm;
}
/**
* returns the realm this BasicAuthenticator was created with
* @return the authenticator's realm string.
*/
public String getRealm () {
return realm;
}
public Result authenticate (HttpExchange t)
{
Headers rmap = t.getRequestHeaders();
/*
* look for auth token
*/
String auth = rmap.getFirst ("Authorization");
if (auth == null) {
Headers map = t.getResponseHeaders();
map.set ("WWW-Authenticate", "Basic realm=" + "\""+realm+"\"");
return new Authenticator.Retry (401);
}
int sp = auth.indexOf (' ');
if (sp == -1 || !auth.substring(0, sp).equals ("Basic")) {
return new Authenticator.Failure (401);
}
byte[] b = Base64.getDecoder().decode(auth.substring(sp+1));
String userpass = new String (b);
int colon = userpass.indexOf (':');
String uname = userpass.substring (0, colon);
String pass = userpass.substring (colon+1);
if (checkCredentials (uname, pass)) {
return new Authenticator.Success (
new HttpPrincipal (
uname, realm
)
);
} else {
/* reject the request again with 401 */
Headers map = t.getResponseHeaders();
map.set ("WWW-Authenticate", "Basic realm=" + "\""+realm+"\"");
return new Authenticator.Failure(401);
}
}
/**
* called for each incoming request to verify the
* given name and password in the context of this
* Authenticator's realm. Any caching of credentials
* must be done by the implementation of this method
* @param username the username from the request
* @param password the password from the request
* @return <code>true</code> if the credentials are valid,
* <code>false</code> otherwise.
*/
public abstract boolean checkCredentials (String username, String password);
}

View File

@@ -0,0 +1,121 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.io.IOException;
import java.util.*;
/**
* A filter used to pre- and post-process incoming requests. Pre-processing occurs
* before the application's exchange handler is invoked, and post-processing
* occurs after the exchange handler returns. Filters
* are organised in chains, and are associated with HttpContext instances.
* <p>
* Each Filter in the chain, invokes the next filter within its own
* doFilter() implementation. The final Filter in the chain invokes the applications
* exchange handler.
* @since 1.6
*/
@jdk.Exported
public abstract class Filter {
protected Filter () {}
/**
* a chain of filters associated with a HttpServer.
* Each filter in the chain is given one of these
* so it can invoke the next filter in the chain
*/
@jdk.Exported
public static class Chain {
/* the last element in the chain must invoke the users
* handler
*/
private ListIterator<Filter> iter;
private HttpHandler handler;
public Chain (List<Filter> filters, HttpHandler handler) {
iter = filters.listIterator();
this.handler = handler;
}
/**
* calls the next filter in the chain, or else
* the users exchange handler, if this is the
* final filter in the chain. The Filter may decide
* to terminate the chain, by not calling this method.
* In this case, the filter <b>must</b> send the
* response to the request, because the application's
* exchange handler will not be invoked.
* @param exchange the HttpExchange
* @throws IOException let exceptions pass up the stack
* @throws NullPointerException if exchange is <code>null</code>
*/
public void doFilter (HttpExchange exchange) throws IOException {
if (!iter.hasNext()) {
handler.handle (exchange);
} else {
Filter f = iter.next();
f.doFilter (exchange, this);
}
}
}
/**
* Asks this filter to pre/post-process the given exchange. The filter
* can :-
* <ul><li>examine or modify the request headers</li>
* <li>filter the request body or the response body, by creating suitable
* filter streams and calling
* {@link HttpExchange#setStreams(InputStream,OutputStream)}</li>
* <li>set attribute Objects in the exchange, which other filters or the
* exchange handler can access.</li>
* <li>decide to either :-<ol>
* <li>invoke the next filter in the chain, by calling
* {@link Filter.Chain#doFilter(HttpExchange)}</li>
* <li>terminate the chain of invocation, by <b>not</b> calling
* {@link Filter.Chain#doFilter(HttpExchange)}</li></ol>
* <li>if option 1. above taken, then when doFilter() returns all subsequent
* filters in the Chain have been called, and the response headers can be
* examined or modified.</li>
* <li>if option 2. above taken, then this Filter must use the HttpExchange
* to send back an appropriate response</li></ul><p>
* @param exchange the <code>HttpExchange</code> to be filtered.
* @param chain the Chain which allows the next filter to be invoked.
* @throws IOException may be thrown by any filter module, and if
* caught, must be rethrown again.
* @throws NullPointerException if either exchange or chain are <code>null</code>
*/
public abstract void doFilter (HttpExchange exchange, Chain chain)
throws IOException;
/**
* returns a short description of this Filter
* @return a string describing the Filter
*/
public abstract String description ();
}

View File

@@ -0,0 +1,214 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.util.*;
/**
* HTTP request and response headers are represented by this class which implements
* the interface {@link java.util.Map}&lt;
* {@link java.lang.String},{@link java.util.List}&lt;{@link java.lang.String}&gt;&gt;.
* The keys are case-insensitive Strings representing the header names and
* the value associated with each key is a {@link List}&lt;{@link String}&gt; with one
* element for each occurrence of the header name in the request or response.
* <p>
* For example, if a response header instance contains one key "HeaderName" with two values "value1 and value2"
* then this object is output as two header lines:
* <blockquote><pre>
* HeaderName: value1
* HeaderName: value2
* </blockquote></pre>
* <p>
* All the normal {@link java.util.Map} methods are provided, but the following
* additional convenience methods are most likely to be used:
* <ul>
* <li>{@link #getFirst(String)} returns a single valued header or the first value of
* a multi-valued header.</li>
* <li>{@link #add(String,String)} adds the given header value to the list for the given key</li>
* <li>{@link #set(String,String)} sets the given header field to the single value given
* overwriting any existing values in the value list.
* </ul><p>
* All methods in this class accept <code>null</code> values for keys and values. However, null
* keys will never will be present in HTTP request headers, and will not be output/sent in response headers.
* Null values can be represented as either a null entry for the key (i.e. the list is null) or
* where the key has a list, but one (or more) of the list's values is null. Null values are output
* as a header line containing the key but no associated value.
* @since 1.6
*/
@jdk.Exported
public class Headers implements Map<String,List<String>> {
HashMap<String,List<String>> map;
public Headers () {map = new HashMap<String,List<String>>(32);}
/* Normalize the key by converting to following form.
* First char upper case, rest lower case.
* key is presumed to be ASCII
*/
private String normalize (String key) {
if (key == null) {
return null;
}
int len = key.length();
if (len == 0) {
return key;
}
char[] b = key.toCharArray();
if (b[0] >= 'a' && b[0] <= 'z') {
b[0] = (char)(b[0] - ('a' - 'A'));
} else if (b[0] == '\r' || b[0] == '\n')
throw new IllegalArgumentException("illegal character in key");
for (int i=1; i<len; i++) {
if (b[i] >= 'A' && b[i] <= 'Z') {
b[i] = (char) (b[i] + ('a' - 'A'));
} else if (b[i] == '\r' || b[i] == '\n')
throw new IllegalArgumentException("illegal character in key");
}
return new String(b);
}
public int size() {return map.size();}
public boolean isEmpty() {return map.isEmpty();}
public boolean containsKey(Object key) {
if (key == null) {
return false;
}
if (!(key instanceof String)) {
return false;
}
return map.containsKey (normalize((String)key));
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public List<String> get(Object key) {
return map.get(normalize((String)key));
}
/**
* returns the first value from the List of String values
* for the given key (if at least one exists).
* @param key the key to search for
* @return the first string value associated with the key
*/
public String getFirst (String key) {
List<String> l = map.get(normalize(key));
if (l == null) {
return null;
}
return l.get(0);
}
public List<String> put(String key, List<String> value) {
for (String v : value)
checkValue(v);
return map.put (normalize(key), value);
}
/**
* adds the given value to the list of headers
* for the given key. If the mapping does not
* already exist, then it is created
* @param key the header name
* @param value the header value to add to the header
*/
public void add (String key, String value) {
checkValue(value);
String k = normalize(key);
List<String> l = map.get(k);
if (l == null) {
l = new LinkedList<String>();
map.put(k,l);
}
l.add (value);
}
private static void checkValue(String value) {
int len = value.length();
for (int i=0; i<len; i++) {
char c = value.charAt(i);
if (c == '\r') {
// is allowed if it is followed by \n and a whitespace char
if (i >= len - 2) {
throw new IllegalArgumentException("Illegal CR found in header");
}
char c1 = value.charAt(i+1);
char c2 = value.charAt(i+2);
if (c1 != '\n') {
throw new IllegalArgumentException("Illegal char found after CR in header");
}
if (c2 != ' ' && c2 != '\t') {
throw new IllegalArgumentException("No whitespace found after CRLF in header");
}
i+=2;
} else if (c == '\n') {
throw new IllegalArgumentException("Illegal LF found in header");
}
}
}
/**
* sets the given value as the sole header value
* for the given key. If the mapping does not
* already exist, then it is created
* @param key the header name
* @param value the header value to set.
*/
public void set (String key, String value) {
LinkedList<String> l = new LinkedList<String>();
l.add (value);
put (key, l);
}
public List<String> remove(Object key) {
return map.remove(normalize((String)key));
}
public void putAll(Map<? extends String,? extends List<String>> t) {
map.putAll (t);
}
public void clear() {map.clear();}
public Set<String> keySet() {return map.keySet();}
public Collection<List<String>> values() {return map.values();}
public Set<Map.Entry<String, List<String>>> entrySet() {
return map.entrySet();
}
public boolean equals(Object o) {return map.equals(o);}
public int hashCode() {return map.hashCode();}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* HttpContext represents a mapping between the root URI path of an application
* to a {@link HttpHandler} which is invoked to handle requests destined
* for that path on the associated HttpServer or HttpsServer.
* <p>
* HttpContext instances are created by the create methods in HttpServer
* and HttpsServer
* <p>
* A chain of {@link Filter} objects can be added to a HttpContext. All exchanges processed by the
* context can be pre- and post-processed by each Filter in the chain.
* @since 1.6
*/
@jdk.Exported
public abstract class HttpContext {
protected HttpContext () {
}
/**
* returns the handler for this context
* @return the HttpHandler for this context
*/
public abstract HttpHandler getHandler () ;
/**
* Sets the handler for this context, if not already set.
* @param h the handler to set for this context
* @throws IllegalArgumentException if this context's handler is already set.
* @throws NullPointerException if handler is <code>null</code>
*/
public abstract void setHandler (HttpHandler h) ;
/**
* returns the path this context was created with
* @return this context's path
*/
public abstract String getPath() ;
/**
* returns the server this context was created with
* @return this context's server
*/
public abstract HttpServer getServer () ;
/**
* returns a mutable Map, which can be used to pass
* configuration and other data to Filter modules
* and to the context's exchange handler.
* <p>
* Every attribute stored in this Map will be visible to
* every HttpExchange processed by this context
*/
public abstract Map<String,Object> getAttributes() ;
/**
* returns this context's list of Filters. This is the
* actual list used by the server when dispatching requests
* so modifications to this list immediately affect the
* the handling of exchanges.
*/
public abstract List<Filter> getFilters();
/**
* Sets the Authenticator for this HttpContext. Once an authenticator
* is establised on a context, all client requests must be
* authenticated, and the given object will be invoked to validate each
* request. Each call to this method replaces any previous value set.
* @param auth the authenticator to set. If <code>null</code> then any
* previously set authenticator is removed,
* and client authentication will no longer be required.
* @return the previous Authenticator, if any set, or <code>null</code>
* otherwise.
*/
public abstract Authenticator setAuthenticator (Authenticator auth);
/**
* Returns the currently set Authenticator for this context
* if one exists.
* @return this HttpContext's Authenticator, or <code>null</code>
* if none is set.
*/
public abstract Authenticator getAuthenticator ();
}

View File

@@ -0,0 +1,266 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import javax.net.ssl.*;
import java.util.*;
import sun.net.www.MessageHeader;
/**
* This class encapsulates a HTTP request received and a
* response to be generated in one exchange. It provides methods
* for examining the request from the client, and for building and
* sending the response.
* <p>
* The typical life-cycle of a HttpExchange is shown in the sequence
* below.
* <ol><li>{@link #getRequestMethod()} to determine the command
* <li>{@link #getRequestHeaders()} to examine the request headers (if needed)
* <li>{@link #getRequestBody()} returns a {@link java.io.InputStream} for reading the request body.
* After reading the request body, the stream is close.
* <li>{@link #getResponseHeaders()} to set any response headers, except content-length
* <li>{@link #sendResponseHeaders(int,long)} to send the response headers. Must be called before
* next step.
* <li>{@link #getResponseBody()} to get a {@link java.io.OutputStream} to send the response body.
* When the response body has been written, the stream must be closed to terminate the exchange.
* </ol>
* <b>Terminating exchanges</b>
* <br>
* Exchanges are terminated when both the request InputStream and response OutputStream are closed.
* Closing the OutputStream, implicitly closes the InputStream (if it is not already closed).
* However, it is recommended
* to consume all the data from the InputStream before closing it.
* The convenience method {@link #close()} does all of these tasks.
* Closing an exchange without consuming all of the request body is not an error
* but may make the underlying TCP connection unusable for following exchanges.
* The effect of failing to terminate an exchange is undefined, but will typically
* result in resources failing to be freed/reused.
* @since 1.6
*/
@jdk.Exported
public abstract class HttpExchange {
protected HttpExchange () {
}
/**
* Returns an immutable Map containing the HTTP headers that were
* included with this request. The keys in this Map will be the header
* names, while the values will be a List of Strings containing each value
* that was included (either for a header that was listed several times,
* or one that accepts a comma-delimited list of values on a single line).
* In either of these cases, the values for the header name will be
* presented in the order that they were included in the request.
* <p>
* The keys in Map are case-insensitive.
* @return a read-only Map which can be used to access request headers
*/
public abstract Headers getRequestHeaders () ;
/**
* Returns a mutable Map into which the HTTP response headers can be stored
* and which will be transmitted as part of this response. The keys in the
* Map will be the header names, while the values must be a List of Strings
* containing each value that should be included multiple times
* (in the order that they should be included).
* <p>
* The keys in Map are case-insensitive.
* @return a writable Map which can be used to set response headers.
*/
public abstract Headers getResponseHeaders () ;
/**
* Get the request URI
*
* @return the request URI
*/
public abstract URI getRequestURI () ;
/**
* Get the request method
* @return the request method
*/
public abstract String getRequestMethod ();
/**
* Get the HttpContext for this exchange
* @return the HttpContext
*/
public abstract HttpContext getHttpContext ();
/**
* Ends this exchange by doing the following in sequence:<p><ol>
* <li>close the request InputStream, if not already closed<p></li>
* <li>close the response OutputStream, if not already closed. </li>
* </ol>
*/
public abstract void close () ;
/**
* returns a stream from which the request body can be read.
* Multiple calls to this method will return the same stream.
* It is recommended that applications should consume (read) all of the
* data from this stream before closing it. If a stream is closed
* before all data has been read, then the close() call will
* read and discard remaining data (up to an implementation specific
* number of bytes).
* @return the stream from which the request body can be read.
*/
public abstract InputStream getRequestBody () ;
/**
* returns a stream to which the response body must be
* written. {@link #sendResponseHeaders(int,long)}) must be called prior to calling
* this method. Multiple calls to this method (for the same exchange)
* will return the same stream. In order to correctly terminate
* each exchange, the output stream must be closed, even if no
* response body is being sent.
* <p>
* Closing this stream implicitly
* closes the InputStream returned from {@link #getRequestBody()}
* (if it is not already closed).
* <P>
* If the call to sendResponseHeaders() specified a fixed response
* body length, then the exact number of bytes specified in that
* call must be written to this stream. If too many bytes are written,
* then write() will throw an IOException. If too few bytes are written
* then the stream close() will throw an IOException. In both cases,
* the exchange is aborted and the underlying TCP connection closed.
* @return the stream to which the response body is written
*/
public abstract OutputStream getResponseBody () ;
/**
* Starts sending the response back to the client using the current set of response headers
* and the numeric response code as specified in this method. The response body length is also specified
* as follows. If the response length parameter is greater than zero, this specifies an exact
* number of bytes to send and the application must send that exact amount of data.
* If the response length parameter is <code>zero</code>, then chunked transfer encoding is
* used and an arbitrary amount of data may be sent. The application terminates the
* response body by closing the OutputStream. If response length has the value <code>-1</code>
* then no response body is being sent.
* <p>
* If the content-length response header has not already been set then
* this is set to the appropriate value depending on the response length parameter.
* <p>
* This method must be called prior to calling {@link #getResponseBody()}.
* @param rCode the response code to send
* @param responseLength if > 0, specifies a fixed response body length
* and that exact number of bytes must be written
* to the stream acquired from getResponseBody(), or else
* if equal to 0, then chunked encoding is used,
* and an arbitrary number of bytes may be written.
* if <= -1, then no response body length is specified and
* no response body may be written.
* @see HttpExchange#getResponseBody()
*/
public abstract void sendResponseHeaders (int rCode, long responseLength) throws IOException ;
/**
* Returns the address of the remote entity invoking this request
* @return the InetSocketAddress of the caller
*/
public abstract InetSocketAddress getRemoteAddress ();
/**
* Returns the response code, if it has already been set
* @return the response code, if available. <code>-1</code> if not available yet.
*/
public abstract int getResponseCode ();
/**
* Returns the local address on which the request was received
* @return the InetSocketAddress of the local interface
*/
public abstract InetSocketAddress getLocalAddress ();
/**
* Returns the protocol string from the request in the form
* <i>protocol/majorVersion.minorVersion</i>. For example,
* "HTTP/1.1"
* @return the protocol string from the request
*/
public abstract String getProtocol ();
/**
* Filter modules may store arbitrary objects with HttpExchange
* instances as an out-of-band communication mechanism. Other Filters
* or the exchange handler may then access these objects.
* <p>
* Each Filter class will document the attributes which they make
* available.
* @param name the name of the attribute to retrieve
* @return the attribute object, or null if it does not exist
* @throws NullPointerException if name is <code>null</code>
*/
public abstract Object getAttribute (String name) ;
/**
* Filter modules may store arbitrary objects with HttpExchange
* instances as an out-of-band communication mechanism. Other Filters
* or the exchange handler may then access these objects.
* <p>
* Each Filter class will document the attributes which they make
* available.
* @param name the name to associate with the attribute value
* @param value the object to store as the attribute value. <code>null</code>
* value is permitted.
* @throws NullPointerException if name is <code>null</code>
*/
public abstract void setAttribute (String name, Object value) ;
/**
* Used by Filters to wrap either (or both) of this exchange's InputStream
* and OutputStream, with the given filtered streams so
* that subsequent calls to {@link #getRequestBody()} will
* return the given {@link java.io.InputStream}, and calls to
* {@link #getResponseBody()} will return the given
* {@link java.io.OutputStream}. The streams provided to this
* call must wrap the original streams, and may be (but are not
* required to be) sub-classes of {@link java.io.FilterInputStream}
* and {@link java.io.FilterOutputStream}.
* @param i the filtered input stream to set as this object's inputstream,
* or <code>null</code> if no change.
* @param o the filtered output stream to set as this object's outputstream,
* or <code>null</code> if no change.
*/
public abstract void setStreams (InputStream i, OutputStream o);
/**
* If an authenticator is set on the HttpContext that owns this exchange,
* then this method will return the {@link HttpPrincipal} that represents
* the authenticated user for this HttpExchange.
* @return the HttpPrincipal, or <code>null</code> if no authenticator is set.
*/
public abstract HttpPrincipal getPrincipal ();
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.io.IOException;
/**
* A handler which is invoked to process HTTP exchanges. Each
* HTTP exchange is handled by one of these handlers.
* @since 1.6
*/
@jdk.Exported
public interface HttpHandler {
/**
* Handle the given request and generate an appropriate response.
* See {@link HttpExchange} for a description of the steps
* involved in handling an exchange.
* @param exchange the exchange containing the request from the
* client and used to send the response
* @throws NullPointerException if exchange is <code>null</code>
*/
public abstract void handle (HttpExchange exchange) throws IOException;
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.util.*;
import java.security.Principal;
/**
* Represents a user authenticated by HTTP Basic or Digest
* authentication.
*/
@jdk.Exported
public class HttpPrincipal implements Principal {
private String username, realm;
/**
* creates a HttpPrincipal from the given username and realm
* @param username The name of the user within the realm
* @param realm The realm.
* @throws NullPointerException if either username or realm are null
*/
public HttpPrincipal (String username, String realm) {
if (username == null || realm == null) {
throw new NullPointerException();
}
this.username = username;
this.realm = realm;
}
/**
* Compares two HttpPrincipal. Returns <code>true</code>
* if <i>another</i> is an instance of HttpPrincipal, and its
* username and realm are equal to this object's username
* and realm. Returns <code>false</code> otherwise.
*/
public boolean equals (Object another) {
if (!(another instanceof HttpPrincipal)) {
return false;
}
HttpPrincipal theother = (HttpPrincipal)another;
return (username.equals(theother.username) &&
realm.equals(theother.realm));
}
/**
* returns the contents of this principal in the form
* <i>realm:username</i>
*/
public String getName() {
return username;
}
/**
* returns the username this object was created with.
*/
public String getUsername() {
return username;
}
/**
* returns the realm this object was created with.
*/
public String getRealm() {
return realm;
}
/**
* returns a hashcode for this HttpPrincipal. This is calculated
* as <code>(getUsername()+getRealm().hashCode()</code>
*/
public int hashCode() {
return (username+realm).hashCode();
}
/**
* returns the same string as getName()
*/
public String toString() {
return getName();
}
}

View File

@@ -0,0 +1,255 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.nio.*;
import java.security.*;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.*;
import javax.net.ssl.*;
import com.sun.net.httpserver.spi.HttpServerProvider;
/**
* This class implements a simple HTTP server. A HttpServer is bound to an IP address
* and port number and listens for incoming TCP connections from clients on this address.
* The sub-class {@link HttpsServer} implements a server which handles HTTPS requests.
* <p>
* One or more {@link HttpHandler} objects must be associated with a server
* in order to process requests. Each such HttpHandler is registered
* with a root URI path which represents the
* location of the application or service on this server. The mapping of a handler
* to a HttpServer is encapsulated by a {@link HttpContext} object. HttpContexts
* are created by calling {@link #createContext(String,HttpHandler)}.
* Any request for which no handler can be found is rejected with a 404 response.
* Management of threads can be done external to this object by providing a
* {@link java.util.concurrent.Executor} object. If none is provided a default
* implementation is used.
* <p>
* <a name="mapping_description"></a>
* <b>Mapping request URIs to HttpContext paths</b><p>
* When a HTTP request is received,
* the appropriate HttpContext (and handler) is located by finding the context
* whose path is the longest matching prefix of the request URI's path.
* Paths are matched literally, which means that the strings are compared
* case sensitively, and with no conversion to or from any encoded forms.
* For example. Given a HttpServer with the following HttpContexts configured.<p>
* <table >
* <tr><td><i>Context</i></td><td><i>Context path</i></td></tr>
* <tr><td>ctx1</td><td>"/"</td></tr>
* <tr><td>ctx2</td><td>"/apps/"</td></tr>
* <tr><td>ctx3</td><td>"/apps/foo/"</td></tr>
* </table>
* <p>
* the following table shows some request URIs and which, if any context they would
* match with.<p>
* <table>
* <tr><td><i>Request URI</i></td><td><i>Matches context</i></td></tr>
* <tr><td>"http://foo.com/apps/foo/bar"</td><td>ctx3</td></tr>
* <tr><td>"http://foo.com/apps/Foo/bar"</td><td>no match, wrong case</td></tr>
* <tr><td>"http://foo.com/apps/app1"</td><td>ctx2</td></tr>
* <tr><td>"http://foo.com/foo"</td><td>ctx1</td></tr>
* </table>
* <p>
* <b>Note about socket backlogs</b><p>
* When binding to an address and port number, the application can also specify an integer
* <i>backlog</i> parameter. This represents the maximum number of incoming TCP connections
* which the system will queue internally. Connections are queued while they are waiting to
* be accepted by the HttpServer. When the limit is reached, further connections may be
* rejected (or possibly ignored) by the underlying TCP implementation. Setting the right
* backlog value is a compromise between efficient resource usage in the TCP layer (not setting
* it too high) and allowing adequate throughput of incoming requests (not setting it too low).
* @since 1.6
*/
@jdk.Exported
public abstract class HttpServer {
/**
*/
protected HttpServer () {
}
/**
* creates a HttpServer instance which is initially not bound to any local address/port.
* The HttpServer is acquired from the currently installed {@link HttpServerProvider}
* The server must be bound using {@link #bind(InetSocketAddress,int)} before it can be used.
* @throws IOException
*/
public static HttpServer create () throws IOException {
return create (null, 0);
}
/**
* Create a <code>HttpServer</code> instance which will bind to the
* specified {@link java.net.InetSocketAddress} (IP address and port number)
*
* A maximum backlog can also be specified. This is the maximum number of
* queued incoming connections to allow on the listening socket.
* Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
* The HttpServer is acquired from the currently installed {@link HttpServerProvider}
*
* @param addr the address to listen on, if <code>null</code> then bind() must be called
* to set the address
* @param backlog the socket backlog. If this value is less than or equal to zero,
* then a system default value is used.
* @throws BindException if the server cannot bind to the requested address,
* or if the server is already bound.
* @throws IOException
*/
public static HttpServer create (
InetSocketAddress addr, int backlog
) throws IOException {
HttpServerProvider provider = HttpServerProvider.provider();
return provider.createHttpServer (addr, backlog);
}
/**
* Binds a currently unbound HttpServer to the given address and port number.
* A maximum backlog can also be specified. This is the maximum number of
* queued incoming connections to allow on the listening socket.
* Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
* @param addr the address to listen on
* @param backlog the socket backlog. If this value is less than or equal to zero,
* then a system default value is used.
* @throws BindException if the server cannot bind to the requested address or if the server
* is already bound.
* @throws NullPointerException if addr is <code>null</code>
*/
public abstract void bind (InetSocketAddress addr, int backlog) throws IOException;
/**
* Starts this server in a new background thread. The background thread
* inherits the priority, thread group and context class loader
* of the caller.
*/
public abstract void start () ;
/**
* sets this server's {@link java.util.concurrent.Executor} object. An
* Executor must be established before {@link #start()} is called.
* All HTTP requests are handled in tasks given to the executor.
* If this method is not called (before start()) or if it is
* called with a <code>null</code> Executor, then
* a default implementation is used, which uses the thread
* which was created by the {@link #start()} method.
* @param executor the Executor to set, or <code>null</code> for default
* implementation
* @throws IllegalStateException if the server is already started
*/
public abstract void setExecutor (Executor executor);
/**
* returns this server's Executor object if one was specified with
* {@link #setExecutor(Executor)}, or <code>null</code> if none was
* specified.
* @return the Executor established for this server or <code>null</code> if not set.
*/
public abstract Executor getExecutor () ;
/**
* stops this server by closing the listening socket and disallowing
* any new exchanges from being processed. The method will then block
* until all current exchange handlers have completed or else when
* approximately <i>delay</i> seconds have elapsed (whichever happens
* sooner). Then, all open TCP connections are closed, the background
* thread created by start() exits, and the method returns.
* Once stopped, a HttpServer cannot be re-used. <p>
*
* @param delay the maximum time in seconds to wait until exchanges have finished.
* @throws IllegalArgumentException if delay is less than zero.
*/
public abstract void stop (int delay);
/**
* Creates a HttpContext. A HttpContext represents a mapping from a
* URI path to a exchange handler on this HttpServer. Once created, all requests
* received by the server for the path will be handled by calling
* the given handler object. The context is identified by the path, and
* can later be removed from the server using this with the {@link #removeContext(String)} method.
* <p>
* The path specifies the root URI path for this context. The first character of path must be
* '/'. <p>
* The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
* to HttpContext instances.
* @param path the root URI path to associate the context with
* @param handler the handler to invoke for incoming requests.
* @throws IllegalArgumentException if path is invalid, or if a context
* already exists for this path
* @throws NullPointerException if either path, or handler are <code>null</code>
*/
public abstract HttpContext createContext (String path, HttpHandler handler) ;
/**
* Creates a HttpContext without initially specifying a handler. The handler must later be specified using
* {@link HttpContext#setHandler(HttpHandler)}. A HttpContext represents a mapping from a
* URI path to an exchange handler on this HttpServer. Once created, and when
* the handler has been set, all requests
* received by the server for the path will be handled by calling
* the handler object. The context is identified by the path, and
* can later be removed from the server using this with the {@link #removeContext(String)} method.
* <p>
* The path specifies the root URI path for this context. The first character of path must be
* '/'. <p>
* The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a>
* to HttpContext instances.
* @param path the root URI path to associate the context with
* @throws IllegalArgumentException if path is invalid, or if a context
* already exists for this path
* @throws NullPointerException if path is <code>null</code>
*/
public abstract HttpContext createContext (String path) ;
/**
* Removes the context identified by the given path from the server.
* Removing a context does not affect exchanges currently being processed
* but prevents new ones from being accepted.
* @param path the path of the handler to remove
* @throws IllegalArgumentException if no handler corresponding to this
* path exists.
* @throws NullPointerException if path is <code>null</code>
*/
public abstract void removeContext (String path) throws IllegalArgumentException ;
/**
* Removes the given context from the server.
* Removing a context does not affect exchanges currently being processed
* but prevents new ones from being accepted.
* @param context the context to remove
* @throws NullPointerException if context is <code>null</code>
*/
public abstract void removeContext (HttpContext context) ;
/**
* returns the address this server is listening on
* @return the address/port number the server is listening on
*/
public abstract InetSocketAddress getAddress() ;
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.nio.*;
import java.security.*;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.*;
import javax.net.ssl.*;
/**
* This class is used to configure the https parameters for each incoming
* https connection on a HttpsServer. Applications need to override
* the {@link #configure(HttpsParameters)} method in order to change
* the default configuration.
* <p>
* The following <a name="example">example</a> shows how this may be done:
* <p>
* <pre><blockquote>
* SSLContext sslContext = SSLContext.getInstance (....);
* HttpsServer server = HttpsServer.create();
*
* server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
* public void configure (HttpsParameters params) {
*
* // get the remote address if needed
* InetSocketAddress remote = params.getClientAddress();
*
* SSLContext c = getSSLContext();
*
* // get the default parameters
* SSLParameters sslparams = c.getDefaultSSLParameters();
* if (remote.equals (...) ) {
* // modify the default set for client x
* }
*
* params.setSSLParameters(sslparams);
* }
* });
* </blockquote></pre>
* @since 1.6
*/
@jdk.Exported
public class HttpsConfigurator {
private SSLContext context;
/**
* Creates an Https configuration, with the given SSLContext.
* @param context the SSLContext to use for this configurator
* @throws NullPointerException if no SSLContext supplied
*/
public HttpsConfigurator (SSLContext context) {
if (context == null) {
throw new NullPointerException ("null SSLContext");
}
this.context = context;
}
/**
* Returns the SSLContext for this HttpsConfigurator.
* @return the SSLContext
*/
public SSLContext getSSLContext() {
return context;
}
//BEGIN_TIGER_EXCLUDE
/**
* Called by the HttpsServer to configure the parameters
* for a https connection currently being established.
* The implementation of configure() must call
* {@link HttpsParameters#setSSLParameters(SSLParameters)}
* in order to set the SSL parameters for the connection.
* <p>
* The default implementation of this method uses the
* SSLParameters returned from <p>
* <code>getSSLContext().getDefaultSSLParameters()</code>
* <p>
* configure() may be overridden in order to modify this behavior.
* See, the example <a href="#example">above</a>.
* @param params the HttpsParameters to be configured.
*
* @since 1.6
*/
public void configure (HttpsParameters params) {
params.setSSLParameters (getSSLContext().getDefaultSSLParameters());
}
//END_TIGER_EXCLUDE
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import javax.net.ssl.*;
import java.util.*;
/**
* This class encapsulates a HTTPS request received and a
* response to be generated in one exchange and defines
* the extensions to HttpExchange that are specific to the HTTPS protocol.
* @since 1.6
*/
@jdk.Exported
public abstract class HttpsExchange extends HttpExchange {
protected HttpsExchange () {
}
/**
* Get the SSLSession for this exchange.
* @return the SSLSession
*/
public abstract SSLSession getSSLSession ();
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.InetSocketAddress;
//BEGIN_TIGER_EXCLUDE
import javax.net.ssl.SSLParameters;
//END_TIGER_EXCLUDE
/**
* Represents the set of parameters for each https
* connection negotiated with clients. One of these
* is created and passed to
* {@link HttpsConfigurator#configure(HttpsParameters)}
* for every incoming https connection,
* in order to determine the parameters to use.
* <p>
* The underlying SSL parameters may be established either
* via the set/get methods of this class, or else via
* a {@link javax.net.ssl.SSLParameters} object. SSLParameters
* is the preferred method, because in the future,
* additional configuration capabilities may be added to that class, and
* it is easier to determine the set of supported parameters and their
* default values with SSLParameters. Also, if an SSLParameters object is
* provided via
* {@link #setSSLParameters(SSLParameters)} then those parameter settings
* are used, and any settings made in this object are ignored.
* @since 1.6
*/
@jdk.Exported
public abstract class HttpsParameters {
private String[] cipherSuites;
private String[] protocols;
private boolean wantClientAuth;
private boolean needClientAuth;
protected HttpsParameters() {}
/**
* Returns the HttpsConfigurator for this HttpsParameters.
*/
public abstract HttpsConfigurator getHttpsConfigurator();
/**
* Returns the address of the remote client initiating the
* connection.
*/
public abstract InetSocketAddress getClientAddress();
//BEGIN_TIGER_EXCLUDE
/**
* Sets the SSLParameters to use for this HttpsParameters.
* The parameters must be supported by the SSLContext contained
* by the HttpsConfigurator associated with this HttpsParameters.
* If no parameters are set, then the default behavior is to use
* the default parameters from the associated SSLContext.
* @param params the SSLParameters to set. If <code>null</code>
* then the existing parameters (if any) remain unchanged.
* @throws IllegalArgumentException if any of the parameters are
* invalid or unsupported.
*/
public abstract void setSSLParameters (SSLParameters params);
//END_TIGER_EXCLUDE
/**
* Returns a copy of the array of ciphersuites or null if none
* have been set.
*
* @return a copy of the array of ciphersuites or null if none
* have been set.
*/
public String[] getCipherSuites() {
return cipherSuites != null ? cipherSuites.clone() : null;
}
/**
* Sets the array of ciphersuites.
*
* @param cipherSuites the array of ciphersuites (or null)
*/
public void setCipherSuites(String[] cipherSuites) {
this.cipherSuites = cipherSuites != null ? cipherSuites.clone() : null;
}
/**
* Returns a copy of the array of protocols or null if none
* have been set.
*
* @return a copy of the array of protocols or null if none
* have been set.
*/
public String[] getProtocols() {
return protocols != null ? protocols.clone() : null;
}
/**
* Sets the array of protocols.
*
* @param protocols the array of protocols (or null)
*/
public void setProtocols(String[] protocols) {
this.protocols = protocols != null ? protocols.clone() : null;
}
/**
* Returns whether client authentication should be requested.
*
* @return whether client authentication should be requested.
*/
public boolean getWantClientAuth() {
return wantClientAuth;
}
/**
* Sets whether client authentication should be requested. Calling
* this method clears the <code>needClientAuth</code> flag.
*
* @param wantClientAuth whether client authentication should be requested
*/
public void setWantClientAuth(boolean wantClientAuth) {
this.wantClientAuth = wantClientAuth;
}
/**
* Returns whether client authentication should be required.
*
* @return whether client authentication should be required.
*/
public boolean getNeedClientAuth() {
return needClientAuth;
}
/**
* Sets whether client authentication should be required. Calling
* this method clears the <code>wantClientAuth</code> flag.
*
* @param needClientAuth whether client authentication should be required
*/
public void setNeedClientAuth(boolean needClientAuth) {
this.needClientAuth = needClientAuth;
}
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver;
import java.net.*;
import java.io.*;
import java.nio.*;
import java.security.*;
import java.nio.channels.*;
import java.util.*;
import java.util.concurrent.*;
import javax.net.ssl.*;
import com.sun.net.httpserver.spi.*;
/**
* This class is an extension of {@link HttpServer} which provides
* support for HTTPS. <p>
* A HttpsServer must have an associated {@link HttpsConfigurator} object
* which is used to establish the SSL configuration for the SSL connections.
* <p>
* All other configuration is the same as for HttpServer.
* @since 1.6
*/
@jdk.Exported
public abstract class HttpsServer extends HttpServer {
/**
*/
protected HttpsServer () {
}
/**
* creates a HttpsServer instance which is initially not bound to any local address/port.
* The HttpsServer is acquired from the currently installed {@link HttpServerProvider}
* The server must be bound using {@link #bind(InetSocketAddress,int)} before it can be used.
* The server must also have a HttpsConfigurator established with {@link #setHttpsConfigurator(HttpsConfigurator)}
* @throws IOException
*/
public static HttpsServer create () throws IOException {
return create (null, 0);
}
/**
* Create a <code>HttpsServer</code> instance which will bind to the
* specified {@link java.net.InetSocketAddress} (IP address and port number)
*
* A maximum backlog can also be specified. This is the maximum number of
* queued incoming connections to allow on the listening socket.
* Queued TCP connections exceeding this limit may be rejected by the TCP implementation.
* The HttpsServer is acquired from the currently installed {@link HttpServerProvider}
* The server must have a HttpsConfigurator established with {@link #setHttpsConfigurator(HttpsConfigurator)}
*
* @param addr the address to listen on, if <code>null</code> then bind() must be called
* to set the address
* @param backlog the socket backlog. If this value is less than or equal to zero,
* then a system default value is used.
* @throws BindException if the server cannot bind to the requested address,
* or if the server is already bound.
* @throws IOException
*/
public static HttpsServer create (
InetSocketAddress addr, int backlog
) throws IOException {
HttpServerProvider provider = HttpServerProvider.provider();
return provider.createHttpsServer (addr, backlog);
}
/**
* Sets this server's {@link HttpsConfigurator} object.
* @param config the HttpsConfigurator to set
* @throws NullPointerException if config is null.
*/
public abstract void setHttpsConfigurator (HttpsConfigurator config) ;
/**
* Gets this server's {@link HttpsConfigurator} object, if it has been set.
* @return the HttpsConfigurator for this server, or <code>null</code> if not set.
*/
public abstract HttpsConfigurator getHttpsConfigurator ();
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
Provides a simple high-level Http server API, which can be used to build
embedded HTTP servers. Both "http" and "https" are supported. The API provides
a partial implementation of RFC <a href="http://www.ietf.org/rfc/rfc2616.txt">2616</a> (HTTP 1.1)
and RFC <a href="http://www.ietf.org/rfc/rfc2818.txt">2818</a> (HTTP over TLS).
Any HTTP functionality not provided by this API can be implemented by application code
using the API.
<p>
Programmers must implement the {@link com.sun.net.httpserver.HttpHandler} interface. This interface
provides a callback which is invoked to handle incoming requests from clients.
A HTTP request and its response is known as an exchange. HTTP exchanges are
represented by the {@link com.sun.net.httpserver.HttpExchange} class.
The {@link com.sun.net.httpserver.HttpServer} class is used to listen for incoming TCP connections
and it dispatches requests on these connections to handlers which have been
registered with the server.
<p>
A minimal Http server example is shown below:
<blockquote><pre>
class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
InputStream is = t.getRequestBody();
read(is); // .. read the request body
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
...
HttpServer server = HttpServer.create(new InetSocketAddress(8000));
server.createContext("/applications/myapp", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
</blockquote></pre>
<p>The example above creates a simple HttpServer which uses the calling
application thread to invoke the handle() method for incoming http
requests directed to port 8000, and to the path /applications/myapp/.
<p>
The {@link com.sun.net.httpserver.HttpExchange} class encapsulates everything an application needs to
process incoming requests and to generate appropriate responses.
<p>
Registering a handler with a HttpServer creates a {@link com.sun.net.httpserver.HttpContext} object and
{@link com.sun.net.httpserver.Filter}
objects can be added to the returned context. Filters are used to perform automatic pre- and
post-processing of exchanges before they are passed to the exchange handler.
<p>
For sensitive information, a {@link com.sun.net.httpserver.HttpsServer} can
be used to process "https" requests secured by the SSL or TLS protocols.
A HttpsServer must be provided with a
{@link com.sun.net.httpserver.HttpsConfigurator} object, which contains an
initialized {@link javax.net.ssl.SSLContext}.
HttpsConfigurator can be used to configure the
cipher suites and other SSL operating parameters.
A simple example SSLContext could be created as follows:
<blockquote><pre>
char[] passphrase = "passphrase".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("testkeys"), passphrase);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
</blockquote></pre>
<p>
In the example above, a keystore file called "testkeys", created with the keytool utility
is used as a certificate store for client and server certificates.
The following code shows how the SSLContext is then used in a HttpsConfigurator
and how the SSLContext and HttpsConfigurator are linked to the HttpsServer.
<blockquote><pre>
server.setHttpsConfigurator (new HttpsConfigurator(sslContext) {
public void configure (HttpsParameters params) {
// get the remote address if needed
InetSocketAddress remote = params.getClientAddress();
SSLContext c = getSSLContext();
// get the default parameters
SSLParameters sslparams = c.getDefaultSSLParameters();
if (remote.equals (...) ) {
// modify the default set for client x
}
params.setSSLParameters(sslparams);
// statement above could throw IAE if any params invalid.
// eg. if app has a UI and parameters supplied by a user.
}
});
</blockquote></pre>
<p>
@since 1.6
*/
@jdk.Exported
package com.sun.net.httpserver;

View File

@@ -0,0 +1,179 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.net.httpserver.spi;
import java.io.IOException;
import java.net.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
import com.sun.net.httpserver.*;
/**
* Service provider class for HttpServer.
* Sub-classes of HttpServerProvider provide an implementation of
* {@link HttpServer} and associated classes. Applications do not normally use
* this class. See {@link #provider()} for how providers are found and loaded.
*/
@jdk.Exported
public abstract class HttpServerProvider {
/**
* creates a HttpServer from this provider
*
* @param addr
* the address to bind to. May be {@code null}
*
* @param backlog
* the socket backlog. A value of {@code zero} means the systems default
*/
public abstract HttpServer createHttpServer(InetSocketAddress addr,
int backlog)
throws IOException;
/**
* creates a HttpsServer from this provider
*
* @param addr
* the address to bind to. May be {@code null}
*
* @param backlog
* the socket backlog. A value of {@code zero} means the systems default
*/
public abstract HttpsServer createHttpsServer(InetSocketAddress addr,
int backlog)
throws IOException;
private static final Object lock = new Object();
private static HttpServerProvider provider = null;
/**
* Initializes a new instance of this class.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link RuntimePermission}{@code ("httpServerProvider")}
*/
protected HttpServerProvider() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new RuntimePermission("httpServerProvider"));
}
private static boolean loadProviderFromProperty() {
String cn = System.getProperty("com.sun.net.httpserver.HttpServerProvider");
if (cn == null)
return false;
try {
Class<?> c = Class.forName(cn, true,
ClassLoader.getSystemClassLoader());
provider = (HttpServerProvider)c.newInstance();
return true;
} catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
SecurityException x) {
throw new ServiceConfigurationError(null, x);
}
}
private static boolean loadProviderAsService() {
Iterator<HttpServerProvider> i =
ServiceLoader.load(HttpServerProvider.class,
ClassLoader.getSystemClassLoader())
.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
/**
* Returns the system wide default HttpServerProvider for this invocation of
* the Java virtual machine.
*
* <p> The first invocation of this method locates the default provider
* object as follows: </p>
*
* <ol>
*
* <li><p> If the system property
* {@code com.sun.net.httpserver.HttpServerProvider} is defined then it
* is taken to be the fully-qualified name of a concrete provider class.
* The class is loaded and instantiated; if this process fails then an
* unspecified unchecked error or exception is thrown. </p></li>
*
* <li><p> If a provider class has been installed in a jar file that is
* visible to the system class loader, and that jar file contains a
* provider-configuration file named
* {@code com.sun.net.httpserver.HttpServerProvider} in the resource
* directory <tt>META-INF/services</tt>, then the first class name
* specified in that file is taken. The class is loaded and
* instantiated; if this process fails then an unspecified unchecked error
* or exception is thrown. </p></li>
*
* <li><p> Finally, if no provider has been specified by any of the above
* means then the system-default provider class is instantiated and the
* result is returned. </p></li>
*
* </ol>
*
* <p> Subsequent invocations of this method return the provider that was
* returned by the first invocation. </p>
*
* @return The system-wide default HttpServerProvider
*/
public static HttpServerProvider provider () {
synchronized (lock) {
if (provider != null)
return provider;
return (HttpServerProvider)AccessController
.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
if (loadProviderFromProperty())
return provider;
if (loadProviderAsService())
return provider;
provider = new sun.net.httpserver.DefaultHttpServerProvider();
return provider;
}
});
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Provides a pluggable service provider interface, which allows the HTTP server
* implementation to be replaced with other implementations.
*/
@jdk.Exported
package com.sun.net.httpserver.spi;