code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP server.
*
*
*/
public class NHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(args[0]));
handler.setHandlerResolver(reqistry);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
NStringEntity entity = new NStringEntity(
"<html><body><h1>File" + file.getPath() +
" not found</h1></body></html>", "UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
NStringEntity entity = new NStringEntity(
"<html><body><h1>Access denied</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
NFileEntity body = new NFileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpServer.java
|
Java
|
gpl3
| 8,685
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
/**
* Rudimentary HTTP/1.1 reverse proxy based on the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy.
*
*
*/
public class NHttpReverseProxy {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Usage: NHttpReverseProxy <hostname> [port]");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
// Target host
HttpHost targetHost = new HttpHost(hostname, port);
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1")
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
final ConnectingIOReactor connectingIOReactor = new DefaultConnectingIOReactor(
1, params);
final ListeningIOReactor listeningIOReactor = new DefaultListeningIOReactor(
1, params);
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
NHttpClientHandler connectingHandler = new ConnectingHandler(
inhttpproc,
new DefaultConnectionReuseStrategy(),
params);
NHttpServiceHandler listeningHandler = new ListeningHandler(
targetHost,
connectingIOReactor,
outhttpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
final IOEventDispatch connectingEventDispatch = new DefaultClientIOEventDispatch(
connectingHandler, params);
final IOEventDispatch listeningEventDispatch = new DefaultServerIOEventDispatch(
listeningHandler, params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
connectingIOReactor.execute(connectingEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
});
t.start();
try {
listeningIOReactor.listen(new InetSocketAddress(8888));
listeningIOReactor.execute(listeningEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
}
static class ListeningHandler implements NHttpServiceHandler {
private final HttpHost targetHost;
private final ConnectingIOReactor connectingIOReactor;
private final HttpProcessor httpProcessor;
private final HttpResponseFactory responseFactory;
private final ConnectionReuseStrategy connStrategy;
private final HttpParams params;
public ListeningHandler(
final HttpHost targetHost,
final ConnectingIOReactor connectingIOReactor,
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
super();
this.targetHost = targetHost;
this.connectingIOReactor = connectingIOReactor;
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.responseFactory = responseFactory;
this.params = params;
}
public void connected(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] conn open");
ProxyTask proxyTask = new ProxyTask();
synchronized (proxyTask) {
// Initialize connection state
proxyTask.setTarget(this.targetHost);
proxyTask.setClientIOControl(conn);
proxyTask.setClientState(ConnState.CONNECTED);
HttpContext context = conn.getContext();
context.setAttribute(ProxyTask.ATTRIB, proxyTask);
InetSocketAddress address = new InetSocketAddress(
this.targetHost.getHostName(),
this.targetHost.getPort());
this.connectingIOReactor.connect(
address,
null,
proxyTask,
null);
}
}
public void requestReceived(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] request received");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.IDLE
&& connState != ConnState.CONNECTED) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
HttpRequest request = conn.getHttpRequest();
System.out.println(conn + " [client->proxy] >> " + request.getRequestLine());
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
// Update connection state
proxyTask.setRequest(request);
proxyTask.setClientState(ConnState.REQUEST_RECEIVED);
// See if the client expects a 100-Continue
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
HttpResponse ack = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_CONTINUE,
context);
conn.submitResponse(ack);
}
} else {
// No request content expected. Suspend client input
conn.suspendInput();
}
// If there is already a connection to the origin server
// make sure origin output is active
if (proxyTask.getOriginIOControl() != null) {
proxyTask.getOriginIOControl().requestOutput();
}
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
System.out.println(conn + " [client->proxy] input ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.REQUEST_RECEIVED
&& connState != ConnState.REQUEST_BODY_STREAM) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
ByteBuffer dst = proxyTask.getInBuffer();
int bytesRead = decoder.read(dst);
System.out.println(conn + " [client->proxy] " + bytesRead + " bytes read");
System.out.println(conn + " [client->proxy] " + decoder);
if (!dst.hasRemaining()) {
// Input buffer is full. Suspend client input
// until the origin handler frees up some space in the buffer
conn.suspendInput();
}
// If there is some content in the input buffer make sure origin
// output is active
if (dst.position() > 0) {
if (proxyTask.getOriginIOControl() != null) {
proxyTask.getOriginIOControl().requestOutput();
}
}
if (decoder.isCompleted()) {
System.out.println(conn + " [client->proxy] request body received");
// Update connection state
proxyTask.setClientState(ConnState.REQUEST_BODY_DONE);
// Suspend client input
conn.suspendInput();
} else {
proxyTask.setClientState(ConnState.REQUEST_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
System.out.println(conn + " [client<-proxy] response ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState == ConnState.IDLE) {
// Response not available
return;
}
if (connState != ConnState.REQUEST_RECEIVED
&& connState != ConnState.REQUEST_BODY_DONE) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
try {
HttpRequest request = proxyTask.getRequest();
HttpResponse response = proxyTask.getResponse();
if (response == null) {
throw new IllegalStateException("HTTP request is null");
}
// Remove hop-by-hop headers
response.removeHeaders(HTTP.CONTENT_LEN);
response.removeHeaders(HTTP.TRANSFER_ENCODING);
response.removeHeaders(HTTP.CONN_DIRECTIVE);
response.removeHeaders("Keep-Alive");
response.removeHeaders("Proxy-Authenticate");
response.removeHeaders("Proxy-Authorization");
response.removeHeaders("TE");
response.removeHeaders("Trailers");
response.removeHeaders("Upgrade");
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
// Close client connection if the connection to the target
// is no longer active / open
if (proxyTask.getOriginState().compareTo(ConnState.CLOSING) >= 0) {
response.addHeader(HTTP.CONN_DIRECTIVE, "Close");
}
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(response, context);
conn.submitResponse(response);
proxyTask.setClientState(ConnState.RESPONSE_SENT);
System.out.println(conn + " [client<-proxy] << " + response.getStatusLine());
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [client<-proxy] close connection");
proxyTask.setClientState(ConnState.CLOSING);
conn.close();
} else {
// Reset connection state
proxyTask.reset();
conn.requestInput();
// Ready to deal with a new request
}
}
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
private boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
System.out.println(conn + " [client<-proxy] output ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getClientState();
if (connState != ConnState.RESPONSE_SENT
&& connState != ConnState.RESPONSE_BODY_STREAM) {
throw new IllegalStateException("Illegal client connection state: " + connState);
}
HttpResponse response = proxyTask.getResponse();
if (response == null) {
throw new IllegalStateException("HTTP request is null");
}
try {
ByteBuffer src = proxyTask.getOutBuffer();
src.flip();
int bytesWritten = encoder.write(src);
System.out.println(conn + " [client<-proxy] " + bytesWritten + " bytes written");
System.out.println(conn + " [client<-proxy] " + encoder);
src.compact();
if (src.position() == 0) {
if (proxyTask.getOriginState() == ConnState.RESPONSE_BODY_DONE) {
encoder.complete();
} else {
// Input output is empty. Wait until the origin handler
// fills up the buffer
conn.suspendOutput();
}
}
// Update connection state
if (encoder.isCompleted()) {
System.out.println(conn + " [proxy] response body sent");
proxyTask.setClientState(ConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [client<-proxy] close connection");
proxyTask.setClientState(ConnState.CLOSING);
conn.close();
} else {
// Reset connection state
proxyTask.reset();
conn.requestInput();
// Ready to deal with a new request
}
} else {
proxyTask.setClientState(ConnState.RESPONSE_BODY_STREAM);
// Make sure origin input is active
proxyTask.getOriginIOControl().requestInput();
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void closed(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] conn closed");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
if (proxyTask != null) {
synchronized (proxyTask) {
proxyTask.setClientState(ConnState.CLOSED);
}
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
System.out.println(conn + " [client->proxy] HTTP error: " + httpex.getMessage());
if (conn.isResponseSubmitted()) {
shutdownConnection(conn);
return;
}
HttpContext context = conn.getContext();
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0, HttpStatus.SC_BAD_REQUEST, context);
response.setParams(
new DefaultedHttpParams(this.params, response.getParams()));
response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, null);
this.httpProcessor.process(response, context);
conn.submitResponse(response);
conn.close();
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn);
System.out.println(conn + " [client->proxy] I/O error: " + ex.getMessage());
}
public void timeout(final NHttpServerConnection conn) {
System.out.println(conn + " [client->proxy] timeout");
closeConnection(conn);
}
private void shutdownConnection(final NHttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
private void closeConnection(final NHttpConnection conn) {
try {
conn.close();
} catch (IOException ignore) {
}
}
}
static class ConnectingHandler implements NHttpClientHandler {
private final HttpProcessor httpProcessor;
private final ConnectionReuseStrategy connStrategy;
private final HttpParams params;
public ConnectingHandler(
final HttpProcessor httpProcessor,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
super();
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.params = params;
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
System.out.println(conn + " [proxy->origin] conn open");
// The shared state object is expected to be passed as an attachment
ProxyTask proxyTask = (ProxyTask) attachment;
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.IDLE) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
// Set origin IO control handle
proxyTask.setOriginIOControl(conn);
// Store the state object in the context
HttpContext context = conn.getContext();
context.setAttribute(ProxyTask.ATTRIB, proxyTask);
// Update connection state
proxyTask.setOriginState(ConnState.CONNECTED);
if (proxyTask.getRequest() != null) {
conn.requestOutput();
}
}
}
public void requestReady(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] request ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState == ConnState.REQUEST_SENT
|| connState == ConnState.REQUEST_BODY_DONE) {
// Request sent but no response available yet
return;
}
if (connState != ConnState.IDLE
&& connState != ConnState.CONNECTED) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpRequest request = proxyTask.getRequest();
if (request == null) {
throw new IllegalStateException("HTTP request is null");
}
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("Proxy-Authorization");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
// Remove host header
request.removeHeaders(HTTP.TARGET_HOST);
HttpHost targetHost = proxyTask.getTarget();
try {
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
// Pre-process HTTP request
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.httpProcessor.process(request, context);
// and send it to the origin server
conn.submitRequest(request);
// Update connection state
proxyTask.setOriginState(ConnState.REQUEST_SENT);
System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString());
} catch (IOException ex) {
shutdownConnection(conn);
} catch (HttpException ex) {
shutdownConnection(conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
System.out.println(conn + " [proxy->origin] output ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.REQUEST_SENT
&& connState != ConnState.REQUEST_BODY_STREAM) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
try {
ByteBuffer src = proxyTask.getInBuffer();
src.flip();
int bytesWritten = encoder.write(src);
System.out.println(conn + " [proxy->origin] " + bytesWritten + " bytes written");
System.out.println(conn + " [proxy->origin] " + encoder);
src.compact();
if (src.position() == 0) {
if (proxyTask.getClientState() == ConnState.REQUEST_BODY_DONE) {
encoder.complete();
} else {
// Input buffer is empty. Wait until the client fills up
// the buffer
conn.suspendOutput();
}
}
// Update connection state
if (encoder.isCompleted()) {
System.out.println(conn + " [proxy->origin] request body sent");
proxyTask.setOriginState(ConnState.REQUEST_BODY_DONE);
} else {
proxyTask.setOriginState(ConnState.REQUEST_BODY_STREAM);
// Make sure client input is active
proxyTask.getClientIOControl().requestInput();
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy<-origin] response received");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.REQUEST_SENT
&& connState != ConnState.REQUEST_BODY_DONE) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpResponse response = conn.getHttpResponse();
HttpRequest request = proxyTask.getRequest();
System.out.println(conn + " [proxy<-origin] << " + response.getStatusLine());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// Ignore 1xx response
return;
}
try {
// Update connection state
proxyTask.setResponse(response);
proxyTask.setOriginState(ConnState.RESPONSE_RECEIVED);
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [proxy<-origin] close connection");
proxyTask.setOriginState(ConnState.CLOSING);
conn.close();
}
}
// Make sure client output is active
proxyTask.getClientIOControl().requestOutput();
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
private boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
System.out.println(conn + " [proxy<-origin] input ready");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
synchronized (proxyTask) {
ConnState connState = proxyTask.getOriginState();
if (connState != ConnState.RESPONSE_RECEIVED
&& connState != ConnState.RESPONSE_BODY_STREAM) {
throw new IllegalStateException("Illegal target connection state: " + connState);
}
HttpResponse response = proxyTask.getResponse();
try {
ByteBuffer dst = proxyTask.getOutBuffer();
int bytesRead = decoder.read(dst);
System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
System.out.println(conn + " [proxy<-origin] " + decoder);
if (!dst.hasRemaining()) {
// Output buffer is full. Suspend origin input until
// the client handler frees up some space in the buffer
conn.suspendInput();
}
// If there is some content in the buffer make sure client output
// is active
if (dst.position() > 0) {
proxyTask.getClientIOControl().requestOutput();
}
if (decoder.isCompleted()) {
System.out.println(conn + " [proxy<-origin] response body received");
proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
System.out.println(conn + " [proxy<-origin] close connection");
proxyTask.setOriginState(ConnState.CLOSING);
conn.close();
}
} else {
proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn);
}
}
}
public void closed(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] conn closed");
HttpContext context = conn.getContext();
ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB);
if (proxyTask != null) {
synchronized (proxyTask) {
proxyTask.setOriginState(ConnState.CLOSED);
}
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
shutdownConnection(conn);
System.out.println(conn + " [proxy->origin] HTTP error: " + ex.getMessage());
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn);
System.out.println(conn + " [proxy->origin] I/O error: " + ex.getMessage());
}
public void timeout(final NHttpClientConnection conn) {
System.out.println(conn + " [proxy->origin] timeout");
closeConnection(conn);
}
private void shutdownConnection(final HttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
private void closeConnection(final HttpConnection conn) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
}
enum ConnState {
IDLE,
CONNECTED,
REQUEST_RECEIVED,
REQUEST_SENT,
REQUEST_BODY_STREAM,
REQUEST_BODY_DONE,
RESPONSE_RECEIVED,
RESPONSE_SENT,
RESPONSE_BODY_STREAM,
RESPONSE_BODY_DONE,
CLOSING,
CLOSED
}
static class ProxyTask {
public static final String ATTRIB = "nhttp.proxy-task";
private final ByteBuffer inBuffer;
private final ByteBuffer outBuffer;
private HttpHost target;
private IOControl originIOControl;
private IOControl clientIOControl;
private ConnState originState;
private ConnState clientState;
private HttpRequest request;
private HttpResponse response;
public ProxyTask() {
super();
this.originState = ConnState.IDLE;
this.clientState = ConnState.IDLE;
this.inBuffer = ByteBuffer.allocateDirect(10240);
this.outBuffer = ByteBuffer.allocateDirect(10240);
}
public ByteBuffer getInBuffer() {
return this.inBuffer;
}
public ByteBuffer getOutBuffer() {
return this.outBuffer;
}
public HttpHost getTarget() {
return this.target;
}
public void setTarget(final HttpHost target) {
this.target = target;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public IOControl getClientIOControl() {
return this.clientIOControl;
}
public void setClientIOControl(final IOControl clientIOControl) {
this.clientIOControl = clientIOControl;
}
public IOControl getOriginIOControl() {
return this.originIOControl;
}
public void setOriginIOControl(final IOControl originIOControl) {
this.originIOControl = originIOControl;
}
public ConnState getOriginState() {
return this.originState;
}
public void setOriginState(final ConnState state) {
this.originState = state;
}
public ConnState getClientState() {
return this.clientState;
}
public void setClientState(final ConnState state) {
this.clientState = state;
}
public void reset() {
this.inBuffer.clear();
this.outBuffer.clear();
this.originState = ConnState.IDLE;
this.clientState = ConnState.IDLE;
this.request = null;
this.response = null;
}
public void shutdown() {
if (this.clientIOControl != null) {
try {
this.clientIOControl.shutdown();
} catch (IOException ignore) {
}
}
if (this.originIOControl != null) {
try {
this.originIOControl.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpReverseProxy.java
|
Java
|
gpl3
| 41,469
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.examples.nio;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentDecoderChannel;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.ContentListener;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerResolver;
import org.apache.http.nio.protocol.SimpleNHttpRequestHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
*
*
*/
public class NHttpFileServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
boolean useFileChannels = true;
if (args.length >= 2) {
String s = args[1];
if (s.equalsIgnoreCase("disableFileChannels")) {
useFileChannels = false;
}
}
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
final HttpFileHandler filehandler = new HttpFileHandler(args[0], useFileChannels);
NHttpRequestHandlerResolver resolver = new NHttpRequestHandlerResolver() {
public NHttpRequestHandler lookup(String requestURI) {
return filehandler;
}
};
handler.setHandlerResolver(resolver);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler extends SimpleNHttpRequestHandler {
private final String docRoot;
private final boolean useFileChannels;
public HttpFileHandler(final String docRoot, boolean useFileChannels) {
this.docRoot = docRoot;
this.useFileChannels = useFileChannels;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) throws HttpException, IOException {
return new ConsumingNHttpEntityTemplate(
request.getEntity(),
new FileWriteListener(useFileChannels));
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
NStringEntity entity = new NStringEntity(
"<html><body><h1>File" + file.getPath() +
" not found</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
NStringEntity entity = new NStringEntity(
"<html><body><h1>Access denied</h1></body></html>",
"UTF-8");
entity.setContentType("text/html; charset=UTF-8");
response.setEntity(entity);
} else {
response.setStatusCode(HttpStatus.SC_OK);
NFileEntity entity = new NFileEntity(file, "text/html", useFileChannels);
response.setEntity(entity);
}
}
}
static class FileWriteListener implements ContentListener {
private final File file;
private final FileOutputStream outputFile;
private final FileChannel fileChannel;
private final boolean useFileChannels;
private long idx = 0;
public FileWriteListener(boolean useFileChannels) throws IOException {
this.file = File.createTempFile("tmp", ".tmp", null);
this.outputFile = new FileOutputStream(file, true);
this.fileChannel = outputFile.getChannel();
this.useFileChannels = useFileChannels;
}
public void contentAvailable(ContentDecoder decoder, IOControl ioctrl)
throws IOException {
long transferred;
if(useFileChannels && decoder instanceof FileContentDecoder) {
transferred = ((FileContentDecoder) decoder).transfer(
fileChannel, idx, Long.MAX_VALUE);
} else {
transferred = fileChannel.transferFrom(
new ContentDecoderChannel(decoder), idx, Integer.MAX_VALUE);
}
if(transferred > 0)
idx += transferred;
}
public void finished() {
try {
outputFile.close();
} catch(IOException ignored) {}
try {
fileChannel.close();
} catch(IOException ignored) {}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpFileServer.java
|
Java
|
gpl3
| 10,514
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;
/**
* Example of a very simple asynchronous connection manager that maintains a pool of persistent
* connections to one target host.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpClientConnManagement {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// Set up protocol handler
BufferingHttpClientHandler protocolHandler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(),
new DefaultConnectionReuseStrategy(),
params);
protocolHandler.setEventListener(new EventLogger());
// Limit the total maximum of concurrent connections to 5
int maxTotalConnections = 5;
// Use the connection manager to maintain a pool of connections to localhost:8080
final AsyncConnectionManager connMgr = new AsyncConnectionManager(
new HttpHost("localhost", 8080),
maxTotalConnections,
protocolHandler,
params);
// Start the I/O reactor in a separate thread
Thread t = new Thread(new Runnable() {
public void run() {
try {
connMgr.execute();
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("I/O reactor terminated");
}
});
t.start();
// Submit 50 requests using maximum 5 concurrent connections
Queue<RequestHandle> queue = new LinkedList<RequestHandle>();
for (int i = 0; i < 50; i++) {
AsyncConnectionRequest connRequest = connMgr.requestConnection();
connRequest.waitFor();
NHttpClientConnection conn = connRequest.getConnection();
if (conn == null) {
System.err.println("Failed to obtain connection");
break;
}
HttpContext context = conn.getContext();
BasicHttpRequest httpget = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
RequestHandle handle = new RequestHandle(connMgr, conn);
context.setAttribute("request", httpget);
context.setAttribute("request-handle", handle);
queue.add(handle);
conn.requestOutput();
}
// Wait until all requests have been completed
while (!queue.isEmpty()) {
RequestHandle handle = queue.remove();
handle.waitFor();
}
// Give the I/O reactor 10 sec to shut down
connMgr.shutdown(10000);
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
public MyHttpRequestExecutionHandler() {
super();
}
public void initalizeContext(final HttpContext context, final Object attachment) {
}
public void finalizeContext(final HttpContext context) {
RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle");
if (handle != null) {
handle.cancel();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpRequest request = (HttpRequest) context.removeAttribute("request");
return request;
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle");
if (handle != null) {
handle.completed();
}
}
}
static class AsyncConnectionRequest {
private volatile boolean completed;
private volatile NHttpClientConnection conn;
public AsyncConnectionRequest() {
super();
}
public boolean isCompleted() {
return this.completed;
}
public void setConnection(NHttpClientConnection conn) {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.conn = conn;
notifyAll();
}
}
public NHttpClientConnection getConnection() {
return this.conn;
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
notifyAll();
}
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
}
static class AsyncConnectionManager {
private final HttpHost target;
private final int maxConnections;
private final NHttpClientHandler handler;
private final HttpParams params;
private final ConnectingIOReactor ioreactor;
private final Object lock;
private final Set<NHttpClientConnection> allConns;
private final Queue<NHttpClientConnection> availableConns;
private final Queue<AsyncConnectionRequest> pendingRequests;
private volatile boolean shutdown;
public AsyncConnectionManager(
HttpHost target,
int maxConnections,
NHttpClientHandler handler,
HttpParams params) throws IOReactorException {
super();
this.target = target;
this.maxConnections = maxConnections;
this.handler = handler;
this.params = params;
this.lock = new Object();
this.allConns = new HashSet<NHttpClientConnection>();
this.availableConns = new LinkedList<NHttpClientConnection>();
this.pendingRequests = new LinkedList<AsyncConnectionRequest>();
this.ioreactor = new DefaultConnectingIOReactor(2, params);
}
public void execute() throws IOException {
IOEventDispatch dispatch = new DefaultClientIOEventDispatch(
new ManagedClientHandler(this.handler, this), this.params);
this.ioreactor.execute(dispatch);
}
public void shutdown(long waitMs) throws IOException {
synchronized (this.lock) {
if (!this.shutdown) {
this.shutdown = true;
while (!this.pendingRequests.isEmpty()) {
AsyncConnectionRequest request = this.pendingRequests.remove();
request.cancel();
}
this.availableConns.clear();
this.allConns.clear();
}
}
this.ioreactor.shutdown(waitMs);
}
void addConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
this.allConns.add(conn);
}
}
void removeConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
if (this.allConns.remove(conn)) {
this.availableConns.remove(conn);
}
processRequests();
}
}
public AsyncConnectionRequest requestConnection() {
if (this.shutdown) {
throw new IllegalStateException("Connection manager has been shut down");
}
AsyncConnectionRequest request = new AsyncConnectionRequest();
synchronized (this.lock) {
while (!this.availableConns.isEmpty()) {
NHttpClientConnection conn = this.availableConns.remove();
if (conn.isOpen()) {
System.out.println("Re-using persistent connection");
request.setConnection(conn);
break;
} else {
this.allConns.remove(conn);
}
}
if (!request.isCompleted()) {
this.pendingRequests.add(request);
processRequests();
}
}
return request;
}
public void releaseConnection(NHttpClientConnection conn) {
if (conn == null) {
return;
}
if (this.shutdown) {
return;
}
synchronized (this.lock) {
if (this.allConns.contains(conn)) {
if (conn.isOpen()) {
conn.setSocketTimeout(0);
AsyncConnectionRequest request = this.pendingRequests.poll();
if (request != null) {
System.out.println("Re-using persistent connection");
request.setConnection(conn);
} else {
this.availableConns.add(conn);
}
} else {
this.allConns.remove(conn);
processRequests();
}
}
}
}
private void processRequests() {
while (this.allConns.size() < this.maxConnections) {
AsyncConnectionRequest request = this.pendingRequests.poll();
if (request == null) {
break;
}
InetSocketAddress address = new InetSocketAddress(
this.target.getHostName(),
this.target.getPort());
ConnRequestCallback callback = new ConnRequestCallback(request);
System.out.println("Opening new connection");
this.ioreactor.connect(address, null, request, callback);
}
}
}
static class ManagedClientHandler implements NHttpClientHandler {
private final NHttpClientHandler handler;
private final AsyncConnectionManager connMgr;
public ManagedClientHandler(NHttpClientHandler handler, AsyncConnectionManager connMgr) {
super();
this.handler = handler;
this.connMgr = connMgr;
}
public void connected(NHttpClientConnection conn, Object attachment) {
AsyncConnectionRequest request = (AsyncConnectionRequest) attachment;
this.handler.connected(conn, attachment);
this.connMgr.addConnection(conn);
request.setConnection(conn);
}
public void closed(NHttpClientConnection conn) {
this.connMgr.removeConnection(conn);
this.handler.closed(conn);
}
public void requestReady(NHttpClientConnection conn) {
this.handler.requestReady(conn);
}
public void outputReady(NHttpClientConnection conn, ContentEncoder encoder) {
this.handler.outputReady(conn, encoder);
}
public void responseReceived(NHttpClientConnection conn) {
this.handler.responseReceived(conn);
}
public void inputReady(NHttpClientConnection conn, ContentDecoder decoder) {
this.handler.inputReady(conn, decoder);
}
public void exception(NHttpClientConnection conn, HttpException ex) {
this.handler.exception(conn, ex);
}
public void exception(NHttpClientConnection conn, IOException ex) {
this.handler.exception(conn, ex);
}
public void timeout(NHttpClientConnection conn) {
this.handler.timeout(conn);
}
}
static class RequestHandle {
private final AsyncConnectionManager connMgr;
private final NHttpClientConnection conn;
private volatile boolean completed;
public RequestHandle(AsyncConnectionManager connMgr, NHttpClientConnection conn) {
super();
this.connMgr = connMgr;
this.conn = conn;
}
public boolean isCompleted() {
return this.completed;
}
public void completed() {
if (this.completed) {
return;
}
this.completed = true;
this.connMgr.releaseConnection(this.conn);
synchronized (this) {
notifyAll();
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
notifyAll();
}
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
}
static class ConnRequestCallback implements SessionRequestCallback {
private final AsyncConnectionRequest request;
ConnRequestCallback(AsyncConnectionRequest request) {
super();
this.request = request;
}
public void completed(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request successful");
}
public void cancelled(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request cancelled");
this.request.cancel();
}
public void failed(SessionRequest request) {
System.err.println(request.getRemoteAddress() + " - request failed");
IOException ex = request.getException();
if (ex != null) {
ex.printStackTrace();
}
this.request.cancel();
}
public void timeout(SessionRequest request) {
System.out.println(request.getRemoteAddress() + " - request timed out");
this.request.cancel();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpClientConnManagement.java
|
Java
|
gpl3
| 20,713
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
Default implementations for interfaces in
{@link org.apache.http org.apache.http.nio}.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/package.html
|
HTML
|
gpl3
| 1,326
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.ssl;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.impl.nio.DefaultNHttpServerConnection;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.impl.nio.reactor.SSLSetupHandler;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class SSLServerIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "http.nio.ssl-session";
private final NHttpServiceHandler handler;
private final SSLContext sslcontext;
private final SSLSetupHandler sslHandler;
private final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpServerIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
this.handler.connected(conn);
try {
sslSession.bind(SSLMode.SERVER, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpServerIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
private void ensureNotNull(final SSLIOSession ssliosession) {
if (ssliosession == null) {
throw new IllegalStateException("SSL I/O session is null");
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to cleanly terminate
sslSession.shutdown();
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/ssl/SSLServerIOEventDispatch.java
|
Java
|
gpl3
| 10,386
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.ssl;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultNHttpClientConnection;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.impl.nio.reactor.SSLSetupHandler;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class SSLClientIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "http.nio.ssl-session";
private final NHttpClientHandler handler;
private final SSLContext sslcontext;
private final SSLSetupHandler sslHandler;
private final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given SSL {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL setup handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLSetupHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpClientIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
private void ensureNotNull(final SSLIOSession ssliosession) {
if (ssliosession == null) {
throw new IllegalStateException("SSL I/O session is null");
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
ensureNotNull(sslSession);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to terminate cleanly
sslSession.shutdown();
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/ssl/SSLClientIOEventDispatch.java
|
Java
|
gpl3
| 10,483
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.codecs.DefaultHttpRequestParser;
import org.apache.http.impl.nio.codecs.DefaultHttpResponseWriter;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
/**
* Default implementation of the {@link NHttpServerConnection} interface.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultNHttpServerConnection
extends NHttpConnectionBase implements NHttpServerIOTarget {
protected final NHttpMessageParser<HttpRequest> requestParser;
protected final NHttpMessageWriter<HttpResponse> responseWriter;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param requestFactory HTTP request factory.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public DefaultNHttpServerConnection(
final IOSession session,
final HttpRequestFactory requestFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, allocator, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestParser = createRequestParser(this.inbuf, requestFactory, params);
this.responseWriter = createResponseWriter(this.outbuf, params);
}
/**
* Creates an instance of {@link NHttpMessageParser} to be used
* by this connection for parsing incoming {@link HttpRequest} messages.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpMessageParser} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageParser<HttpRequest> createRequestParser(
final SessionInputBuffer buffer,
final HttpRequestFactory requestFactory,
final HttpParams params) {
// override in derived class to specify a line parser
return new DefaultHttpRequestParser(buffer, null, requestFactory, params);
}
/**
* Creates an instance of {@link NHttpMessageWriter} to be used
* by this connection for writing out outgoing {@link HttpResponse}
* messages.
* <p>
* This method can be overridden by a super class in order to provide
* a different implementation of the {@link NHttpMessageWriter} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageWriter<HttpResponse> createResponseWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
// override in derived class to specify a line formatter
return new DefaultHttpResponseWriter(buffer, null, params);
}
public void resetInput() {
this.request = null;
this.contentDecoder = null;
this.requestParser.reset();
}
public void resetOutput() {
this.response = null;
this.contentEncoder = null;
this.responseWriter.reset();
}
public void consumeInput(final NHttpServiceHandler handler) {
if (this.status != ACTIVE) {
this.session.clearEvent(EventMask.READ);
return;
}
try {
if (this.request == null) {
int bytesRead;
do {
bytesRead = this.requestParser.fillBuffer(this.session.channel());
if (bytesRead > 0) {
this.inTransportMetrics.incrementBytesTransferred(bytesRead);
}
this.request = this.requestParser.parse();
} while (bytesRead > 0 && this.request == null);
if (this.request != null) {
if (this.request instanceof HttpEntityEnclosingRequest) {
// Receive incoming entity
HttpEntity entity = prepareDecoder(this.request);
((HttpEntityEnclosingRequest)this.request).setEntity(entity);
}
this.connMetrics.incrementRequestCount();
handler.requestReceived(this);
if (this.contentDecoder == null) {
// No request entity is expected
// Ready to receive a new request
resetInput();
}
}
if (bytesRead == -1) {
close();
}
}
if (this.contentDecoder != null) {
handler.inputReady(this, this.contentDecoder);
if (this.contentDecoder.isCompleted()) {
// Request entity received
// Ready to receive a new request
resetInput();
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} catch (HttpException ex) {
resetInput();
handler.exception(this, ex);
} finally {
// Finally set buffered input flag
this.hasBufferedInput = this.inbuf.hasData();
}
}
public void produceOutput(final NHttpServiceHandler handler) {
try {
if (this.outbuf.hasData()) {
int bytesWritten = this.outbuf.flush(this.session.channel());
if (bytesWritten > 0) {
this.outTransportMetrics.incrementBytesTransferred(bytesWritten);
}
}
if (!this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
resetOutput();
return;
} else {
if (this.contentEncoder != null) {
handler.outputReady(this, this.contentEncoder);
if (this.contentEncoder.isCompleted()) {
resetOutput();
}
}
}
if (this.contentEncoder == null && !this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
}
if (this.status != CLOSED) {
this.session.clearEvent(EventMask.WRITE);
handler.responseReady(this);
}
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} finally {
// Finally set the buffered output flag
this.hasBufferedOutput = this.outbuf.hasData();
}
}
public void submitResponse(final HttpResponse response) throws IOException, HttpException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertNotClosed();
if (this.response != null) {
throw new HttpException("Response already submitted");
}
this.responseWriter.write(response);
this.hasBufferedOutput = this.outbuf.hasData();
if (response.getStatusLine().getStatusCode() >= 200) {
this.connMetrics.incrementResponseCount();
if (response.getEntity() != null) {
this.response = response;
prepareEncoder(response);
}
}
this.session.setEvent(EventMask.WRITE);
}
public boolean isResponseSubmitted() {
return this.response != null;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpServerConnection.java
|
Java
|
gpl3
| 10,087
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.ConnectionClosedException;
import org.apache.http.Header;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpInetConnection;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentLengthStrategy;
import org.apache.http.impl.HttpConnectionMetricsImpl;
import org.apache.http.impl.entity.LaxContentLengthStrategy;
import org.apache.http.impl.entity.StrictContentLengthStrategy;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.impl.nio.codecs.ChunkDecoder;
import org.apache.http.impl.nio.codecs.ChunkEncoder;
import org.apache.http.impl.nio.codecs.IdentityDecoder;
import org.apache.http.impl.nio.codecs.IdentityEncoder;
import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder;
import org.apache.http.impl.nio.codecs.LengthDelimitedEncoder;
import org.apache.http.impl.nio.reactor.SessionInputBufferImpl;
import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl;
import org.apache.http.io.HttpTransportMetrics;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
/**
* This class serves as a base for all {@link NHttpConnection} implementations
* and implements functionality common to both client and server
* HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* </ul>
*
* @since 4.0
*/
public class NHttpConnectionBase
implements NHttpConnection, HttpInetConnection, SessionBufferStatus {
protected final ContentLengthStrategy incomingContentStrategy;
protected final ContentLengthStrategy outgoingContentStrategy;
protected final SessionInputBufferImpl inbuf;
protected final SessionOutputBufferImpl outbuf;
protected final HttpTransportMetricsImpl inTransportMetrics;
protected final HttpTransportMetricsImpl outTransportMetrics;
protected final HttpConnectionMetricsImpl connMetrics;
protected HttpContext context;
protected IOSession session;
protected SocketAddress remote;
protected volatile ContentDecoder contentDecoder;
protected volatile boolean hasBufferedInput;
protected volatile ContentEncoder contentEncoder;
protected volatile boolean hasBufferedOutput;
protected volatile HttpRequest request;
protected volatile HttpResponse response;
protected volatile int status;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public NHttpConnectionBase(
final IOSession session,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
if (session == null) {
throw new IllegalArgumentException("I/O session may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP params may not be null");
}
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
int linebuffersize = buffersize;
if (linebuffersize > 512) {
linebuffersize = 512;
}
this.inbuf = new SessionInputBufferImpl(buffersize, linebuffersize, allocator, params);
this.outbuf = new SessionOutputBufferImpl(buffersize, linebuffersize, allocator, params);
this.incomingContentStrategy = new LaxContentLengthStrategy();
this.outgoingContentStrategy = new StrictContentLengthStrategy();
this.inTransportMetrics = createTransportMetrics();
this.outTransportMetrics = createTransportMetrics();
this.connMetrics = createConnectionMetrics(
this.inTransportMetrics,
this.outTransportMetrics);
setSession(session);
this.status = ACTIVE;
}
private void setSession(final IOSession session) {
this.session = session;
this.context = new SessionHttpContext(this.session);
this.session.setBufferStatus(this);
this.remote = this.session.getRemoteAddress();
}
/**
* @since 4.1
*/
protected HttpTransportMetricsImpl createTransportMetrics() {
return new HttpTransportMetricsImpl();
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
public int getStatus() {
return this.status;
}
public HttpContext getContext() {
return this.context;
}
public HttpRequest getHttpRequest() {
return this.request;
}
public HttpResponse getHttpResponse() {
return this.response;
}
public void requestInput() {
this.session.setEvent(EventMask.READ);
}
public void requestOutput() {
this.session.setEvent(EventMask.WRITE);
}
public void suspendInput() {
this.session.clearEvent(EventMask.READ);
}
public void suspendOutput() {
this.session.clearEvent(EventMask.WRITE);
}
/**
* Initializes a specific {@link ContentDecoder} implementation based on the
* properties of the given {@link HttpMessage} and generates an instance of
* {@link HttpEntity} matching the properties of the content decoder.
*
* @param message the HTTP message.
* @return HTTP entity.
* @throws HttpException in case of an HTTP protocol violation.
*/
protected HttpEntity prepareDecoder(final HttpMessage message) throws HttpException {
BasicHttpEntity entity = new BasicHttpEntity();
long len = this.incomingContentStrategy.determineLength(message);
this.contentDecoder = createContentDecoder(
len,
this.session.channel(),
this.inbuf,
this.inTransportMetrics);
if (len == ContentLengthStrategy.CHUNKED) {
entity.setChunked(true);
entity.setContentLength(-1);
} else if (len == ContentLengthStrategy.IDENTITY) {
entity.setChunked(false);
entity.setContentLength(-1);
} else {
entity.setChunked(false);
entity.setContentLength(len);
}
Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader);
}
Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader);
}
return entity;
}
/**
* Factory method for {@link ContentDecoder} instances.
*
* @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or
* {@link ContentLengthStrategy#IDENTITY}, if unknown.
* @param channel the session channel.
* @param buffer the session buffer.
* @param metrics transport metrics.
*
* @return content decoder.
*
* @since 4.1
*/
protected ContentDecoder createContentDecoder(
final long len,
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkDecoder(channel, buffer, metrics);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityDecoder(channel, buffer, metrics);
} else {
return new LengthDelimitedDecoder(channel, buffer, metrics, len);
}
}
/**
* Initializes a specific {@link ContentEncoder} implementation based on the
* properties of the given {@link HttpMessage}.
*
* @param message the HTTP message.
* @throws HttpException in case of an HTTP protocol violation.
*/
protected void prepareEncoder(final HttpMessage message) throws HttpException {
long len = this.outgoingContentStrategy.determineLength(message);
this.contentEncoder = createContentEncoder(
len,
this.session.channel(),
this.outbuf,
this.outTransportMetrics);
}
/**
* Factory method for {@link ContentEncoder} instances.
*
* @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or
* {@link ContentLengthStrategy#IDENTITY}, if unknown.
* @param channel the session channel.
* @param buffer the session buffer.
* @param metrics transport metrics.
*
* @return content encoder.
*
* @since 4.1
*/
protected ContentEncoder createContentEncoder(
final long len,
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkEncoder(channel, buffer, metrics);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityEncoder(channel, buffer, metrics);
} else {
return new LengthDelimitedEncoder(channel, buffer, metrics, len);
}
}
public boolean hasBufferedInput() {
return this.hasBufferedInput;
}
public boolean hasBufferedOutput() {
return this.hasBufferedOutput;
}
/**
* Assets if the connection is still open.
*
* @throws ConnectionClosedException in case the connection has already
* been closed.
*/
protected void assertNotClosed() throws ConnectionClosedException {
if (this.status != ACTIVE) {
throw new ConnectionClosedException("Connection is closed");
}
}
public void close() throws IOException {
if (this.status != ACTIVE) {
return;
}
this.status = CLOSING;
if (this.outbuf.hasData()) {
this.session.setEvent(EventMask.WRITE);
} else {
this.session.close();
this.status = CLOSED;
}
}
public boolean isOpen() {
return this.status == ACTIVE && !this.session.isClosed();
}
public boolean isStale() {
return this.session.isClosed();
}
public InetAddress getLocalAddress() {
SocketAddress address = this.session.getLocalAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getAddress();
} else {
return null;
}
}
public int getLocalPort() {
SocketAddress address = this.session.getLocalAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
SocketAddress address = this.session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getAddress();
} else {
return null;
}
}
public int getRemotePort() {
SocketAddress address = this.session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
return ((InetSocketAddress) address).getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
this.session.setSocketTimeout(timeout);
}
public int getSocketTimeout() {
return this.session.getSocketTimeout();
}
public void shutdown() throws IOException {
this.status = CLOSED;
this.session.shutdown();
}
public HttpConnectionMetrics getMetrics() {
return this.connMetrics;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(this.remote);
if (this.status == CLOSED) {
buffer.append("(closed)");
}
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/NHttpConnectionBase.java
|
Java
|
gpl3
| 14,657
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.protocol.HttpContext;
class SessionHttpContext implements HttpContext {
private final IOSession iosession;
public SessionHttpContext(final IOSession iosession) {
super();
this.iosession = iosession;
}
public Object getAttribute(final String id) {
return this.iosession.getAttribute(id);
}
public Object removeAttribute(final String id) {
return this.iosession.removeAttribute(id);
}
public void setAttribute(final String id, final Object obj) {
this.iosession.setAttribute(id, obj);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/SessionHttpContext.java
|
Java
|
gpl3
| 1,859
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for plain
* (unencrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultClientIOEventDispatch implements IOEventDispatch {
protected final ByteBufferAllocator allocator;
protected final NHttpClientHandler handler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler.
*
* @param handler the client protocol handler.
* @param params HTTP parameters.
*/
public DefaultClientIOEventDispatch(
final NHttpClientHandler handler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.allocator = createByteBufferAllocator();
this.handler = handler;
this.params = params;
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
this.allocator,
this.params);
}
public void connected(final IOSession session) {
NHttpClientIOTarget conn = createConnection(session);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.handler.connected(conn, attachment);
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpClientIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.consumeInput(this.handler);
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.produceOutput(this.handler);
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
this.handler.timeout(conn);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultClientIOEventDispatch.java
|
Java
|
gpl3
| 6,495
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for plain
* (unencrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultServerIOEventDispatch implements IOEventDispatch {
protected final ByteBufferAllocator allocator;
protected final NHttpServiceHandler handler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler.
*
* @param handler the server protocol handler.
* @param params HTTP parameters.
*/
public DefaultServerIOEventDispatch(
final NHttpServiceHandler handler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.allocator = createByteBufferAllocator();
this.handler = handler;
this.params = params;
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
this.allocator,
this.params);
}
public void connected(final IOSession session) {
NHttpServerIOTarget conn = createConnection(session);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.handler.connected(conn);
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
private void ensureNotNull(final NHttpServerIOTarget conn) {
if (conn == null) {
throw new IllegalStateException("HTTP connection is null");
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.consumeInput(this.handler);
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
conn.produceOutput(this.handler);
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
ensureNotNull(conn);
this.handler.timeout(conn);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultServerIOEventDispatch.java
|
Java
|
gpl3
| 6,392
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.MalformedChunkCodingException;
import org.apache.http.TruncatedChunkException;
import org.apache.http.message.BufferedHeader;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Implements chunked transfer coding. The content is received in small chunks.
* Entities transferred using this encoder can be of unlimited length.
*
* @since 4.0
*/
public class ChunkDecoder extends AbstractContentDecoder {
private static final int READ_CONTENT = 0;
private static final int READ_FOOTERS = 1;
private static final int COMPLETED = 2;
private int state;
private boolean endOfChunk;
private boolean endOfStream;
private CharArrayBuffer lineBuf;
private int chunkSize;
private int pos;
private final List<CharArrayBuffer> trailerBufs;
private Header[] footers;
public ChunkDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
this.state = READ_CONTENT;
this.chunkSize = -1;
this.pos = 0;
this.endOfChunk = false;
this.endOfStream = false;
this.trailerBufs = new ArrayList<CharArrayBuffer>();
}
private void readChunkHead() throws IOException {
if (this.endOfChunk) {
if (this.buffer.length() < 2) {
return;
}
int cr = this.buffer.read();
int lf = this.buffer.read();
if (cr != HTTP.CR || lf != HTTP.LF) {
throw new MalformedChunkCodingException("CRLF expected at end of chunk");
}
this.endOfChunk = false;
}
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(32);
} else {
this.lineBuf.clear();
}
if (this.buffer.readLine(this.lineBuf, this.endOfStream)) {
int separator = this.lineBuf.indexOf(';');
if (separator < 0) {
separator = this.lineBuf.length();
}
try {
String s = this.lineBuf.substringTrimmed(0, separator);
this.chunkSize = Integer.parseInt(s, 16);
} catch (NumberFormatException e) {
throw new MalformedChunkCodingException("Bad chunk header");
}
this.pos = 0;
}
}
private void parseHeader() {
CharArrayBuffer current = this.lineBuf;
int count = this.trailerBufs.size();
if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) {
// Handle folded header line
CharArrayBuffer previous = this.trailerBufs.get(count - 1);
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
this.trailerBufs.add(current);
this.lineBuf = null;
}
}
private void processFooters() throws IOException {
int count = this.trailerBufs.size();
if (count > 0) {
this.footers = new Header[this.trailerBufs.size()];
for (int i = 0; i < this.trailerBufs.size(); i++) {
CharArrayBuffer buffer = this.trailerBufs.get(i);
try {
this.footers[i] = new BufferedHeader(buffer);
} catch (ParseException ex) {
throw new IOException(ex.getMessage());
}
}
}
this.trailerBufs.clear();
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.state == COMPLETED) {
return -1;
}
int totalRead = 0;
while (this.state != COMPLETED) {
if (!this.buffer.hasData() || this.chunkSize == -1) {
int bytesRead = this.buffer.fill(this.channel);
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
if (bytesRead == -1) {
this.endOfStream = true;
}
}
switch (this.state) {
case READ_CONTENT:
if (this.chunkSize == -1) {
readChunkHead();
if (this.chunkSize == -1) {
// Unable to read a chunk head
if (this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
}
return totalRead;
}
if (this.chunkSize == 0) {
// Last chunk. Read footers
this.chunkSize = -1;
this.state = READ_FOOTERS;
break;
}
}
int maxLen = this.chunkSize - this.pos;
int len = this.buffer.read(dst, maxLen);
if (len > 0) {
this.pos += len;
totalRead += len;
} else {
if (!this.buffer.hasData() && this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
throw new TruncatedChunkException("Truncated chunk "
+ "( expected size: " + this.chunkSize
+ "; actual size: " + this.pos + ")");
}
}
if (this.pos == this.chunkSize) {
// At the end of the chunk
this.chunkSize = -1;
this.pos = 0;
this.endOfChunk = true;
break;
}
return totalRead;
case READ_FOOTERS:
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(32);
} else {
this.lineBuf.clear();
}
if (!this.buffer.readLine(this.lineBuf, this.endOfStream)) {
// Unable to read a footer
if (this.endOfStream) {
this.state = COMPLETED;
this.completed = true;
}
return totalRead;
}
if (this.lineBuf.length() > 0) {
parseHeader();
} else {
this.state = COMPLETED;
this.completed = true;
processFooters();
}
break;
}
}
return totalRead;
}
public Header[] getFooters() {
if (this.footers != null) {
return this.footers.clone();
} else {
return new Header[] {};
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[chunk-coded; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkDecoder.java
|
Java
|
gpl3
| 9,145
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
Default implementations for interfaces in
{@link org.apache.http.io org.apache.http.nio.codecs}.
<br/>
There are implementations of the transport encodings used by HTTP,
in particular the chunked coding for
{@link org.apache.http.impl.nio.codecs.ChunkEncoder sending} and
{@link org.apache.http.impl.nio.codecs.ChunkDecoder receiving} entities.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/package.html
|
HTML
|
gpl3
| 1,586
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpResponse}s.
*
* @since 4.1
*/
public class DefaultHttpResponseWriter extends AbstractMessageWriter<HttpResponse> {
public DefaultHttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpResponse message) throws IOException {
CharArrayBuffer buffer = lineFormatter.formatStatusLine(
this.lineBuf, message.getStatusLine());
this.sessionBuffer.writeLine(buffer);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseWriter.java
|
Java
|
gpl3
| 2,231
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.StatusLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpResponse}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpResponseParser}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpResponseParser extends AbstractMessageParser {
private final HttpResponseFactory responseFactory;
public HttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
@Override
protected HttpMessage createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
StatusLine statusline = lineParser.parseStatusLine(buffer, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/HttpResponseParser.java
|
Java
|
gpl3
| 3,122
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.ConnectionClosedException;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
/**
* Content decoder that cuts off after a defined number of bytes. This class
* is used to receive content of HTTP messages where the end of the content
* entity is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* This decoder is optimized to transfer data directly from the underlying
* I/O session's channel to a {@link FileChannel}, whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class LengthDelimitedDecoder extends AbstractContentDecoder
implements FileContentDecoder {
private final long contentLength;
private long len;
public LengthDelimitedDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics,
long contentLength) {
super(channel, buffer, metrics);
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.contentLength = contentLength;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
int bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(chunk, this.buffer.length());
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (dst.remaining() > chunk) {
int oldLimit = dst.limit();
int newLimit = oldLimit - (dst.remaining() - chunk);
dst.limit(newLimit);
bytesRead = this.channel.read(dst);
dst.limit(oldLimit);
} else {
bytesRead = this.channel.read(dst);
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
if (this.len < this.contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ this.contentLength + "; received: " + this.len);
}
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
if (this.completed && bytesRead == 0) {
return -1;
} else {
return bytesRead;
}
}
public long transfer(
final FileChannel dst,
long position,
long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return -1;
}
int chunk = (int) Math.min((this.contentLength - this.len), Integer.MAX_VALUE);
long bytesRead;
if (this.buffer.hasData()) {
int maxLen = Math.min(chunk, this.buffer.length());
dst.position(position);
bytesRead = this.buffer.read(dst, maxLen);
} else {
if (count > chunk) {
count = chunk;
}
if (this.channel.isOpen()) {
if(dst.size() < position)
throw new IOException("FileChannel.size() [" + dst.size() +
"] < position [" + position +
"]. Please grow the file before writing.");
bytesRead = dst.transferFrom(this.channel, position, count);
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
if (this.len < this.contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ this.contentLength + "; received: " + this.len);
}
}
this.len += bytesRead;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesRead;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[content length: ");
buffer.append(this.contentLength);
buffer.append("; pos: ");
buffer.append(this.len);
buffer.append("; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedDecoder.java
|
Java
|
gpl3
| 6,536
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.util.Iterator;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.message.LineFormatter;
import org.apache.http.message.BasicLineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Abstract {@link NHttpMessageWriter} that serves as a base for all message
* writer implementations.
*
* @since 4.0
*/
public abstract class AbstractMessageWriter<T extends HttpMessage> implements NHttpMessageWriter<T> {
protected final SessionOutputBuffer sessionBuffer;
protected final CharArrayBuffer lineBuf;
protected final LineFormatter lineFormatter;
/**
* Creates an instance of this class.
*
* @param buffer the session output buffer.
* @param formatter the line formatter.
* @param params HTTP parameters.
*/
public AbstractMessageWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.sessionBuffer = buffer;
this.lineBuf = new CharArrayBuffer(64);
this.lineFormatter = (formatter != null) ?
formatter : BasicLineFormatter.DEFAULT;
}
public void reset() {
}
/**
* Writes out the first line of {@link HttpMessage}.
*
* @param message HTTP message.
* @throws HttpException in case of HTTP protocol violation
*/
protected abstract void writeHeadLine(T message) throws IOException;
public void write(final T message) throws IOException, HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
writeHeadLine(message);
for (Iterator<?> it = message.headerIterator(); it.hasNext(); ) {
Header header = (Header) it.next();
this.sessionBuffer.writeLine
(lineFormatter.formatHeader(this.lineBuf, header));
}
this.lineBuf.clear();
this.sessionBuffer.writeLine(this.lineBuf);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessageWriter.java
|
Java
|
gpl3
| 3,631
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.RequestLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpRequest}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class DefaultHttpRequestParser extends AbstractMessageParser<HttpRequest> {
private final HttpRequestFactory requestFactory;
public DefaultHttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
}
@Override
protected HttpRequest createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor);
return this.requestFactory.newHttpRequest(requestLine);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestParser.java
|
Java
|
gpl3
| 2,999
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
/**
* Abstract {@link ContentDecoder} that serves as a base for all content
* decoder implementations.
*
* @since 4.0
*/
public abstract class AbstractContentDecoder implements ContentDecoder {
protected final ReadableByteChannel channel;
protected final SessionInputBuffer buffer;
protected final HttpTransportMetricsImpl metrics;
protected boolean completed;
/**
* Creates an instance of this class.
*
* @param channel the source channel.
* @param buffer the session input buffer that can be used to store
* session data for intermediate processing.
* @param metrics Transport metrics of the underlying HTTP transport.
*/
public AbstractContentDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super();
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (metrics == null) {
throw new IllegalArgumentException("Transport metrics may not be null");
}
this.buffer = buffer;
this.channel = channel;
this.metrics = metrics;
}
public boolean isCompleted() {
return this.completed;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContentDecoder.java
|
Java
|
gpl3
| 2,864
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Content encoder that cuts off after a defined number of bytes. This class
* is used to send content of HTTP messages where the end of the content entity
* is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* This decoder is optimized to transfer data directly from
* a {@link FileChannel} to the underlying I/O session's channel whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class LengthDelimitedEncoder extends AbstractContentEncoder
implements FileContentEncoder {
private final long contentLength;
private long len;
public LengthDelimitedEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics,
long contentLength) {
super(channel, buffer, metrics);
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.contentLength = contentLength;
this.len = 0;
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int lenRemaining = (int) (this.contentLength - this.len);
int bytesWritten;
if (src.remaining() > lenRemaining) {
int oldLimit = src.limit();
int newLimit = oldLimit - (src.remaining() - lenRemaining);
src.limit(newLimit);
bytesWritten = this.channel.write(src);
src.limit(oldLimit);
} else {
bytesWritten = this.channel.write(src);
}
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
this.len += bytesWritten;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesWritten;
}
public long transfer(
final FileChannel src,
long position,
long count) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int lenRemaining = (int) (this.contentLength - this.len);
long bytesWritten;
if (count > lenRemaining) {
count = lenRemaining;
}
bytesWritten = src.transferTo(position, count, this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
this.len += bytesWritten;
if (this.len >= this.contentLength) {
this.completed = true;
}
return bytesWritten;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[content length: ");
buffer.append(this.contentLength);
buffer.append("; pos: ");
buffer.append(this.len);
buffer.append("; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/LengthDelimitedEncoder.java
|
Java
|
gpl3
| 4,713
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Abstract {@link ContentEncoder} that serves as a base for all content
* encoder implementations.
*
* @since 4.0
*/
public abstract class AbstractContentEncoder implements ContentEncoder {
protected final WritableByteChannel channel;
protected final SessionOutputBuffer buffer;
protected final HttpTransportMetricsImpl metrics;
protected boolean completed;
/**
* Creates an instance of this class.
*
* @param channel the destination channel.
* @param buffer the session output buffer that can be used to store
* session data for intermediate processing.
* @param metrics Transport metrics of the underlying HTTP transport.
*/
public AbstractContentEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super();
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (metrics == null) {
throw new IllegalArgumentException("Transport metrics may not be null");
}
this.buffer = buffer;
this.channel = channel;
this.metrics = metrics;
}
public boolean isCompleted() {
return this.completed;
}
public void complete() throws IOException {
this.completed = true;
}
protected void assertNotCompleted() {
if (this.completed) {
throw new IllegalStateException("Encoding process already completed");
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractContentEncoder.java
|
Java
|
gpl3
| 3,159
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.ParseException;
import org.apache.http.ProtocolException;
import org.apache.http.message.LineParser;
import org.apache.http.message.BasicLineParser;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Abstract {@link NHttpMessageParser} that serves as a base for all message
* parser implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractMessageParser<T extends HttpMessage> implements NHttpMessageParser<T> {
private final SessionInputBuffer sessionBuffer;
private static final int READ_HEAD_LINE = 0;
private static final int READ_HEADERS = 1;
private static final int COMPLETED = 2;
private int state;
private boolean endOfStream;
private T message;
private CharArrayBuffer lineBuf;
private final List<CharArrayBuffer> headerBufs;
private int maxLineLen = -1;
private int maxHeaderCount = -1;
protected final LineParser lineParser;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param params HTTP parameters.
*/
public AbstractMessageParser(final SessionInputBuffer buffer, final LineParser parser, final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.sessionBuffer = buffer;
this.state = READ_HEAD_LINE;
this.endOfStream = false;
this.headerBufs = new ArrayList<CharArrayBuffer>();
this.maxLineLen = params.getIntParameter(
CoreConnectionPNames.MAX_LINE_LENGTH, -1);
this.maxHeaderCount = params.getIntParameter(
CoreConnectionPNames.MAX_HEADER_COUNT, -1);
this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT;
}
public void reset() {
this.state = READ_HEAD_LINE;
this.endOfStream = false;
this.headerBufs.clear();
this.message = null;
}
public int fillBuffer(final ReadableByteChannel channel) throws IOException {
int bytesRead = this.sessionBuffer.fill(channel);
if (bytesRead == -1) {
this.endOfStream = true;
}
return bytesRead;
}
/**
* Creates {@link HttpMessage} instance based on the content of the input
* buffer containing the first line of the incoming HTTP message.
*
* @param buffer the line buffer.
* @return HTTP message.
* @throws HttpException in case of HTTP protocol violation
* @throws ParseException in case of a parse error.
*/
protected abstract T createMessage(CharArrayBuffer buffer)
throws HttpException, ParseException;
private void parseHeadLine() throws HttpException, ParseException {
this.message = createMessage(this.lineBuf);
}
private void parseHeader() throws IOException {
CharArrayBuffer current = this.lineBuf;
int count = this.headerBufs.size();
if ((this.lineBuf.charAt(0) == ' ' || this.lineBuf.charAt(0) == '\t') && count > 0) {
// Handle folded header line
CharArrayBuffer previous = this.headerBufs.get(count - 1);
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
if (this.maxLineLen > 0
&& previous.length() + 1 + current.length() - i > this.maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
this.headerBufs.add(current);
this.lineBuf = null;
}
}
public T parse() throws IOException, HttpException {
while (this.state != COMPLETED) {
if (this.lineBuf == null) {
this.lineBuf = new CharArrayBuffer(64);
} else {
this.lineBuf.clear();
}
boolean lineComplete = this.sessionBuffer.readLine(this.lineBuf, this.endOfStream);
if (this.maxLineLen > 0 &&
(this.lineBuf.length() > this.maxLineLen ||
(!lineComplete && this.sessionBuffer.length() > this.maxLineLen))) {
throw new IOException("Maximum line length limit exceeded");
}
if (!lineComplete) {
break;
}
switch (this.state) {
case READ_HEAD_LINE:
try {
parseHeadLine();
} catch (ParseException px) {
throw new ProtocolException(px.getMessage(), px);
}
this.state = READ_HEADERS;
break;
case READ_HEADERS:
if (this.lineBuf.length() > 0) {
if (this.maxHeaderCount > 0 && headerBufs.size() >= this.maxHeaderCount) {
throw new IOException("Maximum header count exceeded");
}
parseHeader();
} else {
this.state = COMPLETED;
}
break;
}
if (this.endOfStream && !this.sessionBuffer.hasData()) {
this.state = COMPLETED;
}
}
if (this.state == COMPLETED) {
for (int i = 0; i < this.headerBufs.size(); i++) {
CharArrayBuffer buffer = this.headerBufs.get(i);
try {
this.message.addHeader(lineParser.parseHeader(buffer));
} catch (ParseException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
}
return this.message;
} else {
return null;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/AbstractMessageParser.java
|
Java
|
gpl3
| 8,036
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
/**
* Content encoder that writes data without any transformation. The end of
* the content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* This decoder is optimized to transfer data directly from
* a {@link FileChannel} to the underlying I/O session's channel whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class IdentityEncoder extends AbstractContentEncoder
implements FileContentEncoder {
public IdentityEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int bytesWritten = this.channel.write(src);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
return bytesWritten;
}
public long transfer(
final FileChannel src,
long position,
long count) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
long bytesWritten = src.transferTo(position, count, this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
return bytesWritten;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[identity; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityEncoder.java
|
Java
|
gpl3
| 3,375
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.StatusLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpResponse}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.1
*/
public class DefaultHttpResponseParser extends AbstractMessageParser<HttpResponse> {
private final HttpResponseFactory responseFactory;
public DefaultHttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
@Override
protected HttpResponse createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
StatusLine statusline = lineParser.parseStatusLine(buffer, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpResponseParser.java
|
Java
|
gpl3
| 3,017
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpRequest}s.
*
* @since 4.1
*/
public class DefaultHttpRequestWriter extends AbstractMessageWriter<HttpRequest> {
public DefaultHttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpRequest message) throws IOException {
CharArrayBuffer buffer = lineFormatter.formatRequestLine(
this.lineBuf, message.getRequestLine());
this.sessionBuffer.writeLine(buffer);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/DefaultHttpRequestWriter.java
|
Java
|
gpl3
| 2,225
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.RequestLine;
import org.apache.http.ParseException;
import org.apache.http.message.LineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageParser} implementation for {@link HttpRequest}s.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpRequestParser}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpRequestParser extends AbstractMessageParser {
private final HttpRequestFactory requestFactory;
public HttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
}
@Override
protected HttpMessage createMessage(final CharArrayBuffer buffer)
throws HttpException, ParseException {
ParserCursor cursor = new ParserCursor(0, buffer.length());
RequestLine requestLine = lineParser.parseRequestLine(buffer, cursor);
return this.requestFactory.newHttpRequest(requestLine);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/HttpRequestParser.java
|
Java
|
gpl3
| 3,105
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.io.BufferInfo;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.util.CharArrayBuffer;
/**
* Implements chunked transfer coding. The content is sent in small chunks.
* Entities transferred using this decoder can be of unlimited length.
*
* @since 4.0
*/
public class ChunkEncoder extends AbstractContentEncoder {
private final CharArrayBuffer lineBuffer;
private final BufferInfo bufferinfo;
public ChunkEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
this.lineBuffer = new CharArrayBuffer(16);
if (buffer instanceof BufferInfo) {
this.bufferinfo = (BufferInfo) buffer;
} else {
this.bufferinfo = null;
}
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
assertNotCompleted();
int chunk = src.remaining();
if (chunk == 0) {
return 0;
}
long bytesWritten = this.buffer.flush(this.channel);
if (bytesWritten > 0) {
this.metrics.incrementBytesTransferred(bytesWritten);
}
int avail;
if (this.bufferinfo != null) {
avail = this.bufferinfo.available();
} else {
avail = 4096;
}
// subtract the length of the longest chunk header
// 12345678\r\n
// <chunk-data>\r\n
avail -= 12;
if (avail <= 0) {
return 0;
} else if (avail < chunk) {
// write no more than 'avail' bytes
chunk = avail;
this.lineBuffer.clear();
this.lineBuffer.append(Integer.toHexString(chunk));
this.buffer.writeLine(this.lineBuffer);
int oldlimit = src.limit();
src.limit(src.position() + chunk);
this.buffer.write(src);
src.limit(oldlimit);
} else {
// write all
this.lineBuffer.clear();
this.lineBuffer.append(Integer.toHexString(chunk));
this.buffer.writeLine(this.lineBuffer);
this.buffer.write(src);
}
this.lineBuffer.clear();
this.buffer.writeLine(this.lineBuffer);
return chunk;
}
@Override
public void complete() throws IOException {
assertNotCompleted();
this.lineBuffer.clear();
this.lineBuffer.append("0");
this.buffer.writeLine(this.lineBuffer);
this.lineBuffer.clear();
this.buffer.writeLine(this.lineBuffer);
this.completed = true; // == super.complete()
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[chunk-coded; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/ChunkEncoder.java
|
Java
|
gpl3
| 4,416
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpResponse}s.
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpResponseWriter}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpResponseWriter extends AbstractMessageWriter {
public HttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpMessage message)
throws IOException {
final CharArrayBuffer buffer = lineFormatter.formatStatusLine
(this.lineBuf, ((HttpResponse) message).getStatusLine());
this.sessionBuffer.writeLine(buffer);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/HttpResponseWriter.java
|
Java
|
gpl3
| 2,364
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.message.LineFormatter;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.util.CharArrayBuffer;
/**
* Default {@link NHttpMessageWriter} implementation for {@link HttpRequest}s.
*
* @since 4.0
*
* @deprecated use {@link DefaultHttpRequestWriter}
*/
@SuppressWarnings("rawtypes")
@Deprecated
public class HttpRequestWriter extends AbstractMessageWriter {
public HttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
@Override
protected void writeHeadLine(final HttpMessage message)
throws IOException {
final CharArrayBuffer buffer = lineFormatter.formatRequestLine
(this.lineBuf, ((HttpRequest) message).getRequestLine());
this.sessionBuffer.writeLine(buffer);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/HttpRequestWriter.java
|
Java
|
gpl3
| 2,358
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.nio.FileContentDecoder;
import org.apache.http.nio.reactor.SessionInputBuffer;
/**
* Content decoder that reads data without any transformation. The end of the
* content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* This decoder is optimized to transfer data directly from the underlying
* I/O session's channel to a {@link FileChannel}, whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
public class IdentityDecoder extends AbstractContentDecoder
implements FileContentDecoder {
public IdentityDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
/**
* Sets the completed status of this decoder. Normally this is not necessary
* (the decoder will automatically complete when the underlying channel
* returns EOF). It is useful to mark the decoder as completed if you have
* some other means to know all the necessary data has been read and want to
* reuse the underlying connection for more messages.
*/
public void setCompleted(boolean completed) {
this.completed = completed;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int bytesRead;
if (this.buffer.hasData()) {
bytesRead = this.buffer.read(dst);
} else {
bytesRead = this.channel.read(dst);
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
public long transfer(
final FileChannel dst,
long position,
long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return 0;
}
long bytesRead;
if (this.buffer.hasData()) {
dst.position(position);
bytesRead = this.buffer.read(dst);
} else {
if (this.channel.isOpen()) {
if(dst.size() < position)
throw new IOException("FileChannel.size() [" + dst.size() +
"] < position [" + position +
"]. Please grow the file before writing.");
bytesRead = dst.transferFrom(this.channel, position, count);
if (bytesRead == 0) {
bytesRead = buffer.fill(this.channel);
}
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[identity; completed: ");
buffer.append(this.completed);
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/codecs/IdentityDecoder.java
|
Java
|
gpl3
| 4,946
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.nio.codecs.DefaultHttpRequestWriter;
import org.apache.http.impl.nio.codecs.DefaultHttpResponseParser;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
/**
* Default implementation of the {@link NHttpClientConnection} interface.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultNHttpClientConnection
extends NHttpConnectionBase implements NHttpClientIOTarget {
protected final NHttpMessageParser<HttpResponse> responseParser;
protected final NHttpMessageWriter<HttpRequest> requestWriter;
/**
* Creates a new instance of this class given the underlying I/O session.
*
* @param session the underlying I/O session.
* @param responseFactory HTTP response factory.
* @param allocator byte buffer allocator.
* @param params HTTP parameters.
*/
public DefaultNHttpClientConnection(
final IOSession session,
final HttpResponseFactory responseFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(session, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseParser = createResponseParser(this.inbuf, responseFactory, params);
this.requestWriter = createRequestWriter(this.outbuf, params);
this.hasBufferedInput = false;
this.hasBufferedOutput = false;
this.session.setBufferStatus(this);
}
/**
* Creates an instance of {@link NHttpMessageParser} to be used
* by this connection for parsing incoming {@link HttpResponse} messages.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpMessageParser} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
// override in derived class to specify a line parser
return new DefaultHttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link NHttpMessageWriter} to be used
* by this connection for writing out outgoing {@link HttpRequest} messages.
* <p>
* This method can be overridden by a super class in order to provide
* a different implementation of the {@link NHttpMessageWriter} interface.
*
* @return HTTP response parser.
*/
protected NHttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
// override in derived class to specify a line formatter
return new DefaultHttpRequestWriter(buffer, null, params);
}
public void resetInput() {
this.response = null;
this.contentDecoder = null;
this.responseParser.reset();
}
public void resetOutput() {
this.request = null;
this.contentEncoder = null;
this.requestWriter.reset();
}
public void consumeInput(final NHttpClientHandler handler) {
if (this.status != ACTIVE) {
this.session.clearEvent(EventMask.READ);
return;
}
try {
if (this.response == null) {
int bytesRead;
do {
bytesRead = this.responseParser.fillBuffer(this.session.channel());
if (bytesRead > 0) {
this.inTransportMetrics.incrementBytesTransferred(bytesRead);
}
this.response = this.responseParser.parse();
} while (bytesRead > 0 && this.response == null);
if (this.response != null) {
if (this.response.getStatusLine().getStatusCode() >= 200) {
HttpEntity entity = prepareDecoder(this.response);
this.response.setEntity(entity);
this.connMetrics.incrementResponseCount();
}
handler.responseReceived(this);
if (this.contentDecoder == null) {
resetInput();
}
}
if (bytesRead == -1) {
close();
}
}
if (this.contentDecoder != null) {
handler.inputReady(this, this.contentDecoder);
if (this.contentDecoder.isCompleted()) {
// Response entity received
// Ready to receive a new response
resetInput();
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} catch (HttpException ex) {
resetInput();
handler.exception(this, ex);
} finally {
// Finally set buffered input flag
this.hasBufferedInput = this.inbuf.hasData();
}
}
public void produceOutput(final NHttpClientHandler handler) {
try {
if (this.outbuf.hasData()) {
int bytesWritten = this.outbuf.flush(this.session.channel());
if (bytesWritten > 0) {
this.outTransportMetrics.incrementBytesTransferred(bytesWritten);
}
}
if (!this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
resetOutput();
return;
} else {
if (this.contentEncoder != null) {
handler.outputReady(this, this.contentEncoder);
if (this.contentEncoder.isCompleted()) {
resetOutput();
}
}
}
if (this.contentEncoder == null && !this.outbuf.hasData()) {
if (this.status == CLOSING) {
this.session.close();
this.status = CLOSED;
}
if (this.status != CLOSED) {
this.session.clearEvent(EventMask.WRITE);
handler.requestReady(this);
}
}
}
} catch (IOException ex) {
handler.exception(this, ex);
} finally {
// Finally set buffered output flag
this.hasBufferedOutput = this.outbuf.hasData();
}
}
public void submitRequest(final HttpRequest request) throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertNotClosed();
if (this.request != null) {
throw new HttpException("Request already submitted");
}
this.requestWriter.write(request);
this.hasBufferedOutput = this.outbuf.hasData();
if (request instanceof HttpEntityEnclosingRequest
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
prepareEncoder(request);
this.request = request;
}
this.connMetrics.incrementRequestCount();
this.session.setEvent(EventMask.WRITE);
}
public boolean isRequestSubmitted() {
return this.request != null;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/DefaultNHttpClientConnection.java
|
Java
|
gpl3
| 10,015
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.nio.NHttpServerIOTarget;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) server-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch}
*/
@Deprecated
public class SSLServerIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "SSL_SESSION";
protected final NHttpServiceHandler handler;
protected final SSLContext sslcontext;
protected final SSLIOSessionHandler sslHandler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP service handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the server protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLServerIOEventDispatch(
final NHttpServiceHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* by HTTP connections for creating {@link HttpRequest} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link DefaultNHttpServerConnection} based on the
* given {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpServerIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpServerIOTarget createConnection(final IOSession session) {
return new DefaultNHttpServerConnection(
session,
createHttpRequestFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpServerIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
this.handler.connected(conn);
try {
sslSession.bind(SSLMode.SERVER, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
public void inputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpServerIOTarget conn =
(NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to cleanly terminate
sslSession.shutdown();
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLServerIOEventDispatch.java
|
Java
|
gpl3
| 9,854
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio;
import java.io.IOException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.impl.nio.reactor.SSLIOSessionHandler;
import org.apache.http.impl.nio.reactor.SSLMode;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.NHttpClientIOTarget;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
/**
* Default implementation of {@link IOEventDispatch} interface for SSL
* (encrypted) client-side HTTP connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*
* @deprecated use {@link org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch}
*/
@Deprecated
public class SSLClientIOEventDispatch implements IOEventDispatch {
private static final String SSL_SESSION = "SSL_SESSION";
protected final NHttpClientHandler handler;
protected final SSLContext sslcontext;
protected final SSLIOSessionHandler sslHandler;
protected final HttpParams params;
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler,
final HttpParams params) {
super();
if (handler == null) {
throw new IllegalArgumentException("HTTP client handler may not be null");
}
if (sslcontext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.handler = handler;
this.params = params;
this.sslcontext = sslcontext;
this.sslHandler = sslHandler;
}
/**
* Creates a new instance of this class to be used for dispatching I/O event
* notifications to the given protocol handler using the given
* {@link SSLContext}. This I/O dispatcher will transparently handle SSL
* protocol aspects for HTTP connections.
*
* @param handler the client protocol handler.
* @param sslcontext the SSL context.
* @param params HTTP parameters.
*/
public SSLClientIOEventDispatch(
final NHttpClientHandler handler,
final SSLContext sslcontext,
final HttpParams params) {
this(handler, sslcontext, null, params);
}
/**
* Creates an instance of {@link HeapByteBufferAllocator} to be used
* by HTTP connections for allocating {@link java.nio.ByteBuffer} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link ByteBufferAllocator} interface.
*
* @return byte buffer allocator.
*/
protected ByteBufferAllocator createByteBufferAllocator() {
return new HeapByteBufferAllocator();
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* by HTTP connections for creating {@link HttpResponse} objects.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link DefaultNHttpClientConnection} based on the
* given SSL {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link NHttpClientIOTarget} interface.
*
* @param session the underlying SSL I/O session.
*
* @return newly created HTTP connection.
*/
protected NHttpClientIOTarget createConnection(final IOSession session) {
return new DefaultNHttpClientConnection(
session,
createHttpResponseFactory(),
createByteBufferAllocator(),
this.params);
}
/**
* Creates an instance of {@link SSLIOSession} decorating the given
* {@link IOSession}.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of SSL I/O session.
*
* @param session the underlying I/O session.
* @param sslcontext the SSL context.
* @param sslHandler the SSL handler.
* @return newly created SSL I/O session.
*/
protected SSLIOSession createSSLIOSession(
final IOSession session,
final SSLContext sslcontext,
final SSLIOSessionHandler sslHandler) {
return new SSLIOSession(session, sslcontext, sslHandler);
}
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void disconnected(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null) {
this.handler.closed(conn);
}
}
public void inputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppInputReady()) {
conn.consumeInput(this.handler);
}
sslSession.inboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void outputReady(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
try {
if (sslSession.isAppOutputReady()) {
conn.produceOutput(this.handler);
}
sslSession.outboundTransport();
} catch (IOException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
public void timeout(final IOSession session) {
NHttpClientIOTarget conn =
(NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION);
SSLIOSession sslSession =
(SSLIOSession) session.getAttribute(SSL_SESSION);
this.handler.timeout(conn);
synchronized (sslSession) {
if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) {
// The session failed to terminate cleanly
sslSession.shutdown();
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/SSLClientIOEventDispatch.java
|
Java
|
gpl3
| 9,951
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.util.Date;
/**
* A {@link Throwable} instance along with a time stamp.
*
* @since 4.0
*/
public class ExceptionEvent {
private final Throwable ex;
private final long time;
public ExceptionEvent(final Throwable ex, final Date timestamp) {
super();
this.ex = ex;
if (timestamp != null) {
this.time = timestamp.getTime();
} else {
this.time = 0;
}
}
public ExceptionEvent(final Exception ex) {
this(ex, new Date());
}
public Throwable getCause() {
return ex;
}
public Date getTimestamp() {
return new Date(this.time);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(new Date(this.time));
buffer.append(" ");
buffer.append(this.ex);
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ExceptionEvent.java
|
Java
|
gpl3
| 2,140
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ExpandableBuffer;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Default implementation of {@link SessionInputBuffer} based on
* the {@link ExpandableBuffer} class.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
public class SessionInputBufferImpl extends ExpandableBuffer implements SessionInputBuffer {
private CharBuffer charbuffer = null;
private Charset charset = null;
private CharsetDecoder chardecoder = null;
public SessionInputBufferImpl(
int buffersize,
int linebuffersize,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(buffersize, allocator);
this.charbuffer = CharBuffer.allocate(linebuffersize);
this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params));
this.chardecoder = this.charset.newDecoder();
}
public SessionInputBufferImpl(
int buffersize,
int linebuffersize,
final HttpParams params) {
this(buffersize, linebuffersize, new HeapByteBufferAllocator(), params);
}
public int fill(final ReadableByteChannel channel) throws IOException {
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
setInputMode();
if (!this.buffer.hasRemaining()) {
expand();
}
int readNo = channel.read(this.buffer);
return readNo;
}
public int read() {
setOutputMode();
return this.buffer.get() & 0xff;
}
public int read(final ByteBuffer dst, int maxLen) {
if (dst == null) {
return 0;
}
setOutputMode();
int len = Math.min(dst.remaining(), maxLen);
int chunk = Math.min(this.buffer.remaining(), len);
for (int i = 0; i < chunk; i++) {
dst.put(this.buffer.get());
}
return chunk;
}
public int read(final ByteBuffer dst) {
if (dst == null) {
return 0;
}
return read(dst, dst.remaining());
}
public int read(final WritableByteChannel dst, int maxLen) throws IOException {
if (dst == null) {
return 0;
}
setOutputMode();
int bytesRead;
if (this.buffer.remaining() > maxLen) {
int oldLimit = this.buffer.limit();
int newLimit = oldLimit - (this.buffer.remaining() - maxLen);
this.buffer.limit(newLimit);
bytesRead = dst.write(this.buffer);
this.buffer.limit(oldLimit);
} else {
bytesRead = dst.write(this.buffer);
}
return bytesRead;
}
public int read(final WritableByteChannel dst) throws IOException {
if (dst == null) {
return 0;
}
setOutputMode();
return dst.write(this.buffer);
}
public boolean readLine(
final CharArrayBuffer linebuffer,
boolean endOfStream) throws CharacterCodingException {
setOutputMode();
// See if there is LF char present in the buffer
int pos = -1;
boolean hasLine = false;
for (int i = this.buffer.position(); i < this.buffer.limit(); i++) {
int b = this.buffer.get(i);
if (b == HTTP.LF) {
hasLine = true;
pos = i + 1;
break;
}
}
if (!hasLine) {
if (endOfStream && this.buffer.hasRemaining()) {
// No more data. Get the rest
pos = this.buffer.limit();
} else {
// Either no complete line present in the buffer
// or no more data is expected
return false;
}
}
int origLimit = this.buffer.limit();
this.buffer.limit(pos);
int len = this.buffer.limit() - this.buffer.position();
// Ensure capacity of len assuming ASCII as the most likely charset
linebuffer.ensureCapacity(len);
this.chardecoder.reset();
for (;;) {
CoderResult result = this.chardecoder.decode(
this.buffer,
this.charbuffer,
true);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
this.charbuffer.flip();
linebuffer.append(
this.charbuffer.array(),
this.charbuffer.position(),
this.charbuffer.remaining());
this.charbuffer.clear();
}
if (result.isUnderflow()) {
break;
}
}
this.buffer.limit(origLimit);
// flush the decoder
this.chardecoder.flush(this.charbuffer);
this.charbuffer.flip();
// append the decoded content to the line buffer
if (this.charbuffer.hasRemaining()) {
linebuffer.append(
this.charbuffer.array(),
this.charbuffer.position(),
this.charbuffer.remaining());
}
// discard LF if found
int l = linebuffer.length();
if (l > 0) {
if (linebuffer.charAt(l - 1) == HTTP.LF) {
l--;
linebuffer.setLength(l);
}
// discard CR if found
if (l > 0) {
if (linebuffer.charAt(l - 1) == HTTP.CR) {
l--;
linebuffer.setLength(l);
}
}
}
return true;
}
public String readLine(boolean endOfStream) throws CharacterCodingException {
CharArrayBuffer charbuffer = new CharArrayBuffer(64);
boolean found = readLine(charbuffer, endOfStream);
if (found) {
return charbuffer.toString();
} else {
return null;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionInputBufferImpl.java
|
Java
|
gpl3
| 8,059
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
Default implementations for interfaces in
{@link org.apache.http.nio org.apache.http.nio} including default
I/O reactor implementations and support for SSL/TLS transport security.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/package.html
|
HTML
|
gpl3
| 1,418
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.nio.channels.SelectionKey;
/**
* Helper class, representing an entry on an {@link java.nio.channels.SelectionKey#interestOps(int)
* interestOps(int)} queue.
*
* @since 4.1
*/
class InterestOpEntry {
private final SelectionKey key;
private final int eventMask;
public InterestOpEntry(final SelectionKey key, int eventMask) {
super();
if (key == null) {
throw new IllegalArgumentException("Selection key may not be null");
}
this.key = key;
this.eventMask = eventMask;
}
public SelectionKey getSelectionKey() {
return this.key;
}
public int getEventMask() {
return this.eventMask;
}
@Override
public boolean equals(Object obj) {
return this.key.equals(obj);
}
@Override
public int hashCode() {
return this.key.hashCode();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpEntry.java
|
Java
|
gpl3
| 2,117
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.SessionRequest;
/**
* Session request handle class used by I/O reactor implementations to keep
* a reference to a {@link SessionRequest} along with the time the request
* was made.
* @since 4.0
*/
public class SessionRequestHandle {
private final SessionRequestImpl sessionRequest;
private final long requestTime;
public SessionRequestHandle(final SessionRequestImpl sessionRequest) {
super();
if (sessionRequest == null) {
throw new IllegalArgumentException("Session request may not be null");
}
this.sessionRequest = sessionRequest;
this.requestTime = System.currentTimeMillis();
}
public SessionRequestImpl getSessionRequest() {
return this.sessionRequest;
}
public long getRequestTime() {
return this.requestTime;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequestHandle.java
|
Java
|
gpl3
| 2,096
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.HttpParams;
/**
* Default implementation of {@link ListeningIOReactor}. This class extends
* {@link AbstractMultiworkerIOReactor} with capability to listen for incoming
* connections.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultListeningIOReactor extends AbstractMultiworkerIOReactor
implements ListeningIOReactor {
private final Queue<ListenerEndpointImpl> requestQueue;
private final Set<ListenerEndpointImpl> endpoints;
private final Set<SocketAddress> pausedEndpoints;
private volatile boolean paused;
public DefaultListeningIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super(workerCount, threadFactory, params);
this.requestQueue = new ConcurrentLinkedQueue<ListenerEndpointImpl>();
this.endpoints = Collections.synchronizedSet(new HashSet<ListenerEndpointImpl>());
this.pausedEndpoints = new HashSet<SocketAddress>();
}
public DefaultListeningIOReactor(
int workerCount,
final HttpParams params) throws IOReactorException {
this(workerCount, null, params);
}
@Override
protected void cancelRequests() throws IOReactorException {
ListenerEndpointImpl request;
while ((request = this.requestQueue.poll()) != null) {
request.cancel();
}
}
@Override
protected void processEvents(int readyCount) throws IOReactorException {
if (!this.paused) {
processSessionRequests();
}
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
}
private void processEvent(final SelectionKey key)
throws IOReactorException {
try {
if (key.isAcceptable()) {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = null;
try {
socketChannel = serverChannel.accept();
} catch (IOException ex) {
if (this.exceptionHandler == null ||
!this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure accepting connection", ex);
}
}
if (socketChannel != null) {
try {
prepareSocket(socketChannel.socket());
} catch (IOException ex) {
if (this.exceptionHandler == null ||
!this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure initalizing socket", ex);
}
}
ChannelEntry entry = new ChannelEntry(socketChannel);
addChannel(entry);
}
}
} catch (CancelledKeyException ex) {
ListenerEndpoint endpoint = (ListenerEndpoint) key.attachment();
this.endpoints.remove(endpoint);
key.attach(null);
}
}
private ListenerEndpointImpl createEndpoint(final SocketAddress address) {
ListenerEndpointImpl endpoint = new ListenerEndpointImpl(
address,
new ListenerEndpointClosedCallback() {
public void endpointClosed(final ListenerEndpoint endpoint) {
endpoints.remove(endpoint);
}
});
return endpoint;
}
public ListenerEndpoint listen(final SocketAddress address) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
throw new IllegalStateException("I/O reactor has been shut down");
}
ListenerEndpointImpl request = createEndpoint(address);
this.requestQueue.add(request);
this.selector.wakeup();
return request;
}
private void processSessionRequests() throws IOReactorException {
ListenerEndpointImpl request;
while ((request = this.requestQueue.poll()) != null) {
SocketAddress address = request.getAddress();
ServerSocketChannel serverChannel;
try {
serverChannel = ServerSocketChannel.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening server socket", ex);
}
try {
serverChannel.configureBlocking(false);
serverChannel.socket().bind(address);
} catch (IOException ex) {
closeChannel(serverChannel);
request.failed(ex);
if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
throw new IOReactorException("Failure binding socket to address "
+ address, ex);
} else {
return;
}
}
try {
SelectionKey key = serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
key.attach(request);
request.setKey(key);
} catch (IOException ex) {
closeChannel(serverChannel);
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
this.endpoints.add(request);
request.completed(serverChannel.socket().getLocalSocketAddress());
}
}
public Set<ListenerEndpoint> getEndpoints() {
Set<ListenerEndpoint> set = new HashSet<ListenerEndpoint>();
synchronized (this.endpoints) {
Iterator<ListenerEndpointImpl> it = this.endpoints.iterator();
while (it.hasNext()) {
ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
set.add(endpoint);
} else {
it.remove();
}
}
}
return set;
}
public void pause() throws IOException {
if (this.paused) {
return;
}
this.paused = true;
synchronized (this.endpoints) {
Iterator<ListenerEndpointImpl> it = this.endpoints.iterator();
while (it.hasNext()) {
ListenerEndpoint endpoint = it.next();
if (!endpoint.isClosed()) {
endpoint.close();
this.pausedEndpoints.add(endpoint.getAddress());
}
}
this.endpoints.clear();
}
}
public void resume() throws IOException {
if (!this.paused) {
return;
}
this.paused = false;
for (SocketAddress address: this.pausedEndpoints) {
ListenerEndpointImpl request = createEndpoint(address);
this.requestQueue.add(request);
}
this.pausedEndpoints.clear();
this.selector.wakeup();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultListeningIOReactor.java
|
Java
|
gpl3
| 9,895
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
import org.apache.http.params.HttpParams;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectionKey;
/**
* A decorator class intended to transparently extend an {@link IOSession}
* with transport layer security capabilities based on the SSL/TLS protocol.
*
* @since 4.0
*/
public class SSLIOSession implements IOSession, SessionBufferStatus {
private final IOSession session;
private final SSLEngine sslEngine;
private final ByteBuffer inEncrypted;
private final ByteBuffer outEncrypted;
private final ByteBuffer inPlain;
private final ByteBuffer outPlain;
private final InternalByteChannel channel;
private final SSLSetupHandler handler;
private int appEventMask;
private SessionBufferStatus appBufferStatus;
private boolean endOfStream;
private volatile int status;
/**
* @since 4.1
*/
public SSLIOSession(
final IOSession session,
final SSLContext sslContext,
final SSLSetupHandler handler) {
super();
if (session == null) {
throw new IllegalArgumentException("IO session may not be null");
}
if (sslContext == null) {
throw new IllegalArgumentException("SSL context may not be null");
}
this.session = session;
this.appEventMask = session.getEventMask();
this.channel = new InternalByteChannel();
this.handler = handler;
// Override the status buffer interface
this.session.setBufferStatus(this);
SocketAddress address = session.getRemoteAddress();
if (address instanceof InetSocketAddress) {
String hostname = ((InetSocketAddress) address).getHostName();
int port = ((InetSocketAddress) address).getPort();
this.sslEngine = sslContext.createSSLEngine(hostname, port);
} else {
this.sslEngine = sslContext.createSSLEngine();
}
// Allocate buffers for network (encrypted) data
int netBuffersize = this.sslEngine.getSession().getPacketBufferSize();
this.inEncrypted = ByteBuffer.allocate(netBuffersize);
this.outEncrypted = ByteBuffer.allocate(netBuffersize);
// Allocate buffers for application (unencrypted) data
int appBuffersize = this.sslEngine.getSession().getApplicationBufferSize();
this.inPlain = ByteBuffer.allocate(appBuffersize);
this.outPlain = ByteBuffer.allocate(appBuffersize);
}
/**
* @deprecated
*/
@Deprecated
public SSLIOSession(
final IOSession session,
final SSLContext sslContext,
final SSLIOSessionHandler handler) {
this(session, sslContext, handler != null ? new SSLIOSessionHandlerAdaptor(handler) : null);
}
public synchronized void bind(
final SSLMode mode,
final HttpParams params) throws SSLException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
switch (mode) {
case CLIENT:
this.sslEngine.setUseClientMode(true);
break;
case SERVER:
this.sslEngine.setUseClientMode(false);
break;
}
if (this.handler != null) {
this.handler.initalize(this.sslEngine, params);
}
this.sslEngine.beginHandshake();
doHandshake();
}
private void doHandshake() throws SSLException {
boolean handshaking = true;
SSLEngineResult result = null;
while (handshaking) {
switch (this.sslEngine.getHandshakeStatus()) {
case NEED_WRAP:
// Generate outgoing handshake data
this.outPlain.flip();
result = this.sslEngine.wrap(this.outPlain, this.outEncrypted);
this.outPlain.compact();
if (result.getStatus() != Status.OK) {
handshaking = false;
}
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
break;
case NEED_UNWRAP:
// Process incoming handshake data
this.inEncrypted.flip();
result = this.sslEngine.unwrap(this.inEncrypted, this.inPlain);
this.inEncrypted.compact();
if (result.getStatus() != Status.OK) {
handshaking = false;
}
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
if (result.getStatus() == Status.BUFFER_UNDERFLOW && this.endOfStream) {
this.status = CLOSED;
}
break;
case NEED_TASK:
Runnable r = this.sslEngine.getDelegatedTask();
r.run();
break;
case NOT_HANDSHAKING:
handshaking = false;
break;
case FINISHED:
break;
}
}
// The SSLEngine has just finished handshaking. This value is only generated by a call
// to SSLEngine.wrap()/unwrap() when that call finishes a handshake.
// It is never generated by SSLEngine.getHandshakeStatus().
if (result != null && result.getHandshakeStatus() == HandshakeStatus.FINISHED) {
if (this.handler != null) {
this.handler.verify(this.session, this.sslEngine.getSession());
}
}
}
private void updateEventMask() {
if (this.sslEngine.isInboundDone() && this.sslEngine.isOutboundDone()) {
this.status = CLOSED;
}
if (this.status == CLOSED) {
this.session.close();
return;
}
// Need to toggle the event mask for this channel?
int oldMask = this.session.getEventMask();
int newMask = oldMask;
switch (this.sslEngine.getHandshakeStatus()) {
case NEED_WRAP:
newMask = EventMask.READ_WRITE;
break;
case NEED_UNWRAP:
newMask = EventMask.READ;
break;
case NOT_HANDSHAKING:
newMask = this.appEventMask;
break;
case NEED_TASK:
break;
case FINISHED:
break;
}
// Do we have encrypted data ready to be sent?
if (this.outEncrypted.position() > 0) {
newMask = newMask | EventMask.WRITE;
}
// Update the mask if necessary
if (oldMask != newMask) {
this.session.setEventMask(newMask);
}
}
private int sendEncryptedData() throws IOException {
this.outEncrypted.flip();
int bytesWritten = this.session.channel().write(this.outEncrypted);
this.outEncrypted.compact();
return bytesWritten;
}
private int receiveEncryptedData() throws IOException {
return this.session.channel().read(this.inEncrypted);
}
private boolean decryptData() throws SSLException {
boolean decrypted = false;
SSLEngineResult.Status opStatus = Status.OK;
while (this.inEncrypted.position() > 0 && opStatus == Status.OK) {
this.inEncrypted.flip();
SSLEngineResult result = this.sslEngine.unwrap(this.inEncrypted, this.inPlain);
this.inEncrypted.compact();
opStatus = result.getStatus();
if (opStatus == Status.CLOSED) {
this.status = CLOSED;
}
if (opStatus == Status.BUFFER_UNDERFLOW && this.endOfStream) {
this.status = CLOSED;
}
if (opStatus == Status.OK) {
decrypted = true;
}
}
return decrypted;
}
public synchronized boolean isAppInputReady() throws IOException {
int bytesRead = receiveEncryptedData();
if (bytesRead == -1) {
this.endOfStream = true;
}
doHandshake();
decryptData();
// Some decrypted data is available or at the end of stream
return (this.appEventMask & SelectionKey.OP_READ) > 0
&& (this.inPlain.position() > 0
|| (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput())
|| (this.endOfStream && this.status == ACTIVE));
}
/**
* @throws IOException - not thrown currently
*/
public synchronized boolean isAppOutputReady() throws IOException {
return (this.appEventMask & SelectionKey.OP_WRITE) > 0
&& this.status == ACTIVE
&& this.sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING;
}
/**
* @throws IOException - not thrown currently
*/
public synchronized void inboundTransport() throws IOException {
updateEventMask();
}
public synchronized void outboundTransport() throws IOException {
sendEncryptedData();
doHandshake();
updateEventMask();
}
private synchronized int writePlain(final ByteBuffer src) throws SSLException {
if (src == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.status != ACTIVE) {
return -1;
}
if (this.outPlain.position() > 0) {
this.outPlain.flip();
this.sslEngine.wrap(this.outPlain, this.outEncrypted);
this.outPlain.compact();
}
if (this.outPlain.position() == 0) {
SSLEngineResult result = this.sslEngine.wrap(src, this.outEncrypted);
if (result.getStatus() == Status.CLOSED) {
this.status = CLOSED;
}
return result.bytesConsumed();
} else {
return 0;
}
}
/**
* @throws SSLException - not thrown currently
*/
private synchronized int readPlain(final ByteBuffer dst) throws SSLException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.inPlain.position() > 0) {
this.inPlain.flip();
int n = Math.min(this.inPlain.remaining(), dst.remaining());
for (int i = 0; i < n; i++) {
dst.put(this.inPlain.get());
}
this.inPlain.compact();
return n;
} else {
if (this.endOfStream) {
return -1;
} else {
return 0;
}
}
}
public void close() {
if (this.status != ACTIVE) {
return;
}
this.status = CLOSING;
synchronized(this) {
this.sslEngine.closeOutbound();
updateEventMask();
}
}
public void shutdown() {
this.status = CLOSED;
this.session.shutdown();
}
public int getStatus() {
return this.status;
}
public boolean isClosed() {
return this.status != ACTIVE;
}
public synchronized boolean isInboundDone() {
return this.sslEngine.isInboundDone();
}
public synchronized boolean isOutboundDone() {
return this.sslEngine.isOutboundDone();
}
public ByteChannel channel() {
return this.channel;
}
public SocketAddress getLocalAddress() {
return this.session.getLocalAddress();
}
public SocketAddress getRemoteAddress() {
return this.session.getRemoteAddress();
}
public synchronized int getEventMask() {
return this.appEventMask;
}
public synchronized void setEventMask(int ops) {
this.appEventMask = ops;
updateEventMask();
}
public synchronized void setEvent(int op) {
this.appEventMask = this.appEventMask | op;
updateEventMask();
}
public synchronized void clearEvent(int op) {
this.appEventMask = this.appEventMask & ~op;
updateEventMask();
}
public int getSocketTimeout() {
return this.session.getSocketTimeout();
}
public void setSocketTimeout(int timeout) {
this.session.setSocketTimeout(timeout);
}
public synchronized boolean hasBufferedInput() {
return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedInput())
|| this.inEncrypted.position() > 0
|| this.inPlain.position() > 0;
}
public synchronized boolean hasBufferedOutput() {
return (this.appBufferStatus != null && this.appBufferStatus.hasBufferedOutput())
|| this.outEncrypted.position() > 0
|| this.outPlain.position() > 0;
}
public synchronized void setBufferStatus(final SessionBufferStatus status) {
this.appBufferStatus = status;
}
public Object getAttribute(final String name) {
return this.session.getAttribute(name);
}
public Object removeAttribute(final String name) {
return this.session.removeAttribute(name);
}
public void setAttribute(final String name, final Object obj) {
this.session.setAttribute(name, obj);
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(this.session);
buffer.append("[SSL handshake status: ");
buffer.append(this.sslEngine.getHandshakeStatus());
buffer.append("][");
buffer.append(this.inEncrypted.position());
buffer.append("][");
buffer.append(this.inPlain.position());
buffer.append("][");
buffer.append(this.outEncrypted.position());
buffer.append("][");
buffer.append(this.outPlain.position());
buffer.append("]");
return buffer.toString();
}
private class InternalByteChannel implements ByteChannel {
public int write(final ByteBuffer src) throws IOException {
return SSLIOSession.this.writePlain(src);
}
public int read(final ByteBuffer dst) throws IOException {
return SSLIOSession.this.readPlain(dst);
}
public void close() throws IOException {
SSLIOSession.this.close();
}
public boolean isOpen() {
return !SSLIOSession.this.isClosed();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SSLIOSession.java
|
Java
|
gpl3
| 16,133
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
/**
* Callback interface used internally by I/O session implementations to delegate execution
* of a {@link java.nio.channels.SelectionKey#interestOps(int)} operation to the I/O reactor.
*
* @since 4.1
*/
interface InterestOpsCallback {
void addInterestOps(InterestOpEntry entry);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/InterestOpsCallback.java
|
Java
|
gpl3
| 1,522
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import org.apache.http.nio.reactor.ListenerEndpoint;
/**
* Default implementation of {@link ListenerEndpoint}.
*
* @since 4.0
*/
public class ListenerEndpointImpl implements ListenerEndpoint {
private volatile boolean completed;
private volatile boolean closed;
private volatile SelectionKey key;
private volatile SocketAddress address;
private volatile IOException exception;
private final ListenerEndpointClosedCallback callback;
public ListenerEndpointImpl(
final SocketAddress address,
final ListenerEndpointClosedCallback callback) {
super();
if (address == null) {
throw new IllegalArgumentException("Address may not be null");
}
this.address = address;
this.callback = callback;
}
public SocketAddress getAddress() {
return this.address;
}
public boolean isCompleted() {
return this.completed;
}
public IOException getException() {
return this.exception;
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
public void completed(final SocketAddress address) {
if (address == null) {
throw new IllegalArgumentException("Address may not be null");
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.address = address;
notifyAll();
}
}
public void failed(final IOException exception) {
if (exception == null) {
return;
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.exception = exception;
notifyAll();
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
this.closed = true;
synchronized (this) {
notifyAll();
}
}
protected void setKey(final SelectionKey key) {
this.key = key;
}
public boolean isClosed() {
return this.closed || (this.key != null && !this.key.isValid());
}
public void close() {
if (this.closed) {
return;
}
this.completed = true;
this.closed = true;
if (this.key != null) {
this.key.cancel();
Channel channel = this.key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
if (this.callback != null) {
this.callback.endpointClosed(this);
}
synchronized (this) {
notifyAll();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpointImpl.java
|
Java
|
gpl3
| 4,328
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
/**
* Default implementation of {@link SessionRequest}.
*
* @since 4.0
*/
public class SessionRequestImpl implements SessionRequest {
private volatile boolean completed;
private volatile SelectionKey key;
private final SocketAddress remoteAddress;
private final SocketAddress localAddress;
private final Object attachment;
private final SessionRequestCallback callback;
private volatile int connectTimeout;
private volatile IOSession session = null;
private volatile IOException exception = null;
public SessionRequestImpl(
final SocketAddress remoteAddress,
final SocketAddress localAddress,
final Object attachment,
final SessionRequestCallback callback) {
super();
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
this.remoteAddress = remoteAddress;
this.localAddress = localAddress;
this.attachment = attachment;
this.callback = callback;
this.connectTimeout = 0;
}
public SocketAddress getRemoteAddress() {
return this.remoteAddress;
}
public SocketAddress getLocalAddress() {
return this.localAddress;
}
public Object getAttachment() {
return this.attachment;
}
public boolean isCompleted() {
return this.completed;
}
protected void setKey(final SelectionKey key) {
this.key = key;
}
public void waitFor() throws InterruptedException {
if (this.completed) {
return;
}
synchronized (this) {
while (!this.completed) {
wait();
}
}
}
public IOSession getSession() {
synchronized (this) {
return this.session;
}
}
public IOException getException() {
synchronized (this) {
return this.exception;
}
}
public void completed(final IOSession session) {
if (session == null) {
throw new IllegalArgumentException("Session may not be null");
}
if (this.completed) {
return;
}
this.completed = true;
synchronized (this) {
this.session = session;
if (this.callback != null) {
this.callback.completed(this);
}
notifyAll();
}
}
public void failed(final IOException exception) {
if (exception == null) {
return;
}
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
this.exception = exception;
if (this.callback != null) {
this.callback.failed(this);
}
notifyAll();
}
}
public void timeout() {
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
if (this.callback != null) {
this.callback.timeout(this);
}
}
}
public int getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(int timeout) {
if (this.connectTimeout != timeout) {
this.connectTimeout = timeout;
SelectionKey key = this.key;
if (key != null) {
key.selector().wakeup();
}
}
}
public void cancel() {
if (this.completed) {
return;
}
this.completed = true;
SelectionKey key = this.key;
if (key != null) {
key.cancel();
Channel channel = key.channel();
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException ignore) {}
}
}
synchronized (this) {
if (this.callback != null) {
this.callback.cancelled(this);
}
notifyAll();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionRequestImpl.java
|
Java
|
gpl3
| 6,216
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.nio.channels.SocketChannel;
/**
* {@link SocketChannel} entry maintained by the I/O reactor. If the channel
* represents an outgoing client connection, this entry also contains the
* original {@link SessionRequestImpl} used to request it.
*
* @since 4.0
*/
public class ChannelEntry {
private final SocketChannel channel;
private final SessionRequestImpl sessionRequest;
/**
* Creates new ChannelEntry.
*
* @param channel the channel
* @param sessionRequest original session request. Can be <code>null</code>
* if the channel represents an incoming server-side connection.
*/
public ChannelEntry(final SocketChannel channel, final SessionRequestImpl sessionRequest) {
super();
if (channel == null) {
throw new IllegalArgumentException("Socket channel may not be null");
}
this.channel = channel;
this.sessionRequest = sessionRequest;
}
/**
* Creates new ChannelEntry.
*
* @param channel the channel.
*/
public ChannelEntry(final SocketChannel channel) {
this(channel, null);
}
/**
* Returns the original session request, if available. If the channel
* entry represents an incoming server-side connection, returns
* <code>null</code>.
*
* @return the original session request, if client-side channel,
* <code>null</code> otherwise.
*/
public SessionRequestImpl getSessionRequest() {
return this.sessionRequest;
}
/**
* Returns the original session request attachment, if available.
*
* @return the original session request attachment, if available,
* <code>null</code> otherwise.
*/
public Object getAttachment() {
if (this.sessionRequest != null) {
return this.sessionRequest.getAttachment();
} else {
return null;
}
}
/**
* Returns the channel.
*
* @return the channel.
*/
public SocketChannel getChannel() {
return this.channel;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ChannelEntry.java
|
Java
|
gpl3
| 3,317
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.InterruptedIOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOSession;
/**
* Default implementation of {@link AbstractIOReactor} that serves as a base
* for more advanced {@link IOReactor} implementations. This class adds
* support for the I/O event dispatching using {@link IOEventDispatch},
* management of buffering sessions, and session timeout handling.
*
* @since 4.0
*/
public class BaseIOReactor extends AbstractIOReactor {
private final long timeoutCheckInterval;
private final Set<IOSession> bufferingSessions;
private long lastTimeoutCheck;
private IOReactorExceptionHandler exceptionHandler = null;
private IOEventDispatch eventDispatch = null;
/**
* Creates new BaseIOReactor instance.
*
* @param selectTimeout the select timeout.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public BaseIOReactor(long selectTimeout) throws IOReactorException {
this(selectTimeout, false);
}
/**
* Creates new BaseIOReactor instance.
*
* @param selectTimeout the select timeout.
* @param interestOpsQueueing Ops queueing flag.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*
* @since 4.1
*/
public BaseIOReactor(
long selectTimeout, boolean interestOpsQueueing) throws IOReactorException {
super(selectTimeout, interestOpsQueueing);
this.bufferingSessions = new HashSet<IOSession>();
this.timeoutCheckInterval = selectTimeout;
this.lastTimeoutCheck = System.currentTimeMillis();
}
/**
* Activates the I/O reactor. The I/O reactor will start reacting to I/O
* events and dispatch I/O event notifications to the given
* {@link IOEventDispatch}.
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
this.eventDispatch = eventDispatch;
execute();
}
/**
* Sets exception handler for this I/O reactor.
*
* @param exceptionHandler the exception handler.
*/
public void setExceptionHandler(IOReactorExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Handles the given {@link RuntimeException}. This method delegates
* handling of the exception to the {@link IOReactorExceptionHandler},
* if available.
*
* @param ex the runtime exception.
*/
protected void handleRuntimeException(final RuntimeException ex) {
if (this.exceptionHandler == null || !this.exceptionHandler.handle(ex)) {
throw ex;
}
}
/**
* This I/O reactor implementation does not react to the
* {@link SelectionKey#OP_ACCEPT} event.
* <p>
* Super-classes can override this method to react to the event.
*/
@Override
protected void acceptable(final SelectionKey key) {
}
/**
* This I/O reactor implementation does not react to the
* {@link SelectionKey#OP_CONNECT} event.
* <p>
* Super-classes can override this method to react to the event.
*/
@Override
protected void connectable(final SelectionKey key) {
}
/**
* Processes {@link SelectionKey#OP_READ} event on the given selection key.
* This method dispatches the event notification to the
* {@link IOEventDispatch#inputReady(IOSession)} method.
*/
@Override
protected void readable(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
handle.resetLastRead();
try {
this.eventDispatch.inputReady(session);
if (session.hasBufferedInput()) {
this.bufferingSessions.add(session);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
/**
* Processes {@link SelectionKey#OP_WRITE} event on the given selection key.
* This method dispatches the event notification to the
* {@link IOEventDispatch#outputReady(IOSession)} method.
*/
@Override
protected void writable(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
handle.resetLastWrite();
try {
this.eventDispatch.outputReady(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
/**
* Verifies whether any of the sessions associated with the given selection
* keys timed out by invoking the {@link #timeoutCheck(SelectionKey, long)}
* method.
* <p>
* This method will also invoke the
* {@link IOEventDispatch#inputReady(IOSession)} method on all sessions
* that have buffered input data.
*/
@Override
protected void validate(final Set<SelectionKey> keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
SelectionKey key = it.next();
timeoutCheck(key, currentTime);
}
}
}
if (!this.bufferingSessions.isEmpty()) {
for (Iterator<IOSession> it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = it.next();
if (!session.hasBufferedInput()) {
it.remove();
continue;
}
int ops = 0;
try {
ops = session.getEventMask();
} catch (CancelledKeyException ex) {
it.remove();
queueClosedSession(session);
continue;
}
if ((ops & EventMask.READ) > 0) {
try {
this.eventDispatch.inputReady(session);
} catch (CancelledKeyException ex) {
it.remove();
queueClosedSession(session);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
if (!session.hasBufferedInput()) {
it.remove();
}
}
}
}
}
/**
* Performs timeout check for the I/O session associated with the given
* selection key.
*/
@Override
protected void timeoutCheck(final SelectionKey key, long now) {
Object attachment = key.attachment();
if (attachment instanceof SessionHandle) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
int timeout = session.getSocketTimeout();
if (timeout > 0) {
if (handle.getLastAccessTime() + timeout < now) {
try {
this.eventDispatch.timeout(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
}
}
}
/**
* Processes newly created I/O session. This method dispatches the event
* notification to the {@link IOEventDispatch#connected(IOSession)} method.
*/
@Override
protected void sessionCreated(final SelectionKey key, final IOSession session) {
SessionHandle handle = new SessionHandle(session);
key.attach(handle);
try {
this.eventDispatch.connected(session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
@Override
protected IOSession getSession(final SelectionKey key) {
Object attachment = key.attachment();
if (attachment instanceof SessionHandle) {
SessionHandle handle = (SessionHandle) attachment;
return handle.getSession();
} else {
return null;
}
}
/**
* Processes closed I/O session. This method dispatches the event
* notification to the {@link IOEventDispatch#disconnected(IOSession)}
* method.
*/
@Override
protected void sessionClosed(final IOSession session) {
try {
this.eventDispatch.disconnected(session);
} catch (CancelledKeyException ex) {
// ignore
} catch (RuntimeException ex) {
handleRuntimeException(ex);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/BaseIOReactor.java
|
Java
|
gpl3
| 11,235
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
/**
* Callback interface that can be used to customize various aspects of
* the TLS/SSl protocol.
*
* @since 4.1
*/
public interface SSLSetupHandler {
/**
* Triggered when the SSL connection is being initialized. Custom handlers
* can use this callback to customize properties of the {@link SSLEngine}
* used to establish the SSL session.
*
* @param sslengine the SSL engine.
* @param params HTTP parameters.
* @throws SSLException if case of SSL protocol error.
*/
void initalize(SSLEngine sslengine, HttpParams params)
throws SSLException;
/**
* Triggered when the SSL connection has been established and initial SSL
* handshake has been successfully completed. Custom handlers can use
* this callback to verify properties of the {@link SSLSession}.
* For instance this would be the right place to enforce SSL cipher
* strength, validate certificate chain and do hostname checks.
*
* @param iosession the underlying IOSession for the SSL connection.
* @param sslsession newly created SSL session.
* @throws SSLException if case of SSL protocol error.
*/
void verify(IOSession iosession, SSLSession sslsession)
throws SSLException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SSLSetupHandler.java
|
Java
|
gpl3
| 2,683
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.IOSession;
/**
* Session callback interface used internally by I/O reactor implementations.
*
* @since 4.0
*/
public interface SessionClosedCallback {
void sessionClosed(IOSession session);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionClosedCallback.java
|
Java
|
gpl3
| 1,466
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionBufferStatus;
/**
* Default implementation of {@link IOSession}.
*
* @since 4.0
*/
public class IOSessionImpl implements IOSession {
private final SelectionKey key;
private final ByteChannel channel;
private final Map<String, Object> attributes;
private final InterestOpsCallback interestOpsCallback;
private final SessionClosedCallback sessionClosedCallback;
private volatile int status;
private volatile int currentEventMask;
private volatile SessionBufferStatus bufferStatus;
private volatile int socketTimeout;
/**
* Creates new instance of IOSessionImpl.
*
* @param key the selection key.
* @param interestOpsCallback interestOps callback.
* @param sessionClosedCallback session closed callback.
*
* @since 4.1
*/
public IOSessionImpl(
final SelectionKey key,
final InterestOpsCallback interestOpsCallback,
final SessionClosedCallback sessionClosedCallback) {
super();
if (key == null) {
throw new IllegalArgumentException("Selection key may not be null");
}
this.key = key;
this.channel = (ByteChannel) this.key.channel();
this.interestOpsCallback = interestOpsCallback;
this.sessionClosedCallback = sessionClosedCallback;
this.attributes = Collections.synchronizedMap(new HashMap<String, Object>());
this.currentEventMask = 0;
this.socketTimeout = 0;
this.status = ACTIVE;
}
/**
* Creates new instance of IOSessionImpl.
*
* @param key the selection key.
* @param sessionClosedCallback session closed callback.
*/
public IOSessionImpl(
final SelectionKey key,
final SessionClosedCallback sessionClosedCallback) {
this(key, null, sessionClosedCallback);
}
public ByteChannel channel() {
return this.channel;
}
public SocketAddress getLocalAddress() {
Channel channel = this.channel;
if (channel instanceof SocketChannel) {
return ((SocketChannel)channel).socket().getLocalSocketAddress();
} else {
return null;
}
}
public SocketAddress getRemoteAddress() {
Channel channel = this.channel;
if (channel instanceof SocketChannel) {
return ((SocketChannel)channel).socket().getRemoteSocketAddress();
} else {
return null;
}
}
public synchronized int getEventMask() {
return this.interestOpsCallback != null ? this.currentEventMask : this.key.interestOps();
}
public synchronized void setEventMask(int ops) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask = ops;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
this.key.interestOps(ops);
}
this.key.selector().wakeup();
}
public synchronized void setEvent(int op) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask |= op;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
int ops = this.key.interestOps();
this.key.interestOps(ops | op);
}
this.key.selector().wakeup();
}
public synchronized void clearEvent(int op) {
if (this.status == CLOSED) {
return;
}
if (this.interestOpsCallback != null) {
// update the current event mask
this.currentEventMask &= ~op;
// local variable
InterestOpEntry entry = new InterestOpEntry(this.key, this.currentEventMask);
// add this operation to the interestOps() queue
this.interestOpsCallback.addInterestOps(entry);
} else {
int ops = this.key.interestOps();
this.key.interestOps(ops & ~op);
}
this.key.selector().wakeup();
}
public int getSocketTimeout() {
return this.socketTimeout;
}
public void setSocketTimeout(int timeout) {
this.socketTimeout = timeout;
}
public synchronized void close() {
if (this.status == CLOSED) {
return;
}
this.status = CLOSED;
this.key.cancel();
try {
this.key.channel().close();
} catch (IOException ex) {
// Munching exceptions is not nice
// but in this case it is justified
}
if (this.sessionClosedCallback != null) {
this.sessionClosedCallback.sessionClosed(this);
}
if (this.key.selector().isOpen()) {
this.key.selector().wakeup();
}
}
public int getStatus() {
return this.status;
}
public boolean isClosed() {
return this.status == CLOSED;
}
public void shutdown() {
// For this type of session, a close() does exactly
// what we need and nothing more.
close();
}
public boolean hasBufferedInput() {
SessionBufferStatus bufferStatus = this.bufferStatus;
return bufferStatus != null && bufferStatus.hasBufferedInput();
}
public boolean hasBufferedOutput() {
SessionBufferStatus bufferStatus = this.bufferStatus;
return bufferStatus != null && bufferStatus.hasBufferedOutput();
}
public void setBufferStatus(final SessionBufferStatus bufferStatus) {
this.bufferStatus = bufferStatus;
}
public Object getAttribute(final String name) {
return this.attributes.get(name);
}
public Object removeAttribute(final String name) {
return this.attributes.remove(name);
}
public void setAttribute(final String name, final Object obj) {
this.attributes.put(name, obj);
}
private static void formatOps(final StringBuffer buffer, int ops) {
buffer.append('[');
if ((ops & SelectionKey.OP_READ) > 0) {
buffer.append('r');
}
if ((ops & SelectionKey.OP_WRITE) > 0) {
buffer.append('w');
}
if ((ops & SelectionKey.OP_ACCEPT) > 0) {
buffer.append('a');
}
if ((ops & SelectionKey.OP_CONNECT) > 0) {
buffer.append('c');
}
buffer.append(']');
}
@Override
public synchronized String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (this.key.isValid()) {
buffer.append("interest ops: ");
formatOps(buffer, this.interestOpsCallback != null ?
this.currentEventMask : this.key.interestOps());
buffer.append("; ready ops: ");
formatOps(buffer, this.key.readyOps());
} else {
buffer.append("invalid");
}
buffer.append("]");
return buffer.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/IOSessionImpl.java
|
Java
|
gpl3
| 9,091
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.ListenerEndpoint;
/**
* Listener endpoint callback interface used internally by I/O reactor
* implementations.
*
* @since 4.0
*/
public interface ListenerEndpointClosedCallback {
void endpointClosed(ListenerEndpoint endpoint);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/ListenerEndpointClosedCallback.java
|
Java
|
gpl3
| 1,504
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.params.HttpParams;
@Deprecated
class SSLIOSessionHandlerAdaptor implements SSLSetupHandler {
private final SSLIOSessionHandler handler;
public SSLIOSessionHandlerAdaptor(final SSLIOSessionHandler handler) {
super();
this.handler = handler;
}
public void initalize(final SSLEngine sslengine, final HttpParams params) throws SSLException {
this.handler.initalize(sslengine, params);
}
public void verify(final IOSession iosession, final SSLSession sslsession) throws SSLException {
this.handler.verify(iosession.getRemoteAddress(), sslsession);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SSLIOSessionHandlerAdaptor.java
|
Java
|
gpl3
| 2,011
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import org.apache.http.nio.reactor.IOSession;
/**
* Session handle class used by I/O reactor implementations to keep a reference
* to a {@link IOSession} along with information about time of last I/O
* operations on that session.
*
* @since 4.0
*/
public class SessionHandle {
private final IOSession session;
private final long startedTime;
private long lastReadTime;
private long lastWriteTime;
private long lastAccessTime;
public SessionHandle(final IOSession session) {
super();
if (session == null) {
throw new IllegalArgumentException("Session may not be null");
}
this.session = session;
long now = System.currentTimeMillis();
this.startedTime = now;
this.lastReadTime = now;
this.lastWriteTime = now;
this.lastAccessTime = now;
}
public IOSession getSession() {
return this.session;
}
public long getStartedTime() {
return this.startedTime;
}
public long getLastReadTime() {
return this.lastReadTime;
}
public long getLastWriteTime() {
return this.lastWriteTime;
}
public long getLastAccessTime() {
return this.lastAccessTime;
}
public void resetLastRead() {
long now = System.currentTimeMillis();
this.lastReadTime = now;
this.lastAccessTime = now;
}
public void resetLastWrite() {
long now = System.currentTimeMillis();
this.lastWriteTime = now;
this.lastAccessTime = now;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionHandle.java
|
Java
|
gpl3
| 2,789
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.params.NIOReactorParams;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
* Generic implementation of {@link IOReactor} that can run multiple
* {@link BaseIOReactor} instance in separate worker threads and distribute
* newly created I/O session equally across those I/O reactors for a more
* optimal resource utilization and a better I/O performance. Usually it is
* recommended to have one worker I/O reactor per physical CPU core.
* <p>
* <strong>Important note about exception handling</strong>
* <p>
* Protocol specific exceptions as well as those I/O exceptions thrown in the
* course of interaction with the session's channel are to be expected are to be
* dealt with by specific protocol handlers. These exceptions may result in
* termination of an individual session but should not affect the I/O reactor
* and all other active sessions. There are situations, however, when the I/O
* reactor itself encounters an internal problem such as an I/O exception in
* the underlying NIO classes or an unhandled runtime exception. Those types of
* exceptions are usually fatal and will cause the I/O reactor to shut down
* automatically.
* <p>
* There is a possibility to override this behavior and prevent I/O reactors
* from shutting down automatically in case of a runtime exception or an I/O
* exception in internal classes. This can be accomplished by providing a custom
* implementation of the {@link IOReactorExceptionHandler} interface.
* <p>
* If an I/O reactor is unable to automatically recover from an I/O or a runtime
* exception it will enter the shutdown mode. First off, it cancel all pending
* new session requests. Then it will attempt to close all active I/O sessions
* gracefully giving them some time to flush pending output data and terminate
* cleanly. Lastly, it will forcibly shut down those I/O sessions that still
* remain active after the grace period. This is a fairly complex process, where
* many things can fail at the same time and many different exceptions can be
* thrown in the course of the shutdown process. The I/O reactor will record all
* exceptions thrown during the shutdown process, including the original one
* that actually caused the shutdown in the first place, in an audit log. One
* can obtain the audit log using {@link #getAuditLog()}, examine exceptions
* thrown by the I/O reactor prior and in the course of the reactor shutdown
* and decide whether it is safe to restart the I/O reactor.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractMultiworkerIOReactor implements IOReactor {
protected volatile IOReactorStatus status;
protected final HttpParams params;
protected final Selector selector;
protected final long selectTimeout;
protected final boolean interestOpsQueueing;
private final int workerCount;
private final ThreadFactory threadFactory;
private final BaseIOReactor[] dispatchers;
private final Worker[] workers;
private final Thread[] threads;
private final Object statusLock;
protected IOReactorExceptionHandler exceptionHandler;
protected List<ExceptionEvent> auditLog;
private int currentWorker = 0;
/**
* Creates an instance of AbstractMultiworkerIOReactor.
*
* @param workerCount number of worker I/O reactors.
* @param threadFactory the factory to create threads.
* Can be <code>null</code>.
* @param params HTTP parameters.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public AbstractMultiworkerIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super();
if (workerCount <= 0) {
throw new IllegalArgumentException("Worker count may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
try {
this.selector = Selector.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening selector", ex);
}
this.params = params;
this.selectTimeout = NIOReactorParams.getSelectInterval(params);
this.interestOpsQueueing = NIOReactorParams.getInterestOpsQueueing(params);
this.statusLock = new Object();
this.workerCount = workerCount;
if (threadFactory != null) {
this.threadFactory = threadFactory;
} else {
this.threadFactory = new DefaultThreadFactory();
}
this.dispatchers = new BaseIOReactor[workerCount];
this.workers = new Worker[workerCount];
this.threads = new Thread[workerCount];
this.status = IOReactorStatus.INACTIVE;
}
public IOReactorStatus getStatus() {
return this.status;
}
/**
* Returns the audit log containing exceptions thrown by the I/O reactor
* prior and in the course of the reactor shutdown.
*
* @return audit log.
*/
public synchronized List<ExceptionEvent> getAuditLog() {
if (this.auditLog != null) {
return new ArrayList<ExceptionEvent>(this.auditLog);
} else {
return null;
}
}
/**
* Adds the given {@link Throwable} object with the given time stamp
* to the audit log.
*
* @param ex the exception thrown by the I/O reactor.
* @param timestamp the time stamp of the exception. Can be
* <code>null</code> in which case the current date / time will be used.
*/
protected synchronized void addExceptionEvent(final Throwable ex, Date timestamp) {
if (ex == null) {
return;
}
if (timestamp == null) {
timestamp = new Date();
}
if (this.auditLog == null) {
this.auditLog = new ArrayList<ExceptionEvent>();
}
this.auditLog.add(new ExceptionEvent(ex, timestamp));
}
/**
* Adds the given {@link Throwable} object to the audit log.
*
* @param ex the exception thrown by the I/O reactor.
*/
protected void addExceptionEvent(final Throwable ex) {
addExceptionEvent(ex, null);
}
/**
* Sets exception handler for this I/O reactor.
*
* @param exceptionHandler the exception handler.
*/
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Triggered to process I/O events registered by the main {@link Selector}.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param count event count.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected abstract void processEvents(int count) throws IOReactorException;
/**
* Triggered to cancel pending session requests.
* <p>
* Super-classes can implement this method to react to the event.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected abstract void cancelRequests() throws IOReactorException;
/**
* Activates the main I/O reactor as well as all worker I/O reactors.
* The I/O main reactor will start reacting to I/O events and triggering
* notification methods. The worker I/O reactor in their turn will start
* reacting to I/O events and dispatch I/O event notifications to the given
* {@link IOEventDispatch} interface.
* <p>
* This method will enter the infinite I/O select loop on
* the {@link Selector} instance associated with this I/O reactor and used
* to manage creation of new I/O channels. Once a new I/O channel has been
* created the processing of I/O events on that channel will be delegated
* to one of the worker I/O reactors.
* <p>
* The method will remain blocked unto the I/O reactor is shut down or the
* execution thread is interrupted.
*
* @see #processEvents(int)
* @see #cancelRequests()
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTDOWN_REQUEST) >= 0) {
this.status = IOReactorStatus.SHUT_DOWN;
this.statusLock.notifyAll();
return;
}
if (this.status.compareTo(IOReactorStatus.INACTIVE) != 0) {
throw new IllegalStateException("Illegal state: " + this.status);
}
this.status = IOReactorStatus.ACTIVE;
// Start I/O dispatchers
for (int i = 0; i < this.dispatchers.length; i++) {
BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout, this.interestOpsQueueing);
dispatcher.setExceptionHandler(exceptionHandler);
this.dispatchers[i] = dispatcher;
}
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
this.workers[i] = new Worker(dispatcher, eventDispatch);
this.threads[i] = this.threadFactory.newThread(this.workers[i]);
}
}
try {
for (int i = 0; i < this.workerCount; i++) {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.threads[i].start();
}
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) == 0) {
processEvents(readyCount);
}
// Verify I/O dispatchers
for (int i = 0; i < this.workerCount; i++) {
Worker worker = this.workers[i];
Exception ex = worker.getException();
if (ex != null) {
throw new IOReactorException(
"I/O dispatch worker terminated abnormally", ex);
}
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
break;
}
}
} catch (ClosedSelectorException ex) {
addExceptionEvent(ex);
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
throw ex;
} finally {
doShutdown();
synchronized (this.statusLock) {
this.status = IOReactorStatus.SHUT_DOWN;
this.statusLock.notifyAll();
}
}
}
/**
* Activates the shutdown sequence for this reactor. This method will cancel
* all pending session requests, close out all active I/O channels,
* make an attempt to terminate all worker I/O reactors gracefully,
* and finally force-terminate those I/O reactors that failed to
* terminate after the specified grace period.
*
* @throws InterruptedIOException if the shutdown sequence has been
* interrupted.
*/
protected void doShutdown() throws InterruptedIOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
}
/**
* Assigns the given channel entry to one of the worker I/O reactors.
*
* @param entry the channel entry.
*/
protected void addChannel(final ChannelEntry entry) {
// Distribute new channels among the workers
int i = Math.abs(this.currentWorker++ % this.workerCount);
this.dispatchers[i].addChannel(entry);
}
/**
* Registers the given channel with the main {@link Selector}.
*
* @param channel the channel.
* @param ops interest ops.
* @return selection key.
* @throws ClosedChannelException if the channel has been already closed.
*/
protected SelectionKey registerChannel(
final SelectableChannel channel, int ops) throws ClosedChannelException {
return channel.register(this.selector, ops);
}
/**
* Prepares the given {@link Socket} by resetting some of its properties.
*
* @param socket the socket
* @throws IOException in case of an I/O error.
*/
protected void prepareSocket(final Socket socket) throws IOException {
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(this.params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(this.params));
int linger = HttpConnectionParams.getLinger(this.params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
}
/**
* Blocks for the given period of time in milliseconds awaiting
* the completion of the reactor shutdown. If the value of
* <code>timeout</code> is set to <code>0</code> this method blocks
* indefinitely.
*
* @param timeout the maximum wait time.
* @throws InterruptedException if interrupted.
*/
protected void awaitShutdown(long timeout) throws InterruptedException {
synchronized (this.statusLock) {
long deadline = System.currentTimeMillis() + timeout;
long remaining = timeout;
while (this.status != IOReactorStatus.SHUT_DOWN) {
this.statusLock.wait(remaining);
if (timeout > 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
break;
}
}
}
}
}
public void shutdown() throws IOException {
shutdown(2000);
}
public void shutdown(long waitMs) throws IOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
return;
}
if (this.status.compareTo(IOReactorStatus.INACTIVE) == 0) {
this.status = IOReactorStatus.SHUT_DOWN;
cancelRequests();
return;
}
this.status = IOReactorStatus.SHUTDOWN_REQUEST;
}
this.selector.wakeup();
try {
awaitShutdown(waitMs);
} catch (InterruptedException ignore) {
}
}
static void closeChannel(final Channel channel) {
try {
channel.close();
} catch (IOException ignore) {
}
}
static class Worker implements Runnable {
final BaseIOReactor dispatcher;
final IOEventDispatch eventDispatch;
private volatile Exception exception;
public Worker(final BaseIOReactor dispatcher, final IOEventDispatch eventDispatch) {
super();
this.dispatcher = dispatcher;
this.eventDispatch = eventDispatch;
}
public void run() {
try {
this.dispatcher.execute(this.eventDispatch);
} catch (Exception ex) {
this.exception = ex;
}
}
public Exception getException() {
return this.exception;
}
}
static class DefaultThreadFactory implements ThreadFactory {
private static volatile int COUNT = 0;
public Thread newThread(final Runnable r) {
return new Thread(r, "I/O dispatcher " + (++COUNT));
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.java
|
Java
|
gpl3
| 21,432
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.net.SocketAddress;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import org.apache.http.params.HttpParams;
/**
* Callback interface that can be used to customize various aspects of
* the TLS/SSl protocol.
*
* @since 4.0
*
* @deprecated Use {@link SSLSetupHandler}
*/
@Deprecated
public interface SSLIOSessionHandler {
/**
* Triggered when the SSL connection is being initialized. Custom handlers
* can use this callback to customize properties of the {@link SSLEngine}
* used to establish the SSL session.
*
* @param sslengine the SSL engine.
* @param params HTTP parameters.
* @throws SSLException if case of SSL protocol error.
*/
void initalize(SSLEngine sslengine, HttpParams params)
throws SSLException;
/**
* Triggered when the SSL connection has been established and initial SSL
* handshake has been successfully completed. Custom handlers can use
* this callback to verify properties of the {@link SSLSession}.
* For instance this would be the right place to enforce SSL cipher
* strength, validate certificate chain and do hostname checks.
*
* @param remoteAddress the remote address of the connection.
* @param session newly created SSL session.
* @throws SSLException if case of SSL protocol error.
*/
void verify(SocketAddress remoteAddress, SSLSession session)
throws SSLException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SSLIOSessionHandler.java
|
Java
|
gpl3
| 2,726
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.IOSession;
/**
* Generic implementation of {@link IOReactor} that can used as a subclass
* for more specialized I/O reactors. It is based on a single {@link Selector}
* instance.
*
* @since 4.0
*/
public abstract class AbstractIOReactor implements IOReactor {
private volatile IOReactorStatus status;
private final Object statusMutex;
private final long selectTimeout;
private final boolean interestOpsQueueing;
private final Selector selector;
private final Set<IOSession> sessions;
private final Queue<InterestOpEntry> interestOpsQueue;
private final Queue<IOSession> closedSessions;
private final Queue<ChannelEntry> newChannels;
/**
* Creates new AbstractIOReactor instance.
*
* @param selectTimeout the select timeout.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
public AbstractIOReactor(long selectTimeout) throws IOReactorException {
this(selectTimeout, false);
}
/**
* Creates new AbstractIOReactor instance.
*
* @param selectTimeout the select timeout.
* @param interestOpsQueueing Ops queueing flag.
*
* @throws IOReactorException in case if a non-recoverable I/O error.
*
* @since 4.1
*/
public AbstractIOReactor(long selectTimeout, boolean interestOpsQueueing) throws IOReactorException {
super();
if (selectTimeout <= 0) {
throw new IllegalArgumentException("Select timeout may not be negative or zero");
}
this.selectTimeout = selectTimeout;
this.interestOpsQueueing = interestOpsQueueing;
this.sessions = Collections.synchronizedSet(new HashSet<IOSession>());
this.interestOpsQueue = new ConcurrentLinkedQueue<InterestOpEntry>();
this.closedSessions = new ConcurrentLinkedQueue<IOSession>();
this.newChannels = new ConcurrentLinkedQueue<ChannelEntry>();
try {
this.selector = Selector.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening selector", ex);
}
this.statusMutex = new Object();
this.status = IOReactorStatus.INACTIVE;
}
/**
* Triggered when the key signals {@link SelectionKey#OP_ACCEPT} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void acceptable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_CONNECT} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void connectable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_READ} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void readable(SelectionKey key);
/**
* Triggered when the key signals {@link SelectionKey#OP_WRITE} readiness.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
*/
protected abstract void writable(SelectionKey key);
/**
* Triggered to verify whether the I/O session associated with the
* given selection key has not timed out.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
* @param now current time as long value.
*/
protected abstract void timeoutCheck(SelectionKey key, long now);
/**
* Triggered to validate keys currently registered with the selector. This
* method is called after each I/O select loop.
* <p>
* Super-classes can implement this method to run validity checks on
* active sessions and include additional processing that needs to be
* executed after each I/O select loop.
*
* @param keys all selection keys registered with the selector.
*/
protected abstract void validate(Set<SelectionKey> keys);
/**
* Triggered when new session has been created.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param key the selection key.
* @param session new I/O session.
*/
protected abstract void sessionCreated(SelectionKey key, IOSession session);
/**
* Triggered when a session has been closed.
* <p>
* Super-classes can implement this method to react to the event.
*
* @param session closed I/O session.
*/
protected abstract void sessionClosed(IOSession session);
/**
* Obtains {@link IOSession} instance associated with the given selection
* key.
*
* @param key the selection key.
* @return I/O session.
*/
protected abstract IOSession getSession(SelectionKey key);
public IOReactorStatus getStatus() {
return this.status;
}
/**
* Returns <code>true</code> if interest Ops queueing is enabled, <code>false</code> otherwise.
*
* @since 4.1
*/
public boolean getInterestOpsQueueing() {
return this.interestOpsQueueing;
}
/**
* Adds new channel entry. The channel will be asynchronously registered
* with the selector.
*
* @param channelEntry the channel entry.
*/
public void addChannel(final ChannelEntry channelEntry) {
if (channelEntry == null) {
throw new IllegalArgumentException("Channel entry may not be null");
}
this.newChannels.add(channelEntry);
this.selector.wakeup();
}
/**
* Activates the I/O reactor. The I/O reactor will start reacting to
* I/O events and triggering notification methods.
* <p>
* This method will enter the infinite I/O select loop on
* the {@link Selector} instance associated with this I/O reactor.
* <p>
* The method will remain blocked unto the I/O reactor is shut down or the
* execution thread is interrupted.
*
* @see #acceptable(SelectionKey)
* @see #connectable(SelectionKey)
* @see #readable(SelectionKey)
* @see #writable(SelectionKey)
* @see #timeoutCheck(SelectionKey, long)
* @see #validate(Set)
* @see #sessionCreated(SelectionKey, IOSession)
* @see #sessionClosed(IOSession)
*
* @throws InterruptedIOException if the dispatch thread is interrupted.
* @throws IOReactorException in case if a non-recoverable I/O error.
*/
protected void execute() throws InterruptedIOException, IOReactorException {
this.status = IOReactorStatus.ACTIVE;
try {
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status == IOReactorStatus.SHUT_DOWN) {
// Hard shut down. Exit select loop immediately
break;
}
if (this.status == IOReactorStatus.SHUTTING_DOWN) {
// Graceful shutdown in process
// Try to close things out nicely
closeSessions();
closeNewChannels();
}
// Process selected I/O events
if (readyCount > 0) {
processEvents(this.selector.selectedKeys());
}
// Validate active channels
validate(this.selector.keys());
// Process closed sessions
processClosedSessions();
// If active process new channels
if (this.status == IOReactorStatus.ACTIVE) {
processNewChannels();
}
// Exit select loop if graceful shutdown has been completed
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0
&& this.sessions.isEmpty()) {
break;
}
if (this.interestOpsQueueing) {
// process all pending interestOps() operations
processPendingInterestOps();
}
}
} catch (ClosedSelectorException ex) {
} finally {
hardShutdown();
synchronized (this.statusMutex) {
this.statusMutex.notifyAll();
}
}
}
private void processEvents(final Set<SelectionKey> selectedKeys) {
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
/**
* Processes new event on the given selection key.
*
* @param key the selection key that triggered an event.
*/
protected void processEvent(final SelectionKey key) {
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
readable(key);
}
if (key.isWritable()) {
writable(key);
}
} catch (CancelledKeyException ex) {
IOSession session = getSession(key);
queueClosedSession(session);
key.attach(null);
}
}
/**
* Queues the given I/O session to be processed asynchronously as closed.
*
* @param session the closed I/O session.
*/
protected void queueClosedSession(final IOSession session) {
if (session != null) {
this.closedSessions.add(session);
}
}
private void processNewChannels() throws IOReactorException {
ChannelEntry entry;
while ((entry = this.newChannels.poll()) != null) {
SocketChannel channel;
SelectionKey key;
try {
channel = entry.getChannel();
channel.configureBlocking(false);
key = channel.register(this.selector, SelectionKey.OP_READ);
} catch (ClosedChannelException ex) {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.failed(ex);
}
return;
} catch (IOException ex) {
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
SessionClosedCallback sessionClosedCallback = new SessionClosedCallback() {
public void sessionClosed(IOSession session) {
queueClosedSession(session);
}
};
InterestOpsCallback interestOpsCallback = null;
if (this.interestOpsQueueing) {
interestOpsCallback = new InterestOpsCallback() {
public void addInterestOps(final InterestOpEntry entry) {
queueInterestOps(entry);
}
};
}
IOSession session = new IOSessionImpl(key, interestOpsCallback, sessionClosedCallback);
int timeout = 0;
try {
timeout = channel.socket().getSoTimeout();
} catch (IOException ex) {
// Very unlikely to happen and is not fatal
// as the protocol layer is expected to overwrite
// this value anyways
}
session.setAttribute(IOSession.ATTACHMENT_KEY, entry.getAttachment());
session.setSocketTimeout(timeout);
this.sessions.add(session);
try {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.completed(session);
}
sessionCreated(key, session);
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
}
}
private void processClosedSessions() {
IOSession session;
while ((session = this.closedSessions.poll()) != null) {
if (this.sessions.remove(session)) {
try {
sessionClosed(session);
} catch (CancelledKeyException ex) {
// ignore and move on
}
}
}
}
private void processPendingInterestOps() {
// validity check
if (!this.interestOpsQueueing) {
return;
}
InterestOpEntry entry;
while ((entry = this.interestOpsQueue.poll()) != null) {
// obtain the operation's details
SelectionKey key = entry.getSelectionKey();
int eventMask = entry.getEventMask();
if (key.isValid()) {
key.interestOps(eventMask);
}
}
}
private boolean queueInterestOps(final InterestOpEntry entry) {
// validity checks
if (!this.interestOpsQueueing) {
throw new IllegalStateException("Interest ops queueing not enabled");
}
if (entry == null) {
return false;
}
// add this operation to the interestOps() queue
this.interestOpsQueue.add(entry);
return true;
}
/**
* Closes out all I/O sessions maintained by this I/O reactor.
*/
protected void closeSessions() {
synchronized (this.sessions) {
for (Iterator<IOSession> it = this.sessions.iterator(); it.hasNext(); ) {
IOSession session = it.next();
session.close();
}
}
}
/**
* Closes out all new channels pending registration with the selector of
* this I/O reactor.
* @throws IOReactorException - not thrown currently
*/
protected void closeNewChannels() throws IOReactorException {
ChannelEntry entry;
while ((entry = this.newChannels.poll()) != null) {
SessionRequestImpl sessionRequest = entry.getSessionRequest();
if (sessionRequest != null) {
sessionRequest.cancel();
}
SocketChannel channel = entry.getChannel();
try {
channel.close();
} catch (IOException ignore) {
}
}
}
/**
* Closes out all active channels registered with the selector of
* this I/O reactor.
* @throws IOReactorException - not thrown currently
*/
protected void closeActiveChannels() throws IOReactorException {
try {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
IOSession session = getSession(key);
if (session != null) {
session.close();
}
}
this.selector.close();
} catch (IOException ignore) {
}
}
/**
* Attempts graceful shutdown of this I/O reactor.
*/
public void gracefulShutdown() {
synchronized (this.statusMutex) {
if (this.status != IOReactorStatus.ACTIVE) {
// Already shutting down
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
this.selector.wakeup();
}
/**
* Attempts force-shutdown of this I/O reactor.
*/
public void hardShutdown() throws IOReactorException {
synchronized (this.statusMutex) {
if (this.status == IOReactorStatus.SHUT_DOWN) {
// Already shut down
return;
}
this.status = IOReactorStatus.SHUT_DOWN;
}
closeNewChannels();
closeActiveChannels();
processClosedSessions();
}
/**
* Blocks for the given period of time in milliseconds awaiting
* the completion of the reactor shutdown.
*
* @param timeout the maximum wait time.
* @throws InterruptedException if interrupted.
*/
public void awaitShutdown(long timeout) throws InterruptedException {
synchronized (this.statusMutex) {
long deadline = System.currentTimeMillis() + timeout;
long remaining = timeout;
while (this.status != IOReactorStatus.SHUT_DOWN) {
this.statusMutex.wait(remaining);
if (timeout > 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
break;
}
}
}
}
}
public void shutdown(long gracePeriod) throws IOReactorException {
if (this.status != IOReactorStatus.INACTIVE) {
gracefulShutdown();
try {
awaitShutdown(gracePeriod);
} catch (InterruptedException ignore) {
}
}
if (this.status != IOReactorStatus.SHUT_DOWN) {
hardShutdown();
}
}
public void shutdown() throws IOReactorException {
shutdown(1000);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractIOReactor.java
|
Java
|
gpl3
| 19,703
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ExpandableBuffer;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
/**
* Default implementation of {@link SessionOutputBuffer} based on
* the {@link ExpandableBuffer} class.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
public class SessionOutputBufferImpl extends ExpandableBuffer implements SessionOutputBuffer {
private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF};
private CharBuffer charbuffer = null;
private Charset charset = null;
private CharsetEncoder charencoder = null;
public SessionOutputBufferImpl(
int buffersize,
int linebuffersize,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(buffersize, allocator);
this.charbuffer = CharBuffer.allocate(linebuffersize);
this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params));
this.charencoder = this.charset.newEncoder();
}
public SessionOutputBufferImpl(
int buffersize,
int linebuffersize,
final HttpParams params) {
this(buffersize, linebuffersize, new HeapByteBufferAllocator(), params);
}
public void reset(final HttpParams params) {
clear();
}
public int flush(final WritableByteChannel channel) throws IOException {
if (channel == null) {
throw new IllegalArgumentException("Channel may not be null");
}
setOutputMode();
int noWritten = channel.write(this.buffer);
return noWritten;
}
public void write(final ByteBuffer src) {
if (src == null) {
return;
}
setInputMode();
int requiredCapacity = this.buffer.position() + src.remaining();
ensureCapacity(requiredCapacity);
this.buffer.put(src);
}
public void write(final ReadableByteChannel src) throws IOException {
if (src == null) {
return;
}
setInputMode();
src.read(this.buffer);
}
private void write(final byte[] b) {
if (b == null) {
return;
}
setInputMode();
int off = 0;
int len = b.length;
int requiredCapacity = this.buffer.position() + len;
ensureCapacity(requiredCapacity);
this.buffer.put(b, off, len);
}
private void writeCRLF() {
write(CRLF);
}
public void writeLine(final CharArrayBuffer linebuffer) throws CharacterCodingException {
if (linebuffer == null) {
return;
}
// Do not bother if the buffer is empty
if (linebuffer.length() > 0 ) {
setInputMode();
this.charencoder.reset();
// transfer the string in small chunks
int remaining = linebuffer.length();
int offset = 0;
while (remaining > 0) {
int l = this.charbuffer.remaining();
boolean eol = false;
if (remaining <= l) {
l = remaining;
// terminate the encoding process
eol = true;
}
this.charbuffer.put(linebuffer.buffer(), offset, l);
this.charbuffer.flip();
boolean retry = true;
while (retry) {
CoderResult result = this.charencoder.encode(this.charbuffer, this.buffer, eol);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
expand();
}
retry = !result.isUnderflow();
}
this.charbuffer.compact();
offset += l;
remaining -= l;
}
// flush the encoder
boolean retry = true;
while (retry) {
CoderResult result = this.charencoder.flush(this.buffer);
if (result.isError()) {
result.throwException();
}
if (result.isOverflow()) {
expand();
}
retry = !result.isUnderflow();
}
}
writeCRLF();
}
public void writeLine(final String s) throws IOException {
if (s == null) {
return;
}
if (s.length() > 0) {
CharArrayBuffer tmp = new CharArrayBuffer(s.length());
tmp.append(s);
writeLine(tmp);
} else {
write(CRLF);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SessionOutputBufferImpl.java
|
Java
|
gpl3
| 6,677
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
/**
* @since 4.0
*/
public enum SSLMode {
CLIENT,
SERVER
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/SSLMode.java
|
Java
|
gpl3
| 1,299
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
/**
* Default implementation of {@link ConnectingIOReactor}. This class extends
* {@link AbstractMultiworkerIOReactor} with capability to connect to remote
* hosts.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#SELECT_INTERVAL}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#GRACE_PERIOD}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#INTEREST_OPS_QUEUEING}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultConnectingIOReactor extends AbstractMultiworkerIOReactor
implements ConnectingIOReactor {
private final Queue<SessionRequestImpl> requestQueue;
private long lastTimeoutCheck;
public DefaultConnectingIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super(workerCount, threadFactory, params);
this.requestQueue = new ConcurrentLinkedQueue<SessionRequestImpl>();
this.lastTimeoutCheck = System.currentTimeMillis();
}
public DefaultConnectingIOReactor(
int workerCount,
final HttpParams params) throws IOReactorException {
this(workerCount, null, params);
}
@Override
protected void cancelRequests() throws IOReactorException {
SessionRequestImpl request;
while ((request = this.requestQueue.poll()) != null) {
request.cancel();
}
}
@Override
protected void processEvents(int readyCount) throws IOReactorException {
processSessionRequests();
if (readyCount > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) {
SelectionKey key = it.next();
processEvent(key);
}
selectedKeys.clear();
}
long currentTime = System.currentTimeMillis();
if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) {
this.lastTimeoutCheck = currentTime;
Set<SelectionKey> keys = this.selector.keys();
processTimeouts(keys);
}
}
private void processEvent(final SelectionKey key) {
try {
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel();
// Get request handle
SessionRequestHandle requestHandle = (SessionRequestHandle) key.attachment();
SessionRequestImpl sessionRequest = requestHandle.getSessionRequest();
// Finish connection process
try {
channel.finishConnect();
} catch (IOException ex) {
sessionRequest.failed(ex);
}
key.cancel();
if (channel.isConnected()) {
try {
try {
prepareSocket(channel.socket());
} catch (IOException ex) {
if (this.exceptionHandler == null
|| !this.exceptionHandler.handle(ex)) {
throw new IOReactorException(
"Failure initalizing socket", ex);
}
}
ChannelEntry entry = new ChannelEntry(channel, sessionRequest);
addChannel(entry);
} catch (IOException ex) {
sessionRequest.failed(ex);
}
}
}
} catch (CancelledKeyException ex) {
key.attach(null);
}
}
private void processTimeouts(final Set<SelectionKey> keys) {
long now = System.currentTimeMillis();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
SelectionKey key = it.next();
Object attachment = key.attachment();
if (attachment instanceof SessionRequestHandle) {
SessionRequestHandle handle = (SessionRequestHandle) key.attachment();
SessionRequestImpl sessionRequest = handle.getSessionRequest();
int timeout = sessionRequest.getConnectTimeout();
if (timeout > 0) {
if (handle.getRequestTime() + timeout < now) {
sessionRequest.timeout();
}
}
}
}
}
public SessionRequest connect(
final SocketAddress remoteAddress,
final SocketAddress localAddress,
final Object attachment,
final SessionRequestCallback callback) {
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
throw new IllegalStateException("I/O reactor has been shut down");
}
SessionRequestImpl sessionRequest = new SessionRequestImpl(
remoteAddress, localAddress, attachment, callback);
sessionRequest.setConnectTimeout(HttpConnectionParams.getConnectionTimeout(this.params));
this.requestQueue.add(sessionRequest);
this.selector.wakeup();
return sessionRequest;
}
private void validateAddress(final SocketAddress address) throws UnknownHostException {
if (address == null) {
return;
}
if (address instanceof InetSocketAddress) {
InetSocketAddress endpoint = (InetSocketAddress) address;
if (endpoint.isUnresolved()) {
throw new UnknownHostException(endpoint.getHostName());
}
}
}
private void processSessionRequests() throws IOReactorException {
SessionRequestImpl request;
while ((request = this.requestQueue.poll()) != null) {
if (request.isCompleted()) {
continue;
}
SocketChannel socketChannel;
try {
socketChannel = SocketChannel.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening socket", ex);
}
try {
socketChannel.configureBlocking(false);
validateAddress(request.getLocalAddress());
validateAddress(request.getRemoteAddress());
if (request.getLocalAddress() != null) {
Socket sock = socketChannel.socket();
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(this.params));
sock.bind(request.getLocalAddress());
}
boolean connected = socketChannel.connect(request.getRemoteAddress());
if (connected) {
prepareSocket(socketChannel.socket());
ChannelEntry entry = new ChannelEntry(socketChannel, request);
addChannel(entry);
return;
}
} catch (IOException ex) {
closeChannel(socketChannel);
request.failed(ex);
return;
}
SessionRequestHandle requestHandle = new SessionRequestHandle(request);
try {
SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT,
requestHandle);
request.setKey(key);
} catch (IOException ex) {
closeChannel(socketChannel);
throw new IOReactorException("Failure registering channel " +
"with the selector", ex);
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/impl/nio/reactor/DefaultConnectingIOReactor.java
|
Java
|
gpl3
| 10,242
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
HTTP parameters for I/O reactors based on NIO model.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/params/package.html
|
HTML
|
gpl3
| 1,291
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpParams;
/**
* Utility class for accessing I/O reactor parameters in {@link HttpParams}.
*
* @since 4.0
*
* @see NIOReactorPNames
*/
public final class NIOReactorParams implements NIOReactorPNames {
private NIOReactorParams() {
super();
}
/**
* Obtains the value of {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
* If not set, defaults to <code>4096</code>.
*
* @param params HTTP parameters.
* @return content buffer size.
*/
public static int getContentBufferSize(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter(CONTENT_BUFFER_SIZE, 4096);
}
/**
* Sets value of the {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
*
* @param params HTTP parameters.
* @param size content buffer size.
*/
public static void setContentBufferSize(final HttpParams params, int size) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CONTENT_BUFFER_SIZE, size);
}
/**
* Obtains the value of {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
* If not set, defaults to <code>1000</code>.
*
* @param params HTTP parameters.
* @return I/O select interval in milliseconds.
*/
public static long getSelectInterval(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(SELECT_INTERVAL, 1000);
}
/**
* Sets value of the {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
*
* @param params HTTP parameters.
* @param ms I/O select interval in milliseconds.
*/
public static void setSelectInterval(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(SELECT_INTERVAL, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#GRACE_PERIOD} parameter.
* If not set, defaults to <code>500</code>.
*
* @param params HTTP parameters.
* @return shutdown grace period in milliseconds.
*/
public static long getGracePeriod(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(GRACE_PERIOD, 500);
}
/**
* Sets value of the {@link NIOReactorPNames#GRACE_PERIOD} parameter.
*
* @param params HTTP parameters.
* @param ms shutdown grace period in milliseconds.
*/
public static void setGracePeriod(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(GRACE_PERIOD, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
* If not set, defaults to <code>false</code>.
*
* @param params HTTP parameters.
* @return interest ops queuing flag.
*
* @since 4.1
*/
public static boolean getInterestOpsQueueing(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter(INTEREST_OPS_QUEUEING, false);
}
/**
* Sets value of the {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
*
* @param params HTTP parameters.
* @param interestOpsQueueing interest ops queuing.
*
* @since 4.1
*/
public static void setInterestOpsQueueing(
final HttpParams params, boolean interestOpsQueueing) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(INTEREST_OPS_QUEUEING, interestOpsQueueing);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/params/NIOReactorParams.java
|
Java
|
gpl3
| 5,462
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.params;
/**
* Parameter names for I/O reactors.
*
* @since 4.0
*/
public interface NIOReactorPNames {
/**
* Determines the size of the content input/output buffers used
* to buffer data while receiving or transmitting HTTP messages.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String CONTENT_BUFFER_SIZE = "http.nio.content-buffer-size";
/**
* Determines the time interval in milliseconds at which the
* I/O reactor wakes up to check for timed out sessions and session requests.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String SELECT_INTERVAL = "http.nio.select-interval";
/**
* Determines the grace period the I/O reactors are expected to block
* waiting for individual worker threads to terminate cleanly.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String GRACE_PERIOD = "http.nio.grace-period";
/**
* Determines whether interestOps() queueing is enabled for the I/O reactors.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*
* @since 4.1
*/
public static final String INTEREST_OPS_QUEUEING = "http.nio.interest-ops-queueing";
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/params/NIOReactorPNames.java
|
Java
|
gpl3
| 2,583
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams;
/**
* @since 4.0
*/
public class NIOReactorParamBean extends HttpAbstractParamBean {
public NIOReactorParamBean (final HttpParams params) {
super(params);
}
public void setContentBufferSize (int contentBufferSize) {
NIOReactorParams.setContentBufferSize(params, contentBufferSize);
}
public void setSelectInterval (long selectInterval) {
NIOReactorParams.setSelectInterval(params, selectInterval);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/params/NIOReactorParamBean.java
|
Java
|
gpl3
| 1,774
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
The core HTTP components based on non-blocking I/O model (HttpCore NIO).
<p/>
This layer defines interfaces for transferring HTTP messages over non-blocking
HTTP connections and protocol handlers for processing HTTP messages
asynchronously.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/package.html
|
HTML
|
gpl3
| 1,479
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
/**
* Connection input/output control interface. It can be used to control interest
* in I/O event notifications for non-blocking HTTP connections.
* <p>
* Implementations of this interface are expected to be threading safe.
* Therefore it can be used to request / suspend I/O event notifications from
* any thread of execution.
*
* @since 4.0
*/
public interface IOControl {
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for input operations.
*/
void requestInput();
/**
* Suspends event notifications about the underlying channel being
* ready for input operations.
*/
void suspendInput();
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for output operations.
*/
void requestOutput();
/**
* Suspends event notifications about the underlying channel being
* ready for output operations.
*/
void suspendOutput();
/**
* Shuts down the underlying channel.
*
* @throws IOException
*/
void shutdown() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/IOControl.java
|
Java
|
gpl3
| 2,385
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A {@link WritableByteChannel} that delegates to a {@link ContentEncoder}.
* Attempts to close this channel are ignored, and {@link #isOpen} always
* returns <code>true</code>.
*
* @since 4.0
*/
public class ContentEncoderChannel implements WritableByteChannel {
private final ContentEncoder contentEncoder;
public ContentEncoderChannel(ContentEncoder contentEncoder) {
this.contentEncoder = contentEncoder;
}
public int write(ByteBuffer src) throws IOException {
return contentEncoder.write(src);
}
public void close() {}
public boolean isOpen() {
return true;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/ContentEncoderChannel.java
|
Java
|
gpl3
| 2,001
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
/**
* A {@link ReadableByteChannel} that delegates to a {@link ContentDecoder}.
* Attempts to close this channel are ignored, and {@link #isOpen} always
* returns <code>true</code>.
*
* @since 4.0
*/
public class ContentDecoderChannel implements ReadableByteChannel {
private final ContentDecoder decoder;
public ContentDecoderChannel(ContentDecoder decoder) {
this.decoder = decoder;
}
public int read(ByteBuffer dst) throws IOException {
return decoder.read(dst);
}
public void close() {}
public boolean isOpen() {
return true;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/ContentDecoderChannel.java
|
Java
|
gpl3
| 1,920
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
Non-blocking HTTP protocol execution framework. This package contains protocol
handler implementations based on NIO model.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/package.html
|
HTML
|
gpl3
| 1,361
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.ProtocolException;
import org.apache.http.ProtocolVersion;
import org.apache.http.UnsupportedHttpVersionException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.nio.entity.NHttpEntityWrapper;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.entity.SkipContentListener;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.util.EncodingUtils;
/**
* Fully asynchronous HTTP server side protocol handler implementation that
* implements the essential requirements of the HTTP protocol for the server
* side message processing as described by RFC 2616. It is capable of processing
* HTTP requests with nearly constant memory footprint. Only HTTP message heads
* are stored in memory, while content of message bodies is streamed directly
* from the entity to the underlying channel (and vice versa)
* {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces.
* <p/>
* When using this class, it is important to ensure that entities supplied for
* writing implement {@link ProducingNHttpEntity}. Doing so will allow the
* entity to be written out asynchronously. If entities supplied for writing do
* not implement {@link ProducingNHttpEntity}, a delegate is added that buffers
* the entire contents in memory. Additionally, the buffering might take place
* in the I/O thread, which could cause I/O to block temporarily. For best
* results, ensure that all entities set on {@link HttpResponse}s from
* {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}.
* <p/>
* If incoming requests enclose a content entity, {@link NHttpRequestHandler}s
* are expected to return a {@link ConsumingNHttpEntity} for reading the
* content. After the entity is finished reading the data,
* {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)}
* is called to generate a response.
* <p/>
* Individual {@link NHttpRequestHandler}s do not have to submit a response
* immediately. They can defer transmission of the HTTP response back to the
* client without blocking the I/O thread and to delegate the processing the
* HTTP request to a worker thread. The worker thread in its turn can use an
* instance of {@link NHttpResponseTrigger} passed as a parameter to submit
* a response as at a later point of time once the response becomes available.
*
* @see ConsumingNHttpEntity
* @see ProducingNHttpEntity
*
* @since 4.0
*/
public class AsyncNHttpServiceHandler extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected NHttpRequestHandlerResolver handlerResolver;
protected HttpExpectationVerifier expectationVerifier;
public AsyncNHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
public AsyncNHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void connected(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = new ServerConnState();
context.setAttribute(CONN_STATE, connState);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
}
public void requestReceived(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpRequest request = conn.getHttpRequest();
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
connState.setRequest(request);
NHttpRequestHandler requestHandler = getRequestHandler(request);
connState.setRequestHandler(requestHandler);
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
HttpResponse response;
try {
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
if (entityRequest.expectContinue()) {
response = this.responseFactory.newHttpResponse(
ver, HttpStatus.SC_CONTINUE, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
}
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
conn.submitResponse(response);
} else {
conn.resetInput();
sendResponse(conn, request, response);
}
}
// Request content is expected.
ConsumingNHttpEntity consumingEntity = null;
// Lookup request handler for this request
if (requestHandler != null) {
consumingEntity = requestHandler.entityRequest(entityRequest, context);
}
if (consumingEntity == null) {
consumingEntity = new ConsumingNHttpEntityTemplate(
entityRequest.getEntity(),
new SkipContentListener(this.allocator));
}
entityRequest.setEntity(consumingEntity);
connState.setConsumingEntity(consumingEntity);
} else {
// No request content is expected.
// Process request right away
conn.suspendInput();
processRequest(conn, request);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void closed(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
connState.reset();
} catch (IOException ex) {
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
if (conn.isResponseSubmitted()) {
// There is not much that we can do if a response head
// has already been submitted
closeConnection(conn, httpex);
if (eventListener != null) {
eventListener.fatalProtocolException(httpex, conn);
}
return;
}
HttpContext context = conn.getContext();
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
response.setEntity(null);
sendResponse(conn, null, response);
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpRequest request = connState.getRequest();
ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity();
try {
consumingEntity.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
conn.suspendInput();
processRequest(conn, request);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
if (connState.isHandled()) {
return;
}
HttpRequest request = connState.getRequest();
try {
IOException ioex = connState.getIOException();
if (ioex != null) {
throw ioex;
}
HttpException httpex = connState.getHttpException();
if (httpex != null) {
HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
connState.setResponse(response);
}
HttpResponse response = connState.getResponse();
if (response != null) {
connState.setHandled(true);
sendResponse(conn, request, response);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpResponse response = conn.getHttpResponse();
try {
ProducingNHttpEntity entity = connState.getProducingEntity();
entity.produceContent(encoder, conn);
if (encoder.isCompleted()) {
connState.finishOutput();
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
} else {
// Ready to process new request
connState.reset();
conn.requestInput();
}
responseComplete(response, context);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
private void handleException(final HttpException ex, final HttpResponse response) {
int code = HttpStatus.SC_INTERNAL_SERVER_ERROR;
if (ex instanceof MethodNotSupportedException) {
code = HttpStatus.SC_NOT_IMPLEMENTED;
} else if (ex instanceof UnsupportedHttpVersionException) {
code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED;
} else if (ex instanceof ProtocolException) {
code = HttpStatus.SC_BAD_REQUEST;
}
response.setStatusCode(code);
byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
NByteArrayEntity entity = new NByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
/**
* @throws HttpException - not thrown currently
*/
private void processRequest(
final NHttpServerConnection conn,
final HttpRequest request) throws IOException, HttpException {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn);
try {
this.httpProcessor.process(request, context);
NHttpRequestHandler handler = connState.getRequestHandler();
if (handler != null) {
HttpResponse response = this.responseFactory.newHttpResponse(
ver, HttpStatus.SC_OK, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handler.handle(
request,
response,
trigger,
context);
} else {
HttpResponse response = this.responseFactory.newHttpResponse(ver,
HttpStatus.SC_NOT_IMPLEMENTED, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
trigger.submitResponse(response);
}
} catch (HttpException ex) {
trigger.handleException(ex);
}
}
private void sendResponse(
final NHttpServerConnection conn,
final HttpRequest request,
final HttpResponse response) throws IOException, HttpException {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
// Now that a response is ready, we can cleanup the listener for the request.
connState.finishInput();
// Some processers need the request that generated this response.
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(response, context);
context.setAttribute(ExecutionContext.HTTP_REQUEST, null);
if (response.getEntity() != null && !canResponseHaveBody(request, response)) {
response.setEntity(null);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (entity instanceof ProducingNHttpEntity) {
connState.setProducingEntity((ProducingNHttpEntity) entity);
} else {
connState.setProducingEntity(new NHttpEntityWrapper(entity));
}
}
conn.submitResponse(response);
if (entity == null) {
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
} else {
// Ready to process new request
connState.reset();
conn.requestInput();
}
responseComplete(response, context);
}
}
/**
* Signals that this response has been fully sent. This will be called after
* submitting the response to a connection, if there is no entity in the
* response. If there is an entity, it will be called after the entity has
* completed.
*/
protected void responseComplete(HttpResponse response, HttpContext context) {
}
private NHttpRequestHandler getRequestHandler(HttpRequest request) {
NHttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
return handler;
}
protected static class ServerConnState {
private volatile NHttpRequestHandler requestHandler;
private volatile HttpRequest request;
private volatile ConsumingNHttpEntity consumingEntity;
private volatile HttpResponse response;
private volatile ProducingNHttpEntity producingEntity;
private volatile IOException ioex;
private volatile HttpException httpex;
private volatile boolean handled;
public void finishInput() throws IOException {
if (this.consumingEntity != null) {
this.consumingEntity.finish();
this.consumingEntity = null;
}
}
public void finishOutput() throws IOException {
if (this.producingEntity != null) {
this.producingEntity.finish();
this.producingEntity = null;
}
}
public void reset() throws IOException {
finishInput();
this.request = null;
finishOutput();
this.handled = false;
this.response = null;
this.ioex = null;
this.httpex = null;
this.requestHandler = null;
}
public NHttpRequestHandler getRequestHandler() {
return this.requestHandler;
}
public void setRequestHandler(final NHttpRequestHandler requestHandler) {
this.requestHandler = requestHandler;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public ConsumingNHttpEntity getConsumingEntity() {
return this.consumingEntity;
}
public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) {
this.consumingEntity = consumingEntity;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public ProducingNHttpEntity getProducingEntity() {
return this.producingEntity;
}
public void setProducingEntity(final ProducingNHttpEntity producingEntity) {
this.producingEntity = producingEntity;
}
public IOException getIOException() {
return this.ioex;
}
@Deprecated
public IOException getIOExepction() {
return this.ioex;
}
public void setIOException(final IOException ex) {
this.ioex = ex;
}
@Deprecated
public void setIOExepction(final IOException ex) {
this.ioex = ex;
}
public HttpException getHttpException() {
return this.httpex;
}
@Deprecated
public HttpException getHttpExepction() {
return this.httpex;
}
public void setHttpException(final HttpException ex) {
this.httpex = ex;
}
@Deprecated
public void setHttpExepction(final HttpException ex) {
this.httpex = ex;
}
public boolean isHandled() {
return this.handled;
}
public void setHandled(boolean handled) {
this.handled = handled;
}
}
private static class ResponseTriggerImpl implements NHttpResponseTrigger {
private final ServerConnState connState;
private final IOControl iocontrol;
private volatile boolean triggered;
public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) {
super();
this.connState = connState;
this.iocontrol = iocontrol;
}
public void submitResponse(final HttpResponse response) {
if (response == null) {
throw new IllegalArgumentException("Response may not be null");
}
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setResponse(response);
this.iocontrol.requestOutput();
}
public void handleException(final HttpException ex) {
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setHttpException(ex);
this.iocontrol.requestOutput();
}
public void handleException(final IOException ex) {
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setIOException(ex);
this.iocontrol.requestOutput();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AsyncNHttpServiceHandler.java
|
Java
|
gpl3
| 26,212
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Executor;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.ProtocolVersion;
import org.apache.http.ProtocolException;
import org.apache.http.UnsupportedHttpVersionException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.ContentBufferEntity;
import org.apache.http.nio.entity.ContentOutputStream;
import org.apache.http.nio.params.NIOReactorPNames;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ContentInputBuffer;
import org.apache.http.nio.util.ContentOutputBuffer;
import org.apache.http.nio.util.DirectByteBufferAllocator;
import org.apache.http.nio.util.SharedInputBuffer;
import org.apache.http.nio.util.SharedOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
/**
* Service protocol handler implementation that provide compatibility with
* the blocking I/O by utilizing shared content buffers and a fairly small pool
* of worker threads. The throttling protocol handler allocates input / output
* buffers of a constant length upon initialization and controls the rate of
* I/O events in order to ensure those content buffers do not ever get
* overflown. This helps ensure nearly constant memory footprint for HTTP
* connections and avoid the out of memory condition while streaming content
* in and out. The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method will fire immediately when a message is received. The protocol handler
* delegate the task of processing requests and generating response content to
* an {@link Executor}, which is expected to perform those tasks using
* dedicated worker threads in order to avoid blocking the I/O thread.
* <p/>
* Usually throttling protocol handlers need only a modest number of worker
* threads, much fewer than the number of concurrent connections. If the length
* of the message is smaller or about the size of the shared content buffer
* worker thread will just store content in the buffer and terminate almost
* immediately without blocking. The I/O dispatch thread in its turn will take
* care of sending out the buffered content asynchronously. The worker thread
* will have to block only when processing large messages and the shared buffer
* fills up. It is generally advisable to allocate shared buffers of a size of
* an average content body for optimal performance.
*
* @see NIOReactorPNames#CONTENT_BUFFER_SIZE
*
*
* @since 4.0
*/
public class ThrottlingHttpServiceHandler extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected final Executor executor;
protected HttpRequestHandlerResolver handlerResolver;
protected HttpExpectationVerifier expectationVerifier;
public ThrottlingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final Executor executor,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
if (executor == null) {
throw new IllegalArgumentException("Executor may not be null");
}
this.responseFactory = responseFactory;
this.executor = executor;
}
public ThrottlingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final Executor executor,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new DirectByteBufferAllocator(), executor, params);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void connected(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
int bufsize = this.params.getIntParameter(
NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480);
ServerConnState connState = new ServerConnState(bufsize, conn, allocator);
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
}
public void closed(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
if (connState != null) {
synchronized (connState) {
connState.close();
connState.notifyAll();
}
}
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
if (conn.isResponseSubmitted()) {
if (eventListener != null) {
eventListener.fatalProtocolException(httpex, conn);
}
return;
}
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
response.setEntity(null);
this.httpProcessor.process(response, context);
synchronized (connState) {
connState.setResponse(response);
// Response is ready to be committed
conn.requestOutput();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
public void requestReceived(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
final HttpRequest request = conn.getHttpRequest();
final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
synchronized (connState) {
boolean contentExpected = false;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
contentExpected = true;
}
}
if (!contentExpected) {
conn.suspendInput();
}
this.executor.execute(new Runnable() {
public void run() {
try {
handleRequest(request, connState, conn);
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
});
connState.notifyAll();
}
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
ContentInputBuffer buffer = connState.getInbuffer();
buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
connState.setInputState(ServerConnState.REQUEST_BODY_DONE);
} else {
connState.setInputState(ServerConnState.REQUEST_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.isExpectationFailed()) {
// Server expection failed
// Well-behaved client will not be sending
// a request body
conn.resetInput();
connState.setExpectationFailed(false);
}
HttpResponse response = connState.getResponse();
if (connState.getOutputState() == ServerConnState.READY
&& response != null
&& !conn.isResponseSubmitted()) {
conn.submitResponse(response);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (statusCode >= 200 && entity == null) {
connState.setOutputState(ServerConnState.RESPONSE_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setOutputState(ServerConnState.RESPONSE_SENT);
}
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = connState.getResponse();
ContentOutputBuffer buffer = connState.getOutbuffer();
buffer.produceContent(encoder);
if (encoder.isCompleted()) {
connState.setOutputState(ServerConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setOutputState(ServerConnState.RESPONSE_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
private void handleException(final HttpException ex, final HttpResponse response) {
if (ex instanceof MethodNotSupportedException) {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
} else if (ex instanceof UnsupportedHttpVersionException) {
response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
} else if (ex instanceof ProtocolException) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
} else {
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
ByteArrayEntity entity = new ByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
private void handleRequest(
final HttpRequest request,
final ServerConnState connState,
final NHttpServerConnection conn) throws HttpException, IOException {
HttpContext context = conn.getContext();
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.READY) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setInputState(ServerConnState.REQUEST_RECEIVED);
connState.setRequest(request);
}
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
HttpResponse response = null;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request;
if (eeRequest.expectContinue()) {
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_CONTINUE,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
}
synchronized (connState) {
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
connState.setResponse(response);
conn.requestOutput();
// Block until 1xx response is sent to the client
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.RESPONSE_SENT) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.resetOutput();
response = null;
} else {
// Discard request entity
eeRequest.setEntity(null);
conn.suspendInput();
connState.setExpectationFailed(true);
}
}
}
// Create a wrapper entity instead of the original one
if (eeRequest.getEntity() != null) {
eeRequest.setEntity(new ContentBufferEntity(
eeRequest.getEntity(),
connState.getInbuffer()));
}
}
if (response == null) {
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_OK,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
try {
this.httpProcessor.process(request, context);
HttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
if (handler != null) {
handler.handle(request, response, context);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = eeRequest.getEntity();
EntityUtils.consume(entity);
}
// It should be safe to reset the input state at this point
connState.resetInput();
this.httpProcessor.process(response, context);
if (!canResponseHaveBody(request, response)) {
response.setEntity(null);
}
connState.setResponse(response);
// Response is ready to be committed
conn.requestOutput();
if (response.getEntity() != null) {
ContentOutputBuffer buffer = connState.getOutbuffer();
OutputStream outstream = new ContentOutputStream(buffer);
HttpEntity entity = response.getEntity();
entity.writeTo(outstream);
outstream.flush();
outstream.close();
}
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.RESPONSE_DONE) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.resetOutput();
conn.requestInput();
connState.notifyAll();
}
}
@Override
protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
super.shutdownConnection(conn, cause);
if (connState != null) {
connState.shutdown();
}
}
static class ServerConnState {
public static final int SHUTDOWN = -1;
public static final int READY = 0;
public static final int REQUEST_RECEIVED = 1;
public static final int REQUEST_BODY_STREAM = 2;
public static final int REQUEST_BODY_DONE = 4;
public static final int RESPONSE_SENT = 8;
public static final int RESPONSE_BODY_STREAM = 16;
public static final int RESPONSE_BODY_DONE = 32;
public static final int RESPONSE_DONE = 32;
private final SharedInputBuffer inbuffer;
private final SharedOutputBuffer outbuffer;
private volatile int inputState;
private volatile int outputState;
private volatile HttpRequest request;
private volatile HttpResponse response;
private volatile boolean expectationFailure;
public ServerConnState(
int bufsize,
final IOControl ioControl,
final ByteBufferAllocator allocator) {
super();
this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator);
this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator);
this.inputState = READY;
this.outputState = READY;
}
public ContentInputBuffer getInbuffer() {
return this.inbuffer;
}
public ContentOutputBuffer getOutbuffer() {
return this.outbuffer;
}
public int getInputState() {
return this.inputState;
}
public void setInputState(int inputState) {
this.inputState = inputState;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public boolean isExpectationFailed() {
return expectationFailure;
}
public void setExpectationFailed(boolean b) {
this.expectationFailure = b;
}
public void close() {
this.inbuffer.close();
this.outbuffer.close();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void shutdown() {
this.inbuffer.shutdown();
this.outbuffer.shutdown();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void resetInput() {
this.inbuffer.reset();
this.request = null;
this.inputState = READY;
}
public void resetOutput() {
this.outbuffer.reset();
this.response = null;
this.outputState = READY;
this.expectationFailure = false;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/ThrottlingHttpServiceHandler.java
|
Java
|
gpl3
| 26,936
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.util.Map;
import org.apache.http.protocol.UriPatternMatcher;
/**
* Maintains a map of HTTP request handlers keyed by a request URI pattern.
* <br>
* Patterns may have three formats:
* <ul>
* <li><code>*</code></li>
* <li><code>*<uri></code></li>
* <li><code><uri>*</code></li>
* </ul>
* <br>
* This class can be used to resolve an instance of
* {@link NHttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public class NHttpRequestHandlerRegistry implements NHttpRequestHandlerResolver {
private final UriPatternMatcher matcher;
public NHttpRequestHandlerRegistry() {
matcher = new UriPatternMatcher();
}
/**
* Registers the given {@link NHttpRequestHandler} as a handler for URIs
* matching the given pattern.
*
* @param pattern the pattern to register the handler for.
* @param handler the handler.
*/
public void register(final String pattern, final NHttpRequestHandler handler) {
matcher.register(pattern, handler);
}
/**
* Removes registered handler, if exists, for the given pattern.
*
* @param pattern the pattern to unregister the handler for.
*/
public void unregister(final String pattern) {
matcher.unregister(pattern);
}
/**
* Sets handlers from the given map.
* @param map the map containing handlers keyed by their URI patterns.
*/
public void setHandlers(final Map<String, ? extends NHttpRequestHandler> map) {
matcher.setObjects(map);
}
public NHttpRequestHandler lookup(String requestURI) {
return (NHttpRequestHandler) matcher.lookup(requestURI);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpRequestHandlerRegistry.java
|
Java
|
gpl3
| 3,038
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpConnection;
/**
* Event listener used by the HTTP protocol layer to report fatal exceptions
* and events that may need to be logged using a logging toolkit.
*
* @since 4.0
*/
public interface EventListener {
/**
* Triggered when an I/O error caused a connection to be terminated.
*
* @param ex the I/O exception.
* @param conn the connection.
*/
void fatalIOException(IOException ex, NHttpConnection conn);
/**
* Triggered when an HTTP protocol error caused a connection to be
* terminated.
*
* @param ex the protocol exception.
* @param conn the connection.
*/
void fatalProtocolException(HttpException ex, NHttpConnection conn);
/**
* Triggered when a new connection has been established.
*
* @param conn the connection.
*/
void connectionOpen(NHttpConnection conn);
/**
* Triggered when a connection has been terminated.
*
* @param conn the connection.
*/
void connectionClosed(NHttpConnection conn);
/**
* Triggered when a connection has timed out.
*
* @param conn the connection.
*/
void connectionTimeout(NHttpConnection conn);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/EventListener.java
|
Java
|
gpl3
| 2,526
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
/**
* Service protocol handler implementations that provide compatibility with
* the blocking I/O by storing the full content of HTTP messages in memory.
* The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method will fire only when the entire message content has been read into
* an in-memory buffer. Please note that request processing take place the
* main I/O thread and therefore individual HTTP request handlers should not
* block indefinitely.
* <p>
* When using this protocol handler {@link HttpEntity}'s content can be
* generated / consumed using standard {@link InputStream}/{@link OutputStream}
* classes.
* <p>
* IMPORTANT: This protocol handler should be used only when dealing with HTTP
* messages that are known to be limited in length.
*
*
* @since 4.0
*/
public class BufferingHttpServiceHandler implements NHttpServiceHandler {
private final AsyncNHttpServiceHandler asyncHandler;
private HttpRequestHandlerResolver handlerResolver;
public BufferingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
this.asyncHandler = new AsyncNHttpServiceHandler(
httpProcessor,
responseFactory,
connStrategy,
allocator,
params);
this.asyncHandler.setHandlerResolver(new RequestHandlerResolverAdaptor());
}
public BufferingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setEventListener(final EventListener eventListener) {
this.asyncHandler.setEventListener(eventListener);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.asyncHandler.setExpectationVerifier(expectationVerifier);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void connected(final NHttpServerConnection conn) {
this.asyncHandler.connected(conn);
}
public void closed(final NHttpServerConnection conn) {
this.asyncHandler.closed(conn);
}
public void requestReceived(final NHttpServerConnection conn) {
this.asyncHandler.requestReceived(conn);
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
this.asyncHandler.inputReady(conn, decoder);
}
public void responseReady(final NHttpServerConnection conn) {
this.asyncHandler.responseReady(conn);
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
this.asyncHandler.outputReady(conn, encoder);
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
this.asyncHandler.exception(conn, httpex);
}
public void exception(final NHttpServerConnection conn, final IOException ioex) {
this.asyncHandler.exception(conn, ioex);
}
public void timeout(NHttpServerConnection conn) {
this.asyncHandler.timeout(conn);
}
class RequestHandlerResolverAdaptor implements NHttpRequestHandlerResolver {
public NHttpRequestHandler lookup(final String requestURI) {
HttpRequestHandler handler = handlerResolver.lookup(requestURI);
if (handler != null) {
return new RequestHandlerAdaptor(handler);
} else {
return null;
}
}
}
static class RequestHandlerAdaptor extends SimpleNHttpRequestHandler {
private final HttpRequestHandler requestHandler;
public RequestHandlerAdaptor(final HttpRequestHandler requestHandler) {
super();
this.requestHandler = requestHandler;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) throws HttpException, IOException {
return new BufferingNHttpEntity(
request.getEntity(),
new HeapByteBufferAllocator());
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
this.requestHandler.handle(request, response, context);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BufferingHttpServiceHandler.java
|
Java
|
gpl3
| 7,224
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
/**
* Callback interface to submit HTTP responses asynchronously.
* <p/>
* The {@link NHttpRequestHandler#handle(org.apache.http.HttpRequest, HttpResponse, NHttpResponseTrigger, org.apache.http.protocol.HttpContext)}
* method does not have to submit a response immediately. It can defer
* transmission of the HTTP response back to the client without blocking the
* I/O thread by delegating the process of handling the HTTP request to a worker
* thread. The worker thread in its turn can use the instance of
* {@link NHttpResponseTrigger} passed as a parameter to submit a response as at
* a later point of time once the response becomes available.
*
* @since 4.0
*/
public interface NHttpResponseTrigger {
/**
* Submits a response to be sent back to the client as a result of
* processing of the request.
*/
void submitResponse(HttpResponse response);
/**
* Reports a protocol exception thrown while processing the request.
*/
void handleException(HttpException ex);
/**
* Report an IOException thrown while processing the request.
*/
void handleException(IOException ex);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpResponseTrigger.java
|
Java
|
gpl3
| 2,479
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpProcessor;
/**
* @since 4.0
*/
public abstract class NHttpHandlerBase {
protected static final String CONN_STATE = "http.nio.conn-state";
protected final HttpProcessor httpProcessor;
protected final ConnectionReuseStrategy connStrategy;
protected final ByteBufferAllocator allocator;
protected final HttpParams params;
protected EventListener eventListener;
public NHttpHandlerBase(
final HttpProcessor httpProcessor,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
if (httpProcessor == null) {
throw new IllegalArgumentException("HTTP processor may not be null.");
}
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.allocator = allocator;
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setEventListener(final EventListener eventListener) {
this.eventListener = eventListener;
}
protected void closeConnection(final NHttpConnection conn, final Throwable cause) {
try {
// Try to close it nicely
conn.close();
} catch (IOException ex) {
try {
// Just shut the damn thing down
conn.shutdown();
} catch (IOException ignore) {
}
}
}
protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
protected void handleTimeout(final NHttpConnection conn) {
try {
if (conn.getStatus() == NHttpConnection.ACTIVE) {
conn.close();
if (conn.getStatus() == NHttpConnection.CLOSING) {
// Give the connection some grace time to
// close itself nicely
conn.setSocketTimeout(250);
}
if (this.eventListener != null) {
this.eventListener.connectionTimeout(conn);
}
} else {
conn.shutdown();
}
} catch (IOException ignore) {
}
}
protected boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpHandlerBase.java
|
Java
|
gpl3
| 4,829
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpResponseFactory;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandlerResolver;
/**
* @deprecated No longer used.
*
* @since 4.0
*/
@Deprecated
public abstract class NHttpServiceHandlerBase extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected HttpExpectationVerifier expectationVerifier;
protected HttpRequestHandlerResolver handlerResolver;
public NHttpServiceHandlerBase(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
public NHttpServiceHandlerBase(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpServiceHandlerBase.java
|
Java
|
gpl3
| 3,679
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Client protocol handler implementation that provides compatibility with the
* blocking I/O by storing the full content of HTTP messages in memory.
* The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method will fire only when the entire message content has been read into a
* in-memory buffer. Please note that request execution / response processing
* take place the main I/O thread and therefore
* {@link HttpRequestExecutionHandler} methods should not block indefinitely.
* <p>
* When using this protocol handler {@link HttpEntity}'s content can be
* generated / consumed using standard {@link InputStream}/{@link OutputStream}
* classes.
* <p>
* IMPORTANT: This protocol handler should be used only when dealing with HTTP
* messages that are known to be limited in length.
*
*
* @since 4.0
*/
public class BufferingHttpClientHandler implements NHttpClientHandler {
private final AsyncNHttpClientHandler asyncHandler;
public BufferingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
this.asyncHandler = new AsyncNHttpClientHandler(
httpProcessor,
new ExecutionHandlerAdaptor(execHandler),
connStrategy,
allocator,
params);
}
public BufferingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setEventListener(final EventListener eventListener) {
this.asyncHandler.setEventListener(eventListener);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
this.asyncHandler.connected(conn, attachment);
}
public void closed(final NHttpClientConnection conn) {
this.asyncHandler.closed(conn);
}
public void requestReady(final NHttpClientConnection conn) {
this.asyncHandler.requestReady(conn);
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
this.asyncHandler.inputReady(conn, decoder);
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
this.asyncHandler.outputReady(conn, encoder);
}
public void responseReceived(final NHttpClientConnection conn) {
this.asyncHandler.responseReceived(conn);
}
public void exception(final NHttpClientConnection conn, final HttpException httpex) {
this.asyncHandler.exception(conn, httpex);
}
public void exception(final NHttpClientConnection conn, final IOException ioex) {
this.asyncHandler.exception(conn, ioex);
}
public void timeout(final NHttpClientConnection conn) {
this.asyncHandler.timeout(conn);
}
static class ExecutionHandlerAdaptor implements NHttpRequestExecutionHandler {
private final HttpRequestExecutionHandler execHandler;
public ExecutionHandlerAdaptor(final HttpRequestExecutionHandler execHandler) {
super();
this.execHandler = execHandler;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
this.execHandler.initalizeContext(context, attachment);
}
public void finalizeContext(final HttpContext context) {
this.execHandler.finalizeContext(context);
}
public HttpRequest submitRequest(final HttpContext context) {
return this.execHandler.submitRequest(context);
}
public ConsumingNHttpEntity responseEntity(
final HttpResponse response,
final HttpContext context) throws IOException {
return new BufferingNHttpEntity(
response.getEntity(),
new HeapByteBufferAllocator());
}
public void handleResponse(
final HttpResponse response,
final HttpContext context) throws IOException {
this.execHandler.handleResponse(response, context);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/BufferingHttpClientHandler.java
|
Java
|
gpl3
| 6,545
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* A simple implementation of {@link NHttpRequestHandler} that abstracts away
* the need to use {@link NHttpResponseTrigger}. Implementations need only to
* implement {@link #handle(HttpRequest, HttpResponse, HttpContext)}.
*
* @since 4.0
*/
public abstract class SimpleNHttpRequestHandler implements NHttpRequestHandler {
public final void handle(
final HttpRequest request,
final HttpResponse response,
final NHttpResponseTrigger trigger,
final HttpContext context) throws HttpException, IOException {
handle(request, response, context);
trigger.submitResponse(response);
}
public abstract void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/SimpleNHttpRequestHandler.java
|
Java
|
gpl3
| 2,212
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.protocol.HttpContext;
/**
* NHttpRequestHandler represents a routine for asynchronous processing of
* a specific group of non-blocking HTTP requests. Protocol handlers are
* designed to take care of protocol specific aspects, whereas individual
* request handlers are expected to take care of application specific HTTP
* processing. The main purpose of a request handler is to generate a response
* object with a content entity to be sent back to the client in response to
* the given request
*
* @since 4.0
*/
public interface NHttpRequestHandler {
/**
* Triggered when a request is received with an entity. This method should
* return a {@link ConsumingNHttpEntity} that will be used to consume the
* entity. <code>null</code> is a valid response value, and will indicate
* that the entity should be silently ignored.
* <p>
* After the entity is fully consumed,
* {@link #handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)}
* is called to notify a full request & entity are ready to be processed.
*
* @param request the entity enclosing request.
* @param context the execution context.
* @return non-blocking HTTP entity.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
ConsumingNHttpEntity entityRequest(HttpEntityEnclosingRequest request,
HttpContext context)
throws HttpException, IOException;
/**
* Initiates processing of the request. This method does not have to submit
* a response immediately. It can defer transmission of the HTTP response
* back to the client without blocking the I/O thread by delegating the
* process of handling the HTTP request to a worker thread. The worker
* thread in its turn can use the instance of {@link NHttpResponseTrigger}
* passed as a parameter to submit a response as at a later point of time
* once content of the response becomes available.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param trigger the response trigger.
* @param context the HTTP execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
void handle(HttpRequest request, HttpResponse response,
NHttpResponseTrigger trigger, HttpContext context)
throws HttpException, IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpRequestHandler.java
|
Java
|
gpl3
| 4,061
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Executor;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.ContentBufferEntity;
import org.apache.http.nio.entity.ContentOutputStream;
import org.apache.http.nio.params.NIOReactorPNames;
import org.apache.http.nio.protocol.ThrottlingHttpServiceHandler.ServerConnState;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ContentInputBuffer;
import org.apache.http.nio.util.ContentOutputBuffer;
import org.apache.http.nio.util.DirectByteBufferAllocator;
import org.apache.http.nio.util.SharedInputBuffer;
import org.apache.http.nio.util.SharedOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Client protocol handler implementation that provide compatibility with
* the blocking I/O by utilizing shared content buffers and a fairly small pool
* of worker threads. The throttling protocol handler allocates input / output
* buffers of a constant length upon initialization and controls the rate of
* I/O events in order to ensure those content buffers do not ever get
* overflown. This helps ensure nearly constant memory footprint for HTTP
* connections and avoid the out of memory condition while streaming content
* in and out. The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method will fire immediately when a message is received. The protocol handler
* delegate the task of processing requests and generating response content to
* an {@link Executor}, which is expected to perform those tasks using
* dedicated worker threads in order to avoid blocking the I/O thread.
* <p/>
* Usually throttling protocol handlers need only a modest number of worker
* threads, much fewer than the number of concurrent connections. If the length
* of the message is smaller or about the size of the shared content buffer
* worker thread will just store content in the buffer and terminate almost
* immediately without blocking. The I/O dispatch thread in its turn will take
* care of sending out the buffered content asynchronously. The worker thread
* will have to block only when processing large messages and the shared buffer
* fills up. It is generally advisable to allocate shared buffers of a size of
* an average content body for optimal performance.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#CONTENT_BUFFER_SIZE}</li>
* </ul>
*
* @since 4.0
*/
public class ThrottlingHttpClientHandler extends NHttpHandlerBase
implements NHttpClientHandler {
protected HttpRequestExecutionHandler execHandler;
protected final Executor executor;
public ThrottlingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final Executor executor,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
if (executor == null) {
throw new IllegalArgumentException("Executor may not be null");
}
this.execHandler = execHandler;
this.executor = executor;
}
public ThrottlingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final Executor executor,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new DirectByteBufferAllocator(), executor, params);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
HttpContext context = conn.getContext();
initialize(conn, attachment);
int bufsize = this.params.getIntParameter(
NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480);
ClientConnState connState = new ClientConnState(bufsize, conn, this.allocator);
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
requestReady(conn);
}
public void closed(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
if (connState != null) {
synchronized (connState) {
connState.close();
connState.notifyAll();
}
}
this.execHandler.finalizeContext(context);
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void requestReady(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() != ClientConnState.READY) {
return;
}
HttpRequest request = this.execHandler.submitRequest(context);
if (request == null) {
return;
}
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(request, context);
connState.setRequest(request);
conn.submitRequest(request);
connState.setOutputState(ClientConnState.REQUEST_SENT);
conn.requestInput();
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
int timeout = conn.getSocketTimeout();
connState.setTimeout(timeout);
timeout = this.params.getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
conn.setSocketTimeout(timeout);
connState.setOutputState(ClientConnState.EXPECT_CONTINUE);
} else {
sendRequestBody(
(HttpEntityEnclosingRequest) request,
connState,
conn);
}
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
conn.suspendOutput();
return;
}
ContentOutputBuffer buffer = connState.getOutbuffer();
buffer.produceContent(encoder);
if (encoder.isCompleted()) {
connState.setInputState(ClientConnState.REQUEST_BODY_DONE);
} else {
connState.setInputState(ClientConnState.REQUEST_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = conn.getHttpResponse();
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
HttpRequest request = connState.getRequest();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
connState.setOutputState(ClientConnState.REQUEST_SENT);
continueRequest(conn, connState);
}
return;
} else {
connState.setResponse(response);
connState.setInputState(ClientConnState.RESPONSE_RECEIVED);
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
}
}
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
response.setEntity(null);
connState.setInputState(ClientConnState.RESPONSE_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
}
if (response.getEntity() != null) {
response.setEntity(new ContentBufferEntity(
response.getEntity(),
connState.getInbuffer()));
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
this.httpProcessor.process(response, context);
handleResponse(response, connState, conn);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = connState.getResponse();
ContentInputBuffer buffer = connState.getInbuffer();
buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
connState.setInputState(ClientConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setInputState(ClientConnState.RESPONSE_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void timeout(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
connState.setOutputState(ClientConnState.REQUEST_SENT);
continueRequest(conn, connState);
connState.notifyAll();
return;
}
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
handleTimeout(conn);
}
private void initialize(
final NHttpClientConnection conn,
final Object attachment) {
HttpContext context = conn.getContext();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.execHandler.initalizeContext(context, attachment);
}
private void continueRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
HttpRequest request = connState.getRequest();
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
sendRequestBody(
(HttpEntityEnclosingRequest) request,
connState,
conn);
}
/**
* @throws IOException - not thrown currently
*/
private void sendRequestBody(
final HttpEntityEnclosingRequest request,
final ClientConnState connState,
final NHttpClientConnection conn) throws IOException {
HttpEntity entity = request.getEntity();
if (entity != null) {
this.executor.execute(new Runnable() {
public void run() {
try {
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (!connState.isWorkerRunning()) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setWorkerRunning(true);
}
HttpEntity entity = request.getEntity();
OutputStream outstream = new ContentOutputStream(
connState.getOutbuffer());
entity.writeTo(outstream);
outstream.flush();
outstream.close();
synchronized (connState) {
connState.setWorkerRunning(false);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
}
}
});
}
}
private void handleResponse(
final HttpResponse response,
final ClientConnState connState,
final NHttpClientConnection conn) {
final HttpContext context = conn.getContext();
this.executor.execute(new Runnable() {
public void run() {
try {
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (!connState.isWorkerRunning()) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setWorkerRunning(true);
}
execHandler.handleResponse(response, context);
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getInputState();
if (currentState == ClientConnState.RESPONSE_DONE) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
}
connState.resetInput();
connState.resetOutput();
if (conn.isOpen()) {
conn.requestOutput();
}
connState.setWorkerRunning(false);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
}
}
});
}
static class ClientConnState {
public static final int SHUTDOWN = -1;
public static final int READY = 0;
public static final int REQUEST_SENT = 1;
public static final int EXPECT_CONTINUE = 2;
public static final int REQUEST_BODY_STREAM = 4;
public static final int REQUEST_BODY_DONE = 8;
public static final int RESPONSE_RECEIVED = 16;
public static final int RESPONSE_BODY_STREAM = 32;
public static final int RESPONSE_BODY_DONE = 64;
public static final int RESPONSE_DONE = 64;
private final SharedInputBuffer inbuffer;
private final SharedOutputBuffer outbuffer;
private volatile int inputState;
private volatile int outputState;
private volatile HttpRequest request;
private volatile HttpResponse response;
private volatile int timeout;
private volatile boolean workerRunning;
public ClientConnState(
int bufsize,
final IOControl ioControl,
final ByteBufferAllocator allocator) {
super();
this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator);
this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator);
this.inputState = READY;
this.outputState = READY;
}
public ContentInputBuffer getInbuffer() {
return this.inbuffer;
}
public ContentOutputBuffer getOutbuffer() {
return this.outbuffer;
}
public int getInputState() {
return this.inputState;
}
public void setInputState(int inputState) {
this.inputState = inputState;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public boolean isWorkerRunning() {
return this.workerRunning;
}
public void setWorkerRunning(boolean b) {
this.workerRunning = b;
}
public void close() {
this.inbuffer.close();
this.outbuffer.close();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void shutdown() {
this.inbuffer.shutdown();
this.outbuffer.shutdown();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void resetInput() {
this.inbuffer.reset();
this.request = null;
this.inputState = READY;
}
public void resetOutput() {
this.outbuffer.reset();
this.response = null;
this.outputState = READY;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/ThrottlingHttpClientHandler.java
|
Java
|
gpl3
| 25,047
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.NHttpEntityWrapper;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.entity.SkipContentListener;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Fully asynchronous HTTP client side protocol handler that implements the
* essential requirements of the HTTP protocol for the server side message
* processing as described by RFC 2616. It is capable of executing HTTP requests
* with nearly constant memory footprint. Only HTTP message heads are stored in
* memory, while content of message bodies is streamed directly from the entity
* to the underlying channel (and vice versa) using {@link ConsumingNHttpEntity}
* and {@link ProducingNHttpEntity} interfaces.
*
* When using this implementation, it is important to ensure that entities
* supplied for writing implement {@link ProducingNHttpEntity}. Doing so will allow
* the entity to be written out asynchronously. If entities supplied for writing
* do not implement the {@link ProducingNHttpEntity} interface, a delegate is
* added that buffers the entire contents in memory. Additionally, the
* buffering might take place in the I/O dispatch thread, which could cause I/O
* to block temporarily. For best results, one must ensure that all entities
* set on {@link HttpRequest}s from {@link NHttpRequestExecutionHandler}
* implement {@link ProducingNHttpEntity}.
*
* If incoming responses enclose a content entity,
* {@link NHttpRequestExecutionHandler} are expected to return a
* {@link ConsumingNHttpEntity} for reading the content. After the entity is
* finished reading the data,
* {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method is called to process the response.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* </ul>
*
* @see ConsumingNHttpEntity
* @see ProducingNHttpEntity
*
* @since 4.0
*/
public class AsyncNHttpClientHandler extends NHttpHandlerBase
implements NHttpClientHandler {
protected NHttpRequestExecutionHandler execHandler;
public AsyncNHttpClientHandler(
final HttpProcessor httpProcessor,
final NHttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
this.execHandler = execHandler;
}
public AsyncNHttpClientHandler(
final HttpProcessor httpProcessor,
final NHttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
HttpContext context = conn.getContext();
initialize(conn, attachment);
ClientConnState connState = new ClientConnState();
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
requestReady(conn);
}
public void closed(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
connState.reset();
} catch (IOException ex) {
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
this.execHandler.finalizeContext(context);
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void requestReady(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
if (connState.getOutputState() != ClientConnState.READY) {
return;
}
try {
HttpRequest request = this.execHandler.submitRequest(context);
if (request == null) {
return;
}
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(request, context);
HttpEntityEnclosingRequest entityReq = null;
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest) {
entityReq = (HttpEntityEnclosingRequest) request;
entity = entityReq.getEntity();
}
if (entity instanceof ProducingNHttpEntity) {
connState.setProducingEntity((ProducingNHttpEntity) entity);
} else if (entity != null) {
connState.setProducingEntity(new NHttpEntityWrapper(entity));
}
connState.setRequest(request);
conn.submitRequest(request);
connState.setOutputState(ClientConnState.REQUEST_SENT);
if (entityReq != null && entityReq.expectContinue()) {
int timeout = conn.getSocketTimeout();
connState.setTimeout(timeout);
timeout = this.params.getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
conn.setSocketTimeout(timeout);
connState.setOutputState(ClientConnState.EXPECT_CONTINUE);
} else if (connState.getProducingEntity() != null) {
connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity();
try {
consumingEntity.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
processResponse(conn, connState);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
conn.suspendOutput();
return;
}
ProducingNHttpEntity entity = connState.getProducingEntity();
entity.produceContent(encoder, conn);
if (encoder.isCompleted()) {
connState.setOutputState(ClientConnState.REQUEST_BODY_DONE);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
HttpResponse response = conn.getHttpResponse();
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
HttpRequest request = connState.getRequest();
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
continueRequest(conn, connState);
}
return;
} else {
connState.setResponse(response);
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
cancelRequest(conn, connState);
} else if (connState.getOutputState() == ClientConnState.REQUEST_BODY_STREAM) {
// Early response
cancelRequest(conn, connState);
connState.invalidate();
conn.suspendOutput();
}
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
response.setEntity(null);
this.httpProcessor.process(response, context);
processResponse(conn, connState);
} else {
HttpEntity entity = response.getEntity();
if (entity != null) {
ConsumingNHttpEntity consumingEntity = this.execHandler.responseEntity(
response, context);
if (consumingEntity == null) {
consumingEntity = new ConsumingNHttpEntityTemplate(
entity, new SkipContentListener(this.allocator));
}
response.setEntity(consumingEntity);
connState.setConsumingEntity(consumingEntity);
this.httpProcessor.process(response, context);
}
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void timeout(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
continueRequest(conn, connState);
return;
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
handleTimeout(conn);
}
private void initialize(
final NHttpClientConnection conn,
final Object attachment) {
HttpContext context = conn.getContext();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.execHandler.initalizeContext(context, attachment);
}
/**
* @throws IOException - not thrown currently
*/
private void continueRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM);
}
private void cancelRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
connState.resetOutput();
}
/**
* @throws HttpException - not thrown currently
*/
private void processResponse(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException, HttpException {
if (!connState.isValid()) {
conn.close();
}
HttpContext context = conn.getContext();
HttpResponse response = connState.getResponse();
this.execHandler.handleResponse(response, context);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
if (conn.isOpen()) {
// Ready for another request
connState.resetInput();
connState.resetOutput();
conn.requestOutput();
}
}
protected static class ClientConnState {
public static final int READY = 0;
public static final int REQUEST_SENT = 1;
public static final int EXPECT_CONTINUE = 2;
public static final int REQUEST_BODY_STREAM = 4;
public static final int REQUEST_BODY_DONE = 8;
public static final int RESPONSE_RECEIVED = 16;
public static final int RESPONSE_BODY_STREAM = 32;
public static final int RESPONSE_BODY_DONE = 64;
private int outputState;
private HttpRequest request;
private HttpResponse response;
private ConsumingNHttpEntity consumingEntity;
private ProducingNHttpEntity producingEntity;
private boolean valid;
private int timeout;
public ClientConnState() {
super();
this.valid = true;
}
public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) {
this.consumingEntity = consumingEntity;
}
public void setProducingEntity(final ProducingNHttpEntity producingEntity) {
this.producingEntity = producingEntity;
}
public ProducingNHttpEntity getProducingEntity() {
return producingEntity;
}
public ConsumingNHttpEntity getConsumingEntity() {
return consumingEntity;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void resetInput() throws IOException {
this.response = null;
if (this.consumingEntity != null) {
this.consumingEntity.finish();
this.consumingEntity = null;
}
}
public void resetOutput() throws IOException {
this.request = null;
if (this.producingEntity != null) {
this.producingEntity.finish();
this.producingEntity = null;
}
this.outputState = READY;
}
public void reset() throws IOException {
resetInput();
resetOutput();
}
public boolean isValid() {
return this.valid;
}
public void invalidate() {
this.valid = false;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/AsyncNHttpClientHandler.java
|
Java
|
gpl3
| 19,254
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpProcessor;
/**
* @deprecated No longer used.
*
* @since 4.0
*/
@Deprecated
public abstract class NHttpClientHandlerBase extends NHttpHandlerBase
implements NHttpClientHandler {
protected HttpRequestExecutionHandler execHandler;
public NHttpClientHandlerBase(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
this.execHandler = execHandler;
}
public void closed(final NHttpClientConnection conn) {
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpClientHandlerBase.java
|
Java
|
gpl3
| 3,050
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.HttpContext;
/**
* HTTP request execution handler can be used by client-side protocol handlers
* to trigger the submission of a new HTTP request and the processing of an
* HTTP response.
*
*
* @since 4.0
*/
public interface HttpRequestExecutionHandler {
/**
* Triggered when a new connection has been established and the
* HTTP context needs to be initialized.
*
* <p>The attachment object is the same object which was passed
* to the connecting I/O reactor when the connection request was
* made. The attachment may optionally contain some state information
* required in order to correctly initialize the HTTP context.
*
* @see ConnectingIOReactor#connect
*
* @param context the actual HTTP context
* @param attachment the object passed to the connecting I/O reactor
* upon the request for a new connection.
*/
void initalizeContext(HttpContext context, Object attachment);
/**
* Triggered when the underlying connection is ready to send a new
* HTTP request to the target host. This method may return
* <code>null</null> if the client is not yet ready to send a
* request. In this case the connection will remain open and
* can be activated at a later point.
*
* @param context the actual HTTP context
* @return an HTTP request to be sent or <code>null</null> if no
* request needs to be sent
*/
HttpRequest submitRequest(HttpContext context);
/**
* Triggered when an HTTP response is ready to be processed.
*
* @param response the HTTP response to be processed
* @param context the actual HTTP context
*/
void handleResponse(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when the connection is terminated. This event can be used
* to release objects stored in the context or perform some other kind
* of cleanup.
*
* @param context the actual HTTP context
*/
void finalizeContext(HttpContext context);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/HttpRequestExecutionHandler.java
|
Java
|
gpl3
| 3,488
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.HttpContext;
/**
* HTTP request execution handler can be used by client-side protocol handlers
* to trigger the submission of a new HTTP request and the processing of an HTTP
* response. When a new response entity is available for consumption,
* {@link #responseEntity(HttpResponse, HttpContext)} is called.
* After the {@link ConsumingNHttpEntity} consumes the response body,
* {@link #handleResponse(HttpResponse, HttpContext)} is notified that the
* response is fully read.
*
*
* @since 4.0
*/
public interface NHttpRequestExecutionHandler {
/**
* Triggered when a new connection has been established and the
* HTTP context needs to be initialized.
*
* <p>The attachment object is the same object which was passed
* to the connecting I/O reactor when the connection request was
* made. The attachment may optionally contain some state information
* required in order to correctly initalize the HTTP context.
*
* @see ConnectingIOReactor#connect
*
* @param context the actual HTTP context
* @param attachment the object passed to the connecting I/O reactor
* upon the request for a new connection.
*/
void initalizeContext(HttpContext context, Object attachment);
/**
* Triggered when the underlying connection is ready to send a new
* HTTP request to the target host. This method may return
* <code>null</null> if the client is not yet ready to send a
* request. In this case the connection will remain open and
* can be activated at a later point.
* <p>
* If the request has an entity, the entity <b>must</b> be an
* instance of {@link ProducingNHttpEntity}.
*
* @param context the actual HTTP context
* @return an HTTP request to be sent or <code>null</null> if no
* request needs to be sent
*/
HttpRequest submitRequest(HttpContext context);
/**
* Triggered when a response is received with an entity. This method should
* return a {@link ConsumingNHttpEntity} that will be used to consume the
* entity. <code>null</code> is a valid response value, and will indicate
* that the entity should be silently ignored.
* <p>
* After the entity is fully consumed,
* {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* is called to notify a full response & entity are ready to be processed.
*
* @param response
* The response containing the existing entity.
* @param context
* the actual HTTP context
* @return An entity that will asynchronously consume the response's content
* body.
*/
ConsumingNHttpEntity responseEntity(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when an HTTP response is ready to be processed.
*
* @param response
* the HTTP response to be processed
* @param context
* the actual HTTP context
*/
void handleResponse(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when the connection is terminated. This event can be used
* to release objects stored in the context or perform some other kind
* of cleanup.
*
* @param context the actual HTTP context
*/
void finalizeContext(HttpContext context);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpRequestExecutionHandler.java
|
Java
|
gpl3
| 4,950
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.protocol;
/**
* HttpRequestHandlerResolver can be used to resolve an instance of
* {@link NHttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public interface NHttpRequestHandlerResolver {
/**
* Looks up a handler matching the given request URI.
*
* @param requestURI the request URI
* @return HTTP request handler or <code>null</code> if no match
* is found.
*/
NHttpRequestHandler lookup(String requestURI);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/protocol/NHttpRequestHandlerResolver.java
|
Java
|
gpl3
| 1,804
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content encoder. HTTP content encoders can be used
* to apply the required coding transformation and write entity
* content to the underlying channel in small chunks.
*
* @since 4.0
*/
public interface ContentEncoder {
/**
* Writes a portion of entity content to the underlying channel.
*
* @param src The buffer from which content is to be retrieved
* @return The number of bytes read, possibly zero
* @throws IOException if I/O error occurs while writing content
*/
int write(ByteBuffer src) throws IOException;
/**
* Terminates the content stream.
*
* @throws IOException if I/O error occurs while writing content
*/
void complete() throws IOException;
/**
* Returns <code>true</code> if the entity has been transferred in its
* entirety.
*
* @return <code>true</code> if all the content has been produced,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/ContentEncoder.java
|
Java
|
gpl3
| 2,276
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
/**
* Abstract non-blocking server-side HTTP connection interface. It can be used
* to receive HTTP requests and asynchronously submit HTTP responses.
*
* @see NHttpConnection
*
* @since 4.0
*/
public interface NHttpServerConnection extends NHttpConnection {
/**
* Submits {link @HttpResponse} to be sent to the client.
*
* @param response HTTP response
*
* @throws IOException if I/O error occurs while submitting the response
* @throws HttpException if the HTTP response violates the HTTP protocol.
*/
void submitResponse(HttpResponse response) throws IOException, HttpException;
/**
* Returns <code>true</code> if an HTTP response has been submitted to the
* client.
*
* @return <code>true</code> if an HTTP response has been submitted,
* <code>false</code> otherwise.
*/
boolean isResponseSubmitted();
/**
* Resets output state. This method can be used to prematurely terminate
* processing of the incoming HTTP request.
*/
void resetInput();
/**
* Resets input state. This method can be used to prematurely terminate
* processing of the outgoing HTTP response.
*/
void resetOutput();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerConnection.java
|
Java
|
gpl3
| 2,550
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
/**
* Abstract HTTP message parser for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageParser<T extends HttpMessage> {
/**
* Resets the parser. The parser will be ready to start parsing another
* HTTP message.
*/
void reset();
/**
* Fills the internal buffer of the parser with input data from the
* given {@link ReadableByteChannel}.
*
* @param channel the input channel
* @return number of bytes read.
* @throws IOException in case of an I/O error.
*/
int fillBuffer(ReadableByteChannel channel)
throws IOException;
/**
* Attempts to parse a complete message head from the content of the
* internal buffer. If the message in the input buffer is incomplete
* this method will return <code>null</code>.
*
* @return HTTP message head, if available, <code>null</code> otherwise.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
T parse() throws IOException, HttpException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageParser.java
|
Java
|
gpl3
| 2,495
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
/**
* Abstract non-blocking client-side HTTP connection interface. It can be used
* to submit HTTP requests and asynchronously receive HTTP responses.
*
* @see NHttpConnection
*
* @since 4.0
*/
public interface NHttpClientConnection extends NHttpConnection {
/**
* Submits {@link HttpRequest} to be sent to the target server.
*
* @param request HTTP request
* @throws IOException if I/O error occurs while submitting the request
* @throws HttpException if the HTTP request violates the HTTP protocol.
*/
void submitRequest(HttpRequest request) throws IOException, HttpException;
/**
* Returns <code>true</code> if an HTTP request has been submitted to the
* target server.
*
* @return <code>true</code> if an HTTP request has been submitted,
* <code>false</code> otherwise.
*/
boolean isRequestSubmitted();
/**
* Resets output state. This method can be used to prematurely terminate
* processing of the outgoing HTTP request.
*/
void resetOutput();
/**
* Resets input state. This method can be used to prematurely terminate
* processing of the incoming HTTP response.
*/
void resetInput();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientConnection.java
|
Java
|
gpl3
| 2,545
|
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
-->
</head>
<body>
Various buffering primitives intended to facilitate content streaming for
non-blocking HTTP connections.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/package.html
|
HTML
|
gpl3
| 1,343
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentInputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expect to transfer data from {@link ContentDecoder} to the buffer
* by calling {@link #consumeContent(ContentDecoder)}.
* <p>
* The worker thread is expected to read the data from the buffer by calling
* {@link #read()} or {@link #read(byte[], int, int)} methods.
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be shut down
* using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedInputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
public int consumeContent(final ContentDecoder decoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setInputMode();
int totalRead = 0;
int bytesRead;
while ((bytesRead = decoder.read(this.buffer)) > 0) {
totalRead += bytesRead;
}
if (bytesRead == -1 || decoder.isCompleted()) {
this.endOfStream = true;
}
if (!this.buffer.hasRemaining()) {
this.ioctrl.suspendInput();
}
this.condition.signalAll();
if (totalRead > 0) {
return totalRead;
} else {
if (this.endOfStream) {
return -1;
} else {
return 0;
}
}
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
protected void waitForData() throws IOException {
this.lock.lock();
try {
try {
while (!super.hasData() && !this.endOfStream) {
if (this.shutdown) {
throw new InterruptedIOException("Input operation aborted");
}
this.ioctrl.requestInput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while waiting for more data");
}
} finally {
this.lock.unlock();
}
}
public void close() {
if (this.shutdown) {
return;
}
this.endOfStream = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
protected boolean isShutdown() {
return this.shutdown;
}
protected boolean isEndOfStream() {
return this.shutdown || (!hasData() && this.endOfStream);
}
public int read() throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
return this.buffer.get() & 0xff;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b, int off, int len) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
setOutputMode();
int chunk = len;
if (chunk > this.buffer.remaining()) {
chunk = this.buffer.remaining();
}
this.buffer.get(b, off, chunk);
return chunk;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedInputBuffer.java
|
Java
|
gpl3
| 7,472
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
/**
* Basic implementation of the {@link ContentInputBuffer} interface.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
public class SimpleInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
private boolean endOfStream = false;
public SimpleInputBuffer(int buffersize, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
}
public void reset() {
this.endOfStream = false;
super.clear();
}
public int consumeContent(final ContentDecoder decoder) throws IOException {
setInputMode();
int totalRead = 0;
int bytesRead;
while ((bytesRead = decoder.read(this.buffer)) != -1) {
if (bytesRead == 0) {
if (!this.buffer.hasRemaining()) {
expand();
} else {
break;
}
} else {
totalRead += bytesRead;
}
}
if (bytesRead == -1 || decoder.isCompleted()) {
this.endOfStream = true;
}
return totalRead;
}
public boolean isEndOfStream() {
return !hasData() && this.endOfStream;
}
public int read() throws IOException {
if (isEndOfStream()) {
return -1;
}
return this.buffer.get() & 0xff;
}
public int read(final byte[] b, int off, int len) throws IOException {
if (isEndOfStream()) {
return -1;
}
if (b == null) {
return 0;
}
setOutputMode();
int chunk = len;
if (chunk > this.buffer.remaining()) {
chunk = this.buffer.remaining();
}
this.buffer.get(b, off, chunk);
return chunk;
}
public int read(final byte[] b) throws IOException {
if (isEndOfStream()) {
return -1;
}
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
public void shutdown() {
this.endOfStream = true;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleInputBuffer.java
|
Java
|
gpl3
| 3,358
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Abstract interface to allocate {@link ByteBuffer} instances.
*
* @since 4.0
*/
public interface ByteBufferAllocator {
/**
* Allocates {@link ByteBuffer} of the given size.
*
* @param size the size of the buffer.
* @return byte buffer.
*/
ByteBuffer allocate(int size);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ByteBufferAllocator.java
|
Java
|
gpl3
| 1,565
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Buffer for storing content to be streamed out to a {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ContentOutputBuffer {
/**
* Writes content from this buffer to the given {@link ContentEncoder}.
*
* @param encoder content encoder.
* @return number of bytes written.
* @throws IOException in case of an I/O error.
*/
int produceContent(ContentEncoder encoder) throws IOException;
/**
* Resets the buffer by clearing its state and stored content.
*/
void reset();
/**
* @deprecated No longer used.
*/
@Deprecated
void flush() throws IOException;
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, this method can throw a runtime exception. The exact type
* of runtime exception thrown by this method depends on implementation.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes the specified byte to this buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Indicates the content has been fully written.
* @exception IOException if an I/O error occurs.
*/
void writeCompleted() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentOutputBuffer.java
|
Java
|
gpl3
| 3,059
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocateDirect(int)}.
*
* @since 4.0
*/
public class DirectByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/DirectByteBufferAllocator.java
|
Java
|
gpl3
| 1,538
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentOutputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expected to transfer data from the buffer to
* {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}.
* <p>
* The worker thread is expected to write data to the buffer by calling
* {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()}
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be
* shut down using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedOutputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
public int produceContent(final ContentEncoder encoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setOutputMode();
int bytesWritten = 0;
if (super.hasData()) {
bytesWritten = encoder.write(this.buffer);
if (encoder.isCompleted()) {
this.endOfStream = true;
}
}
if (!super.hasData()) {
// No more buffered content
// If at the end of the stream, terminate
if (this.endOfStream && !encoder.isCompleted()) {
encoder.complete();
}
if (!this.endOfStream) {
// suspend output events
this.ioctrl.suspendOutput();
}
}
this.condition.signalAll();
return bytesWritten;
} finally {
this.lock.unlock();
}
}
public void close() {
shutdown();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
int remaining = len;
while (remaining > 0) {
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
int chunk = Math.min(remaining, this.buffer.remaining());
this.buffer.put(b, off, chunk);
remaining -= chunk;
off += chunk;
}
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
this.buffer.put((byte)b);
} finally {
this.lock.unlock();
}
}
public void flush() throws IOException {
}
private void flushContent() throws IOException {
this.lock.lock();
try {
try {
while (super.hasData()) {
if (this.shutdown) {
throw new InterruptedIOException("Output operation aborted");
}
this.ioctrl.requestOutput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while flushing the content buffer");
}
} finally {
this.lock.unlock();
}
}
public void writeCompleted() throws IOException {
this.lock.lock();
try {
if (this.endOfStream) {
return;
}
this.endOfStream = true;
this.ioctrl.requestOutput();
} finally {
this.lock.unlock();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedOutputBuffer.java
|
Java
|
gpl3
| 7,676
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
import org.apache.http.io.BufferInfo;
/**
* A buffer that expand its capacity on demand using {@link ByteBufferAllocator}
* interface. Internally, this class is backed by an instance of
* {@link ByteBuffer}.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
public class ExpandableBuffer implements BufferInfo, org.apache.http.nio.util.BufferInfo {
public final static int INPUT_MODE = 0;
public final static int OUTPUT_MODE = 1;
private int mode;
protected ByteBuffer buffer = null;
private final ByteBufferAllocator allocator;
/**
* Allocates buffer of the given size using the given allocator.
*
* @param buffersize the buffer size.
* @param allocator allocator to be used to allocate {@link ByteBuffer}s.
*/
public ExpandableBuffer(int buffersize, final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.allocator = allocator;
this.buffer = allocator.allocate(buffersize);
this.mode = INPUT_MODE;
}
/**
* Returns the current mode:
* <p>
* {@link #INPUT_MODE}: the buffer is in the input mode.
* <p>
* {@link #OUTPUT_MODE}: the buffer is in the output mode.
*
* @return current input/output mode.
*/
protected int getMode() {
return this.mode;
}
/**
* Sets output mode. The buffer can now be read from.
*/
protected void setOutputMode() {
if (this.mode != OUTPUT_MODE) {
this.buffer.flip();
this.mode = OUTPUT_MODE;
}
}
/**
* Sets input mode. The buffer can now be written into.
*/
protected void setInputMode() {
if (this.mode != INPUT_MODE) {
if (this.buffer.hasRemaining()) {
this.buffer.compact();
} else {
this.buffer.clear();
}
this.mode = INPUT_MODE;
}
}
private void expandCapacity(int capacity) {
ByteBuffer oldbuffer = this.buffer;
this.buffer = allocator.allocate(capacity);
oldbuffer.flip();
this.buffer.put(oldbuffer);
}
/**
* Expands buffer's capacity.
*/
protected void expand() {
int newcapacity = (this.buffer.capacity() + 1) << 1;
if (newcapacity < 0) {
newcapacity = Integer.MAX_VALUE;
}
expandCapacity(newcapacity);
}
/**
* Ensures the buffer can accommodate the required capacity.
*
* @param requiredCapacity
*/
protected void ensureCapacity(int requiredCapacity) {
if (requiredCapacity > this.buffer.capacity()) {
expandCapacity(requiredCapacity);
}
}
/**
* Returns the total capacity of this buffer.
*
* @return total capacity.
*/
public int capacity() {
return this.buffer.capacity();
}
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
public boolean hasData() {
setOutputMode();
return this.buffer.hasRemaining();
}
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
public int length() {
setOutputMode();
return this.buffer.remaining();
}
/**
* Returns available capacity of this buffer.
*
* @return buffer length.
*/
public int available() {
setInputMode();
return this.buffer.remaining();
}
/**
* Clears buffer.
*/
protected void clear() {
this.buffer.clear();
this.mode = INPUT_MODE;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[mode=");
int mode = getMode();
if (mode == INPUT_MODE) {
sb.append("in");
} else {
sb.append("out");
}
sb.append(" pos=");
sb.append(this.buffer.position());
sb.append(" lim=");
sb.append(this.buffer.limit());
sb.append(" cap=");
sb.append(this.buffer.capacity());
sb.append("]");
return sb.toString();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ExpandableBuffer.java
|
Java
|
gpl3
| 5,640
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocate(int)}.
*
* @since 4.0
*/
public class HeapByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocate(size);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/HeapByteBufferAllocator.java
|
Java
|
gpl3
| 1,524
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
/**
* Buffer for storing content streamed out from a {@link ContentDecoder}.
*
* @since 4.0
*/
public interface ContentInputBuffer {
/**
* Reads content from the given {@link ContentDecoder} and stores it in
* this buffer.
*
* @param decoder the content decoder.
* @return number of bytes read.
* @throws IOException in case of an I/O error.
*/
int consumeContent(ContentDecoder decoder) throws IOException;
/**
* Resets the buffer by clearing its state and stored content.
*/
void reset();
/**
* Reads up to <code>len</code> bytes of data from this buffer into
* an array of bytes. The exact number of bytes read depends how many bytes
* are stored in the buffer.
*
* <p> If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, this method can throw a runtime exception. The exact type
* of runtime exception thrown by this method depends on implementation.
* This method returns <code>-1</code> if the end of content stream has been
* reached.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Reads one byte from this buffer. If the buffer is empty this method can
* throw a runtime exception. The exact type of runtime exception thrown
* by this method depends on implementation. This method returns
* <code>-1</code> if the end of content stream has been reached.
*
* @return one byte
*/
int read() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentInputBuffer.java
|
Java
|
gpl3
| 3,413
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Basic implementation of the {@link ContentOutputBuffer} interface.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
public class SimpleOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private boolean endOfStream;
public SimpleOutputBuffer(int buffersize, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
this.endOfStream = false;
}
public int produceContent(final ContentEncoder encoder) throws IOException {
setOutputMode();
int bytesWritten = encoder.write(this.buffer);
if (!hasData() && this.endOfStream) {
encoder.complete();
}
return bytesWritten;
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.buffer.position() + len);
this.buffer.put(b, off, len);
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.capacity() + 1);
this.buffer.put((byte)b);
}
public void reset() {
super.clear();
this.endOfStream = false;
}
public void flush() {
}
public void writeCompleted() {
this.endOfStream = true;
}
public void shutdown() {
this.endOfStream = true;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleOutputBuffer.java
|
Java
|
gpl3
| 3,024
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* 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/>.
*
*/
package org.apache.http.nio.util;
/**
* Basic buffer properties.
*
* @since 4.0
*
* @deprecated Use {@link org.apache.http.io.BufferInfo}
*/
@Deprecated
public interface BufferInfo {
int length();
int capacity();
int available();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/BufferInfo.java
|
Java
|
gpl3
| 1,440
|