code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* 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;
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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 org.apache.http.HttpConnection;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* Abstract non-blocking HTTP connection interface. Each connection contains an
* HTTP execution context, which can be used to maintain a processing state,
* as well as the actual {@link HttpRequest} and {@link HttpResponse} that are
* being transmitted over this connection. Both the request and
* the response objects can be <code>null</code> if there is no incoming or
* outgoing message currently being transferred.
* <p>
* Please note non-blocking HTTP connections are stateful and not thread safe.
* Input / output operations on non-blocking HTTP connections should be
* restricted to the dispatch events triggered by the I/O event dispatch thread.
* However, the {@link IOControl} interface is fully threading safe and can be
* manipulated from any thread.
*
* @since 4.0
*/
public interface NHttpConnection extends HttpConnection, IOControl {
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = 2;
/**
* Returns status of the connection:
* <p>
* {@link #ACTIVE}: connection is active.
* <p>
* {@link #CLOSING}: connection is being closed.
* <p>
* {@link #CLOSED}: connection has been closed.
*
* @return connection status.
*/
int getStatus();
/**
* Returns the current HTTP request if one is being received / transmitted.
* Otherwise returns <code>null</code>.
*
* @return HTTP request, if available, <code>null</code> otherwise.
*/
HttpRequest getHttpRequest();
/**
* Returns the current HTTP response if one is being received / transmitted.
* Otherwise returns <tt>null</tt>.
*
* @return HTTP response, if available, <code>null</code> otherwise.
*/
HttpResponse getHttpResponse();
/**
* Returns an HTTP execution context associated with this connection.
* @return HTTP context
*/
HttpContext getContext();
}
| Java |
/*
* ====================================================================
* 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 org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpServerConnection} used by
* {@link IOEventDispatch} implementations to inform server-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpServerIOTarget extends NHttpServerConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the server protocol handler.
*/
void consumeInput(NHttpServiceHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the server protocol handler.
*/
void produceOutput(NHttpServiceHandler handler);
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.protocol.HTTP;
/**
* A simple, self contained, repeatable non-blocking entity that retrieves
* its content from a {@link String} object.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*
*/
public class NStringEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NStringEntity(final String s, String charset)
throws UnsupportedEncodingException {
if (s == null) {
throw new IllegalArgumentException("Source string may not be null");
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
this.content = s.getBytes(charset);
this.buffer = ByteBuffer.wrap(this.content);
setContentType(HTTP.PLAIN_TEXT_TYPE + HTTP.CHARSET_PARAM + charset);
}
public NStringEntity(final String s) throws UnsupportedEncodingException {
this(s, null);
}
public boolean isRepeatable() {
return true;
}
public long getContentLength() {
return this.buffer.limit();
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A listener for available data on a non-blocking {@link ConsumingNHttpEntity}.
*
* @since 4.0
*/
public interface ContentListener {
/**
* Notification that content is available to be read from the decoder.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void contentAvailable(ContentDecoder decoder, IOControl ioctrl)
throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finished();
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A {@link ConsumingNHttpEntity} that forwards available content to a
* {@link ContentListener}.
*
* @since 4.0
*/
public class ConsumingNHttpEntityTemplate
extends HttpEntityWrapper implements ConsumingNHttpEntity {
private final ContentListener contentListener;
public ConsumingNHttpEntityTemplate(
final HttpEntity httpEntity,
final ContentListener contentListener) {
super(httpEntity);
this.contentListener = contentListener;
}
public ContentListener getContentListener() {
return contentListener;
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.contentListener.contentAvailable(decoder, ioctrl);
}
public void finish() {
this.contentListener.finished();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* An {@link HttpEntity} that can stream content out into a
* {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ProducingNHttpEntity extends HttpEntity {
/**
* Notification that content should be written to the encoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend output events if the entity is temporarily unable to
* produce more content.
* <p>
* When all content is finished, this <b>MUST</b> call {@link ContentEncoder#complete()}.
* Failure to do so could result in the entity never being written.
*
* @param encoder content encoder.
* @param ioctrl I/O control of the underlying connection.
*/
void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for writing can be released.
*/
void finish() throws IOException;
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
/**
* An entity whose content is retrieved from a string. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NStringEntity}
*
* @since 4.0
*/
@Deprecated
public class StringNIOEntity extends StringEntity implements HttpNIOEntity {
public StringNIOEntity(
final String s,
String charset) throws UnsupportedEncodingException {
super(s, charset);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
/**
* A simple self contained, repeatable non-blocking entity that retrieves
* its content from a byte array.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*/
public class NByteArrayEntity
extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NByteArrayEntity(final byte[] b) {
this.content = b;
this.buffer = ByteBuffer.wrap(b);
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public long getContentLength() {
return buffer.limit();
}
public boolean isRepeatable() {
return true;
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
/**
* A simple {@link ContentListener} that reads and ignores all content.
*
* @since 4.0
*/
public class SkipContentListener implements ContentListener {
private final ByteBuffer buffer;
public SkipContentListener(final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.buffer = allocator.allocate(2048);
}
public void contentAvailable(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
int totalRead = 0;
int lastRead;
do {
buffer.clear();
lastRead = decoder.read(buffer);
if (lastRead > 0)
totalRead += lastRead;
} while (lastRead > 0);
}
public void finished() {
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* {@link ProducingNHttpEntity} compatibility adaptor for blocking HTTP
* entities.
*
* @since 4.0
*/
public class NHttpEntityWrapper
extends HttpEntityWrapper implements ProducingNHttpEntity {
private final ReadableByteChannel channel;
private final ByteBuffer buffer;
public NHttpEntityWrapper(final HttpEntity httpEntity) throws IOException {
super(httpEntity);
this.channel = Channels.newChannel(httpEntity.getContent());
this.buffer = ByteBuffer.allocate(4096);
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void produceContent(
final ContentEncoder encoder,
final IOControl ioctrl) throws IOException {
int i = this.channel.read(this.buffer);
this.buffer.flip();
encoder.write(this.buffer);
boolean buffering = this.buffer.hasRemaining();
this.buffer.compact();
if (i == -1 && !buffering) {
encoder.complete();
this.channel.close();
}
}
public void finish() {
try {
this.channel.close();
} catch (IOException ignore) {
}
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.nio.util.ContentOutputBuffer;
/**
* {@link OutputStream} adaptor for {@link ContentOutputBuffer}.
*
* @since 4.0
*/
public class ContentOutputStream extends OutputStream {
private final ContentOutputBuffer buffer;
public ContentOutputStream(final ContentOutputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Output buffer may not be null");
}
this.buffer = buffer;
}
@Override
public void close() throws IOException {
this.buffer.writeCompleted();
}
@Override
public void flush() throws IOException {
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.buffer.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
this.buffer.write(b, 0, b.length);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.SimpleInputBuffer;
/**
* A {@link ConsumingNHttpEntity} that consumes content into a buffer. The
* content can be retrieved as an InputStream via
* {@link HttpEntity#getContent()}, or written to an output stream via
* {@link HttpEntity#writeTo(OutputStream)}.
*
* @since 4.0
*/
public class BufferingNHttpEntity extends HttpEntityWrapper implements
ConsumingNHttpEntity {
private final static int BUFFER_SIZE = 2048;
private final SimpleInputBuffer buffer;
private boolean finished;
private boolean consumed;
public BufferingNHttpEntity(
final HttpEntity httpEntity,
final ByteBufferAllocator allocator) {
super(httpEntity);
this.buffer = new SimpleInputBuffer(BUFFER_SIZE, allocator);
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
this.finished = true;
}
}
public void finish() {
this.finished = true;
}
@Override
public void consumeContent() throws IOException {
}
/**
* Obtains entity's content as {@link InputStream}.
*
* @throws IllegalStateException if content of the entity has not been
* fully received or has already been consumed.
*/
@Override
public InputStream getContent() throws IOException {
if (!this.finished) {
throw new IllegalStateException("Entity content has not been fully received");
}
if (this.consumed) {
throw new IllegalStateException("Entity content has been consumed");
}
this.consumed = true;
return new ContentInputStream(this.buffer);
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = getContent();
byte[] buffer = new byte[BUFFER_SIZE];
int l;
// consume until EOF
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* HTTP entity wrapper whose content is provided by a
* {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentBufferEntity extends BasicHttpEntity {
private HttpEntity wrappedEntity;
/**
* Creates new instance of ContentBufferEntity.
*
* @param entity the original entity.
* @param buffer the content buffer.
*/
public ContentBufferEntity(final HttpEntity entity, final ContentInputBuffer buffer) {
super();
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
this.wrappedEntity = entity;
setContent(new ContentInputStream(buffer));
}
@Override
public boolean isChunked() {
return this.wrappedEntity.isChunked();
}
@Override
public long getContentLength() {
return this.wrappedEntity.getContentLength();
}
@Override
public Header getContentType() {
return this.wrappedEntity.getContentType();
}
@Override
public Header getContentEncoding() {
return this.wrappedEntity.getContentEncoding();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.ContentEncoderChannel;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.IOControl;
/**
* A self contained, repeatable non-blocking entity that retrieves its content
* from a file. This class is mostly used to stream large files of different
* types, so one needs to supply the content type of the file to make sure
* the content can be correctly recognized and processed by the recipient.
*
* @since 4.0
*/
public class NFileEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
private final File file;
private FileChannel fileChannel;
private long idx = -1;
private boolean useFileChannels;
/**
* Creates new instance of NFileEntity from the given source {@link File}
* with the given content type. If <code>useFileChannels</code> is set to
* <code>true</code>, the entity will try to use {@link FileContentEncoder}
* interface to stream file content directly from the file channel.
*
* @param file the source file.
* @param contentType the content type of the file.
* @param useFileChannels flag whether the direct transfer from the file
* channel should be attempted.
*/
public NFileEntity(final File file, final String contentType, boolean useFileChannels) {
if (file == null) {
throw new IllegalArgumentException("File may not be null");
}
this.file = file;
this.useFileChannels = useFileChannels;
setContentType(contentType);
}
public NFileEntity(final File file, final String contentType) {
this(file, contentType, true);
}
public void finish() {
try {
if(fileChannel != null)
fileChannel.close();
} catch(IOException ignored) {}
fileChannel = null;
}
public long getContentLength() {
return file.length();
}
public boolean isRepeatable() {
return true;
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
if(fileChannel == null) {
FileInputStream in = new FileInputStream(file);
fileChannel = in.getChannel();
idx = 0;
}
long transferred;
if(useFileChannels && encoder instanceof FileContentEncoder) {
transferred = ((FileContentEncoder)encoder)
.transfer(fileChannel, idx, Long.MAX_VALUE);
} else {
transferred = fileChannel.
transferTo(idx, Long.MAX_VALUE, new ContentEncoderChannel(encoder));
}
if(transferred > 0)
idx += transferred;
if(idx >= fileChannel.size())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() throws IOException {
return new FileInputStream(this.file);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new FileInputStream(this.file);
try {
byte[] tmp = new byte[4096];
int l;
while ((l = instream.read(tmp)) != -1) {
outstream.write(tmp, 0, l);
}
outstream.flush();
} finally {
instream.close();
}
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
/**
* @deprecated Use {@link ProducingNHttpEntity}
*
* @since 4.0
*/
@Deprecated
public interface HttpNIOEntity extends HttpEntity {
ReadableByteChannel getChannel() throws IOException;
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.FileEntity;
/**
* An entity whose content is retrieved from from a file. In addition to the standard
* {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NFileEntity}
*
* @since 4.0
*/
@Deprecated
public class FileNIOEntity extends FileEntity implements HttpNIOEntity {
public FileNIOEntity(final File file, final String contentType) {
super(file, contentType);
}
public ReadableByteChannel getChannel() throws IOException {
RandomAccessFile rafile = new RandomAccessFile(this.file, "r");
return rafile.getChannel();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.io.BufferInfo;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* {@link InputStream} adaptor for {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentInputStream extends InputStream {
private final ContentInputBuffer buffer;
public ContentInputStream(final ContentInputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Input buffer may not be null");
}
this.buffer = buffer;
}
@Override
public int available() throws IOException {
if (this.buffer instanceof BufferInfo) {
return ((BufferInfo) this.buffer).length();
} else {
return super.available();
}
}
@Override
public int read(final byte[] b, int off, int len) throws IOException {
return this.buffer.read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
if (b == null) {
return 0;
}
return this.buffer.read(b, 0, b.length);
}
@Override
public int read() throws IOException {
return this.buffer.read();
}
@Override
public void close() throws IOException {
// read and discard the remainder of the message
byte tmp[] = new byte[1024];
while (this.buffer.read(tmp, 0, tmp.length) >= 0) {
}
super.close();
}
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A non-blocking {@link HttpEntity} that allows content to be streamed from a
* {@link ContentDecoder}.
*
* @since 4.0
*/
public interface ConsumingNHttpEntity extends HttpEntity {
/**
* Notification that content is available to be read from the decoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend input events if the entity is temporarily unable to
* allocate more storage to accommodate all incoming content.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finish() throws IOException;
}
| Java |
/*
* ====================================================================
* 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.entity;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
/**
* An entity whose content is retrieved from a byte array. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NByteArrayEntity}
*
* @since 4.0
*/
@Deprecated
public class ByteArrayNIOEntity extends ByteArrayEntity implements HttpNIOEntity {
public ByteArrayNIOEntity(final byte[] b) {
super(b);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
| Java |
/*
* ====================================================================
* 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;
/**
* Abstract server-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpServiceHandler {
/**
* Triggered when a new incoming connection is created.
*
* @param conn new incoming connection HTTP connection.
*/
void connected(NHttpServerConnection conn);
/**
* Triggered when a new HTTP request is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP request object.
* <p/>
* If the request received encloses a request entity this method will
* be followed a series of
* {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls
* to transfer the request content.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains a new HTTP request
*/
void requestReceived(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the request entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming request content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpServerConnection conn, ContentDecoder decoder);
/**
* Triggered when the connection is ready to accept a new HTTP response.
* The protocol handler does not have to submit a response if it is not
* ready.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReady(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for writing a
* next portion of the response entity through the corresponding
* content encoder.
* <p/>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing response content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpServerConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpServerConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP request.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpServerConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpServerConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpServerConnection conn);
}
| Java |
/*
* ====================================================================
* 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();
}
| Java |
/*
* ====================================================================
* 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.HttpMessage;
/**
* Abstract HTTP message writer for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageWriter<T extends HttpMessage> {
/**
* Resets the writer. The writer will be ready to start serializing another
* HTTP message.
*/
void reset();
/**
* Serializes out the HTTP message head.
*
* @param message HTTP message.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
void write(T message) throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* 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;
/**
* Abstract client-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpClientHandler {
/**
* Triggered when a new outgoing connection is created.
*
* @param conn new outgoing HTTP connection.
* @param attachment an object that was attached to the session request
*/
void connected(NHttpClientConnection conn, Object attachment);
/**
* Triggered when the connection is ready to accept a new HTTP request.
* The protocol handler does not have to submit a request if it is not
* ready.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that is ready to accept a new HTTP request.
*/
void requestReady(NHttpClientConnection conn);
/**
* Triggered when an HTTP response is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP response object.
* <p/>
* If the response received encloses a response entity this method will
* be followed by a series of
* {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls
* to transfer the response content.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReceived(NHttpClientConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the response entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming response content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpClientConnection conn, ContentDecoder decoder);
/**
* Triggered when the underlying channel is ready for writing a next portion
* of the request entity through the corresponding content encoder.
* <p>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing request content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpClientConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpClientConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP response.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpClientConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpClientConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpClientConnection conn);
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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";
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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 org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpClientConnection} used by
* {@link IOEventDispatch} implementations to inform client-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpClientIOTarget extends NHttpClientConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the client protocol handler.
*/
void consumeInput(NHttpClientHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the client protocol handler.
*/
void produceOutput(NHttpClientHandler handler);
}
| Java |
/*
* ====================================================================
* 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.FileChannel;
/**
* A content decoder capable of transferring data directly to a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentDecoder extends ContentDecoder {
/**
* Transfers a portion of entity content from the underlying network channel
* into the given file channel.<br>
*
* <b>Warning</b>: Many implementations cannot write beyond the length of the file.
* If the position exceeds the channel's size, some implementations
* may throw an IOException.
*
* @param dst the target FileChannel to transfer data into.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative.
* <b>Must be less than or equal to the size of the file</b>
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
* @throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel dst, long position, long count) throws IOException;
}
| Java |
/*
* ====================================================================
* 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 decoder. HTTP content decoders can be used
* to read entity content from the underlying channel in small
* chunks and apply the required coding transformation.
*
* @since 4.0
*/
public interface ContentDecoder {
/**
* Reads a portion of content from the underlying channel
*
* @param dst The buffer into which entity content is to be transferred
* @return The number of bytes read, possibly zero, or -1 if the
* channel has reached end-of-stream
* @throws IOException if I/O error occurs while reading content
*/
int read(ByteBuffer dst) throws IOException;
/**
* Returns <code>true</code> if the entity has been received in its
* entirety.
*
* @return <code>true</code> if all the content has been consumed,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
| Java |
/*
* ====================================================================
* 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();
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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();
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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();
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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));
}
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
}
| Java |
/*
* ====================================================================
* 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);
}
| Java |
/*
* ====================================================================
* 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);
}
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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);
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
| Java |
/*
* ====================================================================
* 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);
}
| Java |
/*
* ====================================================================
* 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);
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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);
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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");
}
}
}
| Java |
/*
* ====================================================================
* 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();
}
}
| Java |
/*
* ====================================================================
* 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;
}
}
}
| Java |
/*
* ====================================================================
* 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.params.SyncBasicHttpParams;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.HttpParams;
public class ElementalEchoServer {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch();
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
ioReactor.listen(new InetSocketAddress(8080));
try {
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 DefaultIoEventDispatch implements IOEventDispatch {
private final ByteBuffer buffer = ByteBuffer.allocate(1024);
public void connected(IOSession session) {
System.out.println("connected");
session.setEventMask(EventMask.READ);
session.setSocketTimeout(20000);
}
public void inputReady(final IOSession session) {
System.out.println("readable");
try {
this.buffer.compact();
int bytesRead = session.channel().read(this.buffer);
if (this.buffer.position() > 0) {
session.setEventMask(EventMask.READ_WRITE);
}
System.out.println("Bytes read: " + bytesRead);
if (bytesRead == -1) {
session.close();
}
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void outputReady(final IOSession session) {
System.out.println("writeable");
try {
this.buffer.flip();
int bytesWritten = session.channel().write(this.buffer);
if (!this.buffer.hasRemaining()) {
session.setEventMask(EventMask.READ);
}
System.out.println("Bytes written: " + bytesWritten);
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void timeout(final IOSession session) {
System.out.println("timeout");
session.close();
}
public void disconnected(final IOSession session) {
System.out.println("disconnected");
}
}
}
| Java |
/*
* ====================================================================
* 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.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Locale;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
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.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
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.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
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, HTTPS/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 NHttpSSLServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
ClassLoader cl = NHttpSSLServer.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
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, "Jakarta-HttpComponents-NIO/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 SSLServerIOEventDispatch(
handler,
sslcontext,
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);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(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());
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.