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.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
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.examples.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BufferingHttpClientHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.HttpRequestExecutionHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; 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.ExecutionContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing HTTP requests using 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 client. * * */ public class NHttpClient { public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); // We are going to use this object to synchronize between the // I/O event and main threads CountDownLatch requestCount = new CountDownLatch(3); BufferingHttpClientHandler handler = new BufferingHttpClientHandler( httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { 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"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[3]; reqs[0] = ioReactor.connect( new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"), new MySessionRequestCallback(requestCount)); reqs[1] = ioReactor.connect( new InetSocketAddress("www.google.com", 80), null, new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount)); reqs[2] = ioReactor.connect( new InetSocketAddress("www.apache.org", 80), null, new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); } static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler { private final static String REQUEST_SENT = "request-sent"; private final static String RESPONSE_RECEIVED = "response-received"; private final CountDownLatch requestCount; public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void initalizeContext(final HttpContext context, final Object attachment) { HttpHost targetHost = (HttpHost) attachment; context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); } public void finalizeContext(final HttpContext context) { Object flag = context.getAttribute(RESPONSE_RECEIVED); if (flag == null) { // Signal completion of the request execution requestCount.countDown(); } } public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object flag = context.getAttribute(REQUEST_SENT); if (flag == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { HttpEntity entity = response.getEntity(); try { String content = EntityUtils.toString(entity); System.out.println("--------------"); System.out.println(response.getStatusLine()); System.out.println("--------------"); System.out.println("Document length: " + content.length()); System.out.println("--------------"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE); // Signal completion of the request execution requestCount.countDown(); } } static class MySessionRequestCallback implements SessionRequestCallback { private final CountDownLatch requestCount; public MySessionRequestCallback(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void cancelled(final SessionRequest request) { System.out.println("Connect request cancelled: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void completed(final SessionRequest request) { } public void failed(final SessionRequest request) { System.out.println("Connect request failed: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void timeout(final SessionRequest request) { System.out.println("Connect request timed out: " + request.getRemoteAddress()); this.requestCount.countDown(); } } 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
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.examples.nio; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.util.concurrent.CountDownLatch; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BufferingHttpClientHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.HttpRequestExecutionHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; 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.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Elemental example for executing HTTPS requests using 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 client. * * */ public class NHttpSSLClient { public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "Jakarta-HttpComponents-NIO/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); // Initialize default SSL context SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, null, null); // We are going to use this object to synchronize between the // I/O event and main threads CountDownLatch requestCount = new CountDownLatch(3); BufferingHttpClientHandler handler = new BufferingHttpClientHandler( httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new SSLClientIOEventDispatch( handler, sslcontext, params); Thread t = new Thread(new Runnable() { public void run() { 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"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[3]; reqs[0] = ioReactor.connect( new InetSocketAddress("www.netscape.com", 443), null, new HttpHost("www.netscape.com", 443), new MySessionRequestCallback(requestCount)); reqs[1] = ioReactor.connect( new InetSocketAddress("www.verisign.com", 443), null, new HttpHost("www.verisign.com", 443), new MySessionRequestCallback(requestCount)); reqs[2] = ioReactor.connect( new InetSocketAddress("www.yahoo.com", 443), null, new HttpHost("www.yahoo.com", 443), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); } static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler { private final static String REQUEST_SENT = "request-sent"; private final static String RESPONSE_RECEIVED = "response-received"; private final CountDownLatch requestCount; public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void initalizeContext(final HttpContext context, final Object attachment) { HttpHost targetHost = (HttpHost) attachment; context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); } public void finalizeContext(final HttpContext context) { Object flag = context.getAttribute(RESPONSE_RECEIVED); if (flag == null) { // Signal completion of the request execution this.requestCount.countDown(); } } public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object token = context.getAttribute(REQUEST_SENT); if (token == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } } public void handleResponse(final HttpResponse response, final HttpContext context) { HttpEntity entity = response.getEntity(); try { String content = EntityUtils.toString(entity); System.out.println("--------------"); System.out.println(response.getStatusLine()); System.out.println("--------------"); System.out.println("Document length: " + content.length()); System.out.println("--------------"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE); // Signal completion of the request execution this.requestCount.countDown(); } } static class MySessionRequestCallback implements SessionRequestCallback { private final CountDownLatch requestCount; public MySessionRequestCallback(final CountDownLatch requestCount) { super(); this.requestCount = requestCount; } public void cancelled(final SessionRequest request) { System.out.println("Connect request cancelled: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void completed(final SessionRequest request) { } public void failed(final SessionRequest request) { System.out.println("Connect request failed: " + request.getRemoteAddress()); this.requestCount.countDown(); } public void timeout(final SessionRequest request) { System.out.println("Connect request timed out: " + request.getRemoteAddress()); this.requestCount.countDown(); } } 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
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.examples.nio; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.URLDecoder; import java.nio.channels.FileChannel; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentDecoderChannel; import org.apache.http.nio.FileContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate; import org.apache.http.nio.entity.ContentListener; import org.apache.http.nio.entity.NFileEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.AsyncNHttpServiceHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerResolver; import org.apache.http.nio.protocol.SimpleNHttpRequestHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; /** * Basic, yet fully functional and spec compliant, HTTP/1.1 file server based on the non-blocking * I/O model. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP file server. * * */ public class NHttpFileServer { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } boolean useFileChannels = true; if (args.length >= 2) { String s = args[1]; if (s.equalsIgnoreCase("disableFileChannels")) { useFileChannels = false; } } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); final HttpFileHandler filehandler = new HttpFileHandler(args[0], useFileChannels); NHttpRequestHandlerResolver resolver = new NHttpRequestHandlerResolver() { public NHttpRequestHandler lookup(String requestURI) { return filehandler; } }; handler.setHandlerResolver(resolver); // Provide an event logger handler.setEventListener(new EventLogger()); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); try { ioReactor.listen(new InetSocketAddress(8080)); ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } static class HttpFileHandler extends SimpleNHttpRequestHandler { private final String docRoot; private final boolean useFileChannels; public HttpFileHandler(final String docRoot, boolean useFileChannels) { this.docRoot = docRoot; this.useFileChannels = useFileChannels; } public ConsumingNHttpEntity entityRequest( final HttpEntityEnclosingRequest request, final HttpContext context) throws HttpException, IOException { return new ConsumingNHttpEntityTemplate( request.getEntity(), new FileWriteListener(useFileChannels)); } @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String target = request.getRequestLine().getUri(); final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); NStringEntity entity = new NStringEntity( "<html><body><h1>File" + file.getPath() + " not found</h1></body></html>", "UTF-8"); entity.setContentType("text/html; charset=UTF-8"); response.setEntity(entity); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); NStringEntity entity = new NStringEntity( "<html><body><h1>Access denied</h1></body></html>", "UTF-8"); entity.setContentType("text/html; charset=UTF-8"); response.setEntity(entity); } else { response.setStatusCode(HttpStatus.SC_OK); NFileEntity entity = new NFileEntity(file, "text/html", useFileChannels); response.setEntity(entity); } } } static class FileWriteListener implements ContentListener { private final File file; private final FileOutputStream outputFile; private final FileChannel fileChannel; private final boolean useFileChannels; private long idx = 0; public FileWriteListener(boolean useFileChannels) throws IOException { this.file = File.createTempFile("tmp", ".tmp", null); this.outputFile = new FileOutputStream(file, true); this.fileChannel = outputFile.getChannel(); this.useFileChannels = useFileChannels; } public void contentAvailable(ContentDecoder decoder, IOControl ioctrl) throws IOException { long transferred; if(useFileChannels && decoder instanceof FileContentDecoder) { transferred = ((FileContentDecoder) decoder).transfer( fileChannel, idx, Long.MAX_VALUE); } else { transferred = fileChannel.transferFrom( new ContentDecoderChannel(decoder), idx, Integer.MAX_VALUE); } if(transferred > 0) idx += transferred; } public void finished() { try { outputFile.close(); } catch(IOException ignored) {} try { fileChannel.close(); } catch(IOException ignored) {} } } static class EventLogger implements EventListener { public void connectionOpen(final NHttpConnection conn) { System.out.println("Connection open: " + conn); } public void connectionTimeout(final NHttpConnection conn) { System.out.println("Connection timed out: " + conn); } public void connectionClosed(final NHttpConnection conn) { System.out.println("Connection closed: " + conn); } public void fatalIOException(final IOException ex, final NHttpConnection conn) { System.err.println("I/O error: " + ex.getMessage()); } public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) { System.err.println("HTTP error: " + ex.getMessage()); } } }
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.net.InetSocketAddress; import java.net.URLDecoder; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.entity.NFileEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.protocol.BufferingHttpServiceHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.EntityUtils; /** * Basic, yet fully functional and spec compliant, HTTP/1.1 server based on the non-blocking * I/O model. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP server. * * */ public class NHttpServer { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler(args[0])); handler.setHandlerResolver(reqistry); // Provide an event logger handler.setEventListener(new EventLogger()); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params); try { ioReactor.listen(new InetSocketAddress(8080)); ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } static class HttpFileHandler implements HttpRequestHandler { private final String docRoot; public HttpFileHandler(final String docRoot) { super(); this.docRoot = docRoot; } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); System.out.println("Incoming entity content (bytes): " + entityContent.length); } String target = request.getRequestLine().getUri(); final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); NStringEntity entity = new NStringEntity( "<html><body><h1>File" + file.getPath() + " not found</h1></body></html>", "UTF-8"); entity.setContentType("text/html; charset=UTF-8"); response.setEntity(entity); System.out.println("File " + file.getPath() + " not found"); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); NStringEntity entity = new NStringEntity( "<html><body><h1>Access denied</h1></body></html>", "UTF-8"); entity.setContentType("text/html; charset=UTF-8"); response.setEntity(entity); System.out.println("Cannot read file " + file.getPath()); } else { response.setStatusCode(HttpStatus.SC_OK); NFileEntity body = new NFileEntity(file, "text/html"); response.setEntity(body); System.out.println("Serving file " + file.getPath()); } } } static class EventLogger implements EventListener { public void connectionOpen(final NHttpConnection conn) { System.out.println("Connection open: " + conn); } public void connectionTimeout(final NHttpConnection conn) { System.out.println("Connection timed out: " + conn); } public void connectionClosed(final NHttpConnection conn) { System.out.println("Connection closed: " + conn); } public void fatalIOException(final IOException ex, final NHttpConnection conn) { System.err.println("I/O error: " + ex.getMessage()); } public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) { System.err.println("HTTP error: " + ex.getMessage()); } } }
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.ConnectionReuseStrategy; import org.apache.http.HttpConnection; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.ProtocolVersion; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; /** * Rudimentary HTTP/1.1 reverse proxy based on the non-blocking I/O model. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy. * * */ public class NHttpReverseProxy { public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: NHttpReverseProxy <hostname> [port]"); System.exit(1); } String hostname = args[0]; int port = 80; if (args.length > 1) { port = Integer.parseInt(args[1]); } // Target host HttpHost targetHost = new HttpHost(hostname, port); HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1") .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor connectingIOReactor = new DefaultConnectingIOReactor( 1, params); final ListeningIOReactor listeningIOReactor = new DefaultListeningIOReactor( 1, params); // Set up HTTP protocol processor for incoming connections HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Set up HTTP protocol processor for outgoing connections HttpProcessor outhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); NHttpClientHandler connectingHandler = new ConnectingHandler( inhttpproc, new DefaultConnectionReuseStrategy(), params); NHttpServiceHandler listeningHandler = new ListeningHandler( targetHost, connectingIOReactor, outhttpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); final IOEventDispatch connectingEventDispatch = new DefaultClientIOEventDispatch( connectingHandler, params); final IOEventDispatch listeningEventDispatch = new DefaultServerIOEventDispatch( listeningHandler, params); Thread t = new Thread(new Runnable() { public void run() { try { connectingIOReactor.execute(connectingEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } }); t.start(); try { listeningIOReactor.listen(new InetSocketAddress(8888)); listeningIOReactor.execute(listeningEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } static class ListeningHandler implements NHttpServiceHandler { private final HttpHost targetHost; private final ConnectingIOReactor connectingIOReactor; private final HttpProcessor httpProcessor; private final HttpResponseFactory responseFactory; private final ConnectionReuseStrategy connStrategy; private final HttpParams params; public ListeningHandler( final HttpHost targetHost, final ConnectingIOReactor connectingIOReactor, final HttpProcessor httpProcessor, final HttpResponseFactory responseFactory, final ConnectionReuseStrategy connStrategy, final HttpParams params) { super(); this.targetHost = targetHost; this.connectingIOReactor = connectingIOReactor; this.httpProcessor = httpProcessor; this.connStrategy = connStrategy; this.responseFactory = responseFactory; this.params = params; } public void connected(final NHttpServerConnection conn) { System.out.println(conn + " [client->proxy] conn open"); ProxyTask proxyTask = new ProxyTask(); synchronized (proxyTask) { // Initialize connection state proxyTask.setTarget(this.targetHost); proxyTask.setClientIOControl(conn); proxyTask.setClientState(ConnState.CONNECTED); HttpContext context = conn.getContext(); context.setAttribute(ProxyTask.ATTRIB, proxyTask); InetSocketAddress address = new InetSocketAddress( this.targetHost.getHostName(), this.targetHost.getPort()); this.connectingIOReactor.connect( address, null, proxyTask, null); } } public void requestReceived(final NHttpServerConnection conn) { System.out.println(conn + " [client->proxy] request received"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getClientState(); if (connState != ConnState.IDLE && connState != ConnState.CONNECTED) { throw new IllegalStateException("Illegal client connection state: " + connState); } try { HttpRequest request = conn.getHttpRequest(); System.out.println(conn + " [client->proxy] >> " + request.getRequestLine()); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } // Update connection state proxyTask.setRequest(request); proxyTask.setClientState(ConnState.REQUEST_RECEIVED); // See if the client expects a 100-Continue if (request instanceof HttpEntityEnclosingRequest) { if (((HttpEntityEnclosingRequest) request).expectContinue()) { HttpResponse ack = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); conn.submitResponse(ack); } } else { // No request content expected. Suspend client input conn.suspendInput(); } // If there is already a connection to the origin server // make sure origin output is active if (proxyTask.getOriginIOControl() != null) { proxyTask.getOriginIOControl().requestOutput(); } } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { System.out.println(conn + " [client->proxy] input ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getClientState(); if (connState != ConnState.REQUEST_RECEIVED && connState != ConnState.REQUEST_BODY_STREAM) { throw new IllegalStateException("Illegal client connection state: " + connState); } try { ByteBuffer dst = proxyTask.getInBuffer(); int bytesRead = decoder.read(dst); System.out.println(conn + " [client->proxy] " + bytesRead + " bytes read"); System.out.println(conn + " [client->proxy] " + decoder); if (!dst.hasRemaining()) { // Input buffer is full. Suspend client input // until the origin handler frees up some space in the buffer conn.suspendInput(); } // If there is some content in the input buffer make sure origin // output is active if (dst.position() > 0) { if (proxyTask.getOriginIOControl() != null) { proxyTask.getOriginIOControl().requestOutput(); } } if (decoder.isCompleted()) { System.out.println(conn + " [client->proxy] request body received"); // Update connection state proxyTask.setClientState(ConnState.REQUEST_BODY_DONE); // Suspend client input conn.suspendInput(); } else { proxyTask.setClientState(ConnState.REQUEST_BODY_STREAM); } } catch (IOException ex) { shutdownConnection(conn); } } } public void responseReady(final NHttpServerConnection conn) { System.out.println(conn + " [client<-proxy] response ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getClientState(); if (connState == ConnState.IDLE) { // Response not available return; } if (connState != ConnState.REQUEST_RECEIVED && connState != ConnState.REQUEST_BODY_DONE) { throw new IllegalStateException("Illegal client connection state: " + connState); } try { HttpRequest request = proxyTask.getRequest(); HttpResponse response = proxyTask.getResponse(); if (response == null) { throw new IllegalStateException("HTTP request is null"); } // Remove hop-by-hop headers response.removeHeaders(HTTP.CONTENT_LEN); response.removeHeaders(HTTP.TRANSFER_ENCODING); response.removeHeaders(HTTP.CONN_DIRECTIVE); response.removeHeaders("Keep-Alive"); response.removeHeaders("Proxy-Authenticate"); response.removeHeaders("Proxy-Authorization"); response.removeHeaders("TE"); response.removeHeaders("Trailers"); response.removeHeaders("Upgrade"); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); // Close client connection if the connection to the target // is no longer active / open if (proxyTask.getOriginState().compareTo(ConnState.CLOSING) >= 0) { response.addHeader(HTTP.CONN_DIRECTIVE, "Close"); } // Pre-process HTTP request context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); this.httpProcessor.process(response, context); conn.submitResponse(response); proxyTask.setClientState(ConnState.RESPONSE_SENT); System.out.println(conn + " [client<-proxy] << " + response.getStatusLine()); if (!canResponseHaveBody(request, response)) { conn.resetInput(); if (!this.connStrategy.keepAlive(response, context)) { System.out.println(conn + " [client<-proxy] close connection"); proxyTask.setClientState(ConnState.CLOSING); conn.close(); } else { // Reset connection state proxyTask.reset(); conn.requestInput(); // Ready to deal with a new request } } } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } } private boolean canResponseHaveBody( final HttpRequest request, final HttpResponse response) { if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { System.out.println(conn + " [client<-proxy] output ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getClientState(); if (connState != ConnState.RESPONSE_SENT && connState != ConnState.RESPONSE_BODY_STREAM) { throw new IllegalStateException("Illegal client connection state: " + connState); } HttpResponse response = proxyTask.getResponse(); if (response == null) { throw new IllegalStateException("HTTP request is null"); } try { ByteBuffer src = proxyTask.getOutBuffer(); src.flip(); int bytesWritten = encoder.write(src); System.out.println(conn + " [client<-proxy] " + bytesWritten + " bytes written"); System.out.println(conn + " [client<-proxy] " + encoder); src.compact(); if (src.position() == 0) { if (proxyTask.getOriginState() == ConnState.RESPONSE_BODY_DONE) { encoder.complete(); } else { // Input output is empty. Wait until the origin handler // fills up the buffer conn.suspendOutput(); } } // Update connection state if (encoder.isCompleted()) { System.out.println(conn + " [proxy] response body sent"); proxyTask.setClientState(ConnState.RESPONSE_BODY_DONE); if (!this.connStrategy.keepAlive(response, context)) { System.out.println(conn + " [client<-proxy] close connection"); proxyTask.setClientState(ConnState.CLOSING); conn.close(); } else { // Reset connection state proxyTask.reset(); conn.requestInput(); // Ready to deal with a new request } } else { proxyTask.setClientState(ConnState.RESPONSE_BODY_STREAM); // Make sure origin input is active proxyTask.getOriginIOControl().requestInput(); } } catch (IOException ex) { shutdownConnection(conn); } } } public void closed(final NHttpServerConnection conn) { System.out.println(conn + " [client->proxy] conn closed"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); if (proxyTask != null) { synchronized (proxyTask) { proxyTask.setClientState(ConnState.CLOSED); } } } public void exception(final NHttpServerConnection conn, final HttpException httpex) { System.out.println(conn + " [client->proxy] HTTP error: " + httpex.getMessage()); if (conn.isResponseSubmitted()) { shutdownConnection(conn); return; } HttpContext context = conn.getContext(); try { HttpResponse response = this.responseFactory.newHttpResponse( HttpVersion.HTTP_1_0, HttpStatus.SC_BAD_REQUEST, context); response.setParams( new DefaultedHttpParams(this.params, response.getParams())); response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); // Pre-process HTTP request context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_REQUEST, null); this.httpProcessor.process(response, context); conn.submitResponse(response); conn.close(); } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } public void exception(final NHttpServerConnection conn, final IOException ex) { shutdownConnection(conn); System.out.println(conn + " [client->proxy] I/O error: " + ex.getMessage()); } public void timeout(final NHttpServerConnection conn) { System.out.println(conn + " [client->proxy] timeout"); closeConnection(conn); } private void shutdownConnection(final NHttpConnection conn) { try { conn.shutdown(); } catch (IOException ignore) { } } private void closeConnection(final NHttpConnection conn) { try { conn.close(); } catch (IOException ignore) { } } } static class ConnectingHandler implements NHttpClientHandler { private final HttpProcessor httpProcessor; private final ConnectionReuseStrategy connStrategy; private final HttpParams params; public ConnectingHandler( final HttpProcessor httpProcessor, final ConnectionReuseStrategy connStrategy, final HttpParams params) { super(); this.httpProcessor = httpProcessor; this.connStrategy = connStrategy; this.params = params; } public void connected(final NHttpClientConnection conn, final Object attachment) { System.out.println(conn + " [proxy->origin] conn open"); // The shared state object is expected to be passed as an attachment ProxyTask proxyTask = (ProxyTask) attachment; synchronized (proxyTask) { ConnState connState = proxyTask.getOriginState(); if (connState != ConnState.IDLE) { throw new IllegalStateException("Illegal target connection state: " + connState); } // Set origin IO control handle proxyTask.setOriginIOControl(conn); // Store the state object in the context HttpContext context = conn.getContext(); context.setAttribute(ProxyTask.ATTRIB, proxyTask); // Update connection state proxyTask.setOriginState(ConnState.CONNECTED); if (proxyTask.getRequest() != null) { conn.requestOutput(); } } } public void requestReady(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] request ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getOriginState(); if (connState == ConnState.REQUEST_SENT || connState == ConnState.REQUEST_BODY_DONE) { // Request sent but no response available yet return; } if (connState != ConnState.IDLE && connState != ConnState.CONNECTED) { throw new IllegalStateException("Illegal target connection state: " + connState); } HttpRequest request = proxyTask.getRequest(); if (request == null) { throw new IllegalStateException("HTTP request is null"); } // Remove hop-by-hop headers request.removeHeaders(HTTP.CONTENT_LEN); request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONN_DIRECTIVE); request.removeHeaders("Keep-Alive"); request.removeHeaders("Proxy-Authenticate"); request.removeHeaders("Proxy-Authorization"); request.removeHeaders("TE"); request.removeHeaders("Trailers"); request.removeHeaders("Upgrade"); // Remove host header request.removeHeaders(HTTP.TARGET_HOST); HttpHost targetHost = proxyTask.getTarget(); try { request.setParams( new DefaultedHttpParams(request.getParams(), this.params)); // Pre-process HTTP request context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); this.httpProcessor.process(request, context); // and send it to the origin server conn.submitRequest(request); // Update connection state proxyTask.setOriginState(ConnState.REQUEST_SENT); System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString()); } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { System.out.println(conn + " [proxy->origin] output ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getOriginState(); if (connState != ConnState.REQUEST_SENT && connState != ConnState.REQUEST_BODY_STREAM) { throw new IllegalStateException("Illegal target connection state: " + connState); } try { ByteBuffer src = proxyTask.getInBuffer(); src.flip(); int bytesWritten = encoder.write(src); System.out.println(conn + " [proxy->origin] " + bytesWritten + " bytes written"); System.out.println(conn + " [proxy->origin] " + encoder); src.compact(); if (src.position() == 0) { if (proxyTask.getClientState() == ConnState.REQUEST_BODY_DONE) { encoder.complete(); } else { // Input buffer is empty. Wait until the client fills up // the buffer conn.suspendOutput(); } } // Update connection state if (encoder.isCompleted()) { System.out.println(conn + " [proxy->origin] request body sent"); proxyTask.setOriginState(ConnState.REQUEST_BODY_DONE); } else { proxyTask.setOriginState(ConnState.REQUEST_BODY_STREAM); // Make sure client input is active proxyTask.getClientIOControl().requestInput(); } } catch (IOException ex) { shutdownConnection(conn); } } } public void responseReceived(final NHttpClientConnection conn) { System.out.println(conn + " [proxy<-origin] response received"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getOriginState(); if (connState != ConnState.REQUEST_SENT && connState != ConnState.REQUEST_BODY_DONE) { throw new IllegalStateException("Illegal target connection state: " + connState); } HttpResponse response = conn.getHttpResponse(); HttpRequest request = proxyTask.getRequest(); System.out.println(conn + " [proxy<-origin] << " + response.getStatusLine()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK) { // Ignore 1xx response return; } try { // Update connection state proxyTask.setResponse(response); proxyTask.setOriginState(ConnState.RESPONSE_RECEIVED); if (!canResponseHaveBody(request, response)) { conn.resetInput(); if (!this.connStrategy.keepAlive(response, context)) { System.out.println(conn + " [proxy<-origin] close connection"); proxyTask.setOriginState(ConnState.CLOSING); conn.close(); } } // Make sure client output is active proxyTask.getClientIOControl().requestOutput(); } catch (IOException ex) { shutdownConnection(conn); } } } private boolean canResponseHaveBody( final HttpRequest request, final HttpResponse response) { if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { System.out.println(conn + " [proxy<-origin] input ready"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); synchronized (proxyTask) { ConnState connState = proxyTask.getOriginState(); if (connState != ConnState.RESPONSE_RECEIVED && connState != ConnState.RESPONSE_BODY_STREAM) { throw new IllegalStateException("Illegal target connection state: " + connState); } HttpResponse response = proxyTask.getResponse(); try { ByteBuffer dst = proxyTask.getOutBuffer(); int bytesRead = decoder.read(dst); System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read"); System.out.println(conn + " [proxy<-origin] " + decoder); if (!dst.hasRemaining()) { // Output buffer is full. Suspend origin input until // the client handler frees up some space in the buffer conn.suspendInput(); } // If there is some content in the buffer make sure client output // is active if (dst.position() > 0) { proxyTask.getClientIOControl().requestOutput(); } if (decoder.isCompleted()) { System.out.println(conn + " [proxy<-origin] response body received"); proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE); if (!this.connStrategy.keepAlive(response, context)) { System.out.println(conn + " [proxy<-origin] close connection"); proxyTask.setOriginState(ConnState.CLOSING); conn.close(); } } else { proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM); } } catch (IOException ex) { shutdownConnection(conn); } } } public void closed(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] conn closed"); HttpContext context = conn.getContext(); ProxyTask proxyTask = (ProxyTask) context.getAttribute(ProxyTask.ATTRIB); if (proxyTask != null) { synchronized (proxyTask) { proxyTask.setOriginState(ConnState.CLOSED); } } } public void exception(final NHttpClientConnection conn, final HttpException ex) { shutdownConnection(conn); System.out.println(conn + " [proxy->origin] HTTP error: " + ex.getMessage()); } public void exception(final NHttpClientConnection conn, final IOException ex) { shutdownConnection(conn); System.out.println(conn + " [proxy->origin] I/O error: " + ex.getMessage()); } public void timeout(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] timeout"); closeConnection(conn); } private void shutdownConnection(final HttpConnection conn) { try { conn.shutdown(); } catch (IOException ignore) { } } private void closeConnection(final HttpConnection conn) { try { conn.shutdown(); } catch (IOException ignore) { } } } enum ConnState { IDLE, CONNECTED, REQUEST_RECEIVED, REQUEST_SENT, REQUEST_BODY_STREAM, REQUEST_BODY_DONE, RESPONSE_RECEIVED, RESPONSE_SENT, RESPONSE_BODY_STREAM, RESPONSE_BODY_DONE, CLOSING, CLOSED } static class ProxyTask { public static final String ATTRIB = "nhttp.proxy-task"; private final ByteBuffer inBuffer; private final ByteBuffer outBuffer; private HttpHost target; private IOControl originIOControl; private IOControl clientIOControl; private ConnState originState; private ConnState clientState; private HttpRequest request; private HttpResponse response; public ProxyTask() { super(); this.originState = ConnState.IDLE; this.clientState = ConnState.IDLE; this.inBuffer = ByteBuffer.allocateDirect(10240); this.outBuffer = ByteBuffer.allocateDirect(10240); } public ByteBuffer getInBuffer() { return this.inBuffer; } public ByteBuffer getOutBuffer() { return this.outBuffer; } public HttpHost getTarget() { return this.target; } public void setTarget(final HttpHost target) { this.target = target; } public HttpRequest getRequest() { return this.request; } public void setRequest(final HttpRequest request) { this.request = request; } public HttpResponse getResponse() { return this.response; } public void setResponse(final HttpResponse response) { this.response = response; } public IOControl getClientIOControl() { return this.clientIOControl; } public void setClientIOControl(final IOControl clientIOControl) { this.clientIOControl = clientIOControl; } public IOControl getOriginIOControl() { return this.originIOControl; } public void setOriginIOControl(final IOControl originIOControl) { this.originIOControl = originIOControl; } public ConnState getOriginState() { return this.originState; } public void setOriginState(final ConnState state) { this.originState = state; } public ConnState getClientState() { return this.clientState; } public void setClientState(final ConnState state) { this.clientState = state; } public void reset() { this.inBuffer.clear(); this.outBuffer.clear(); this.originState = ConnState.IDLE; this.clientState = ConnState.IDLE; this.request = null; this.response = null; } public void shutdown() { if (this.clientIOControl != null) { try { this.clientIOControl.shutdown(); } catch (IOException ignore) { } } if (this.originIOControl != null) { try { this.originIOControl.shutdown(); } catch (IOException ignore) { } } } } }
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.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.message.BasicHttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.BufferingHttpClientHandler; import org.apache.http.nio.protocol.EventListener; import org.apache.http.nio.protocol.HttpRequestExecutionHandler; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.nio.reactor.SessionRequestCallback; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Example of a very simple asynchronous connection manager that maintains a pool of persistent * connections to one target host. * <p> * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. * It is NOT intended to demonstrate the most efficient way of building an HTTP client. * * */ public class NHttpClientConnManagement { public static void main(String[] args) throws Exception { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()}); // Set up protocol handler BufferingHttpClientHandler protocolHandler = new BufferingHttpClientHandler( httpproc, new MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(), params); protocolHandler.setEventListener(new EventLogger()); // Limit the total maximum of concurrent connections to 5 int maxTotalConnections = 5; // Use the connection manager to maintain a pool of connections to localhost:8080 final AsyncConnectionManager connMgr = new AsyncConnectionManager( new HttpHost("localhost", 8080), maxTotalConnections, protocolHandler, params); // Start the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { connMgr.execute(); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("I/O reactor terminated"); } }); t.start(); // Submit 50 requests using maximum 5 concurrent connections Queue<RequestHandle> queue = new LinkedList<RequestHandle>(); for (int i = 0; i < 50; i++) { AsyncConnectionRequest connRequest = connMgr.requestConnection(); connRequest.waitFor(); NHttpClientConnection conn = connRequest.getConnection(); if (conn == null) { System.err.println("Failed to obtain connection"); break; } HttpContext context = conn.getContext(); BasicHttpRequest httpget = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); RequestHandle handle = new RequestHandle(connMgr, conn); context.setAttribute("request", httpget); context.setAttribute("request-handle", handle); queue.add(handle); conn.requestOutput(); } // Wait until all requests have been completed while (!queue.isEmpty()) { RequestHandle handle = queue.remove(); handle.waitFor(); } // Give the I/O reactor 10 sec to shut down connMgr.shutdown(10000); System.out.println("Done"); } static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler { public MyHttpRequestExecutionHandler() { super(); } public void initalizeContext(final HttpContext context, final Object attachment) { } public void finalizeContext(final HttpContext context) { RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle"); if (handle != null) { handle.cancel(); } } public HttpRequest submitRequest(final HttpContext context) { HttpRequest request = (HttpRequest) context.removeAttribute("request"); return request; } public void handleResponse(final HttpResponse response, final HttpContext context) { HttpEntity entity = response.getEntity(); try { String content = EntityUtils.toString(entity); System.out.println("--------------"); System.out.println(response.getStatusLine()); System.out.println("--------------"); System.out.println("Document length: " + content.length()); System.out.println("--------------"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } RequestHandle handle = (RequestHandle) context.removeAttribute("request-handle"); if (handle != null) { handle.completed(); } } } static class AsyncConnectionRequest { private volatile boolean completed; private volatile NHttpClientConnection conn; public AsyncConnectionRequest() { super(); } public boolean isCompleted() { return this.completed; } public void setConnection(NHttpClientConnection conn) { if (this.completed) { return; } this.completed = true; synchronized (this) { this.conn = conn; notifyAll(); } } public NHttpClientConnection getConnection() { return this.conn; } public void cancel() { if (this.completed) { return; } this.completed = true; synchronized (this) { notifyAll(); } } public void waitFor() throws InterruptedException { if (this.completed) { return; } synchronized (this) { while (!this.completed) { wait(); } } } } static class AsyncConnectionManager { private final HttpHost target; private final int maxConnections; private final NHttpClientHandler handler; private final HttpParams params; private final ConnectingIOReactor ioreactor; private final Object lock; private final Set<NHttpClientConnection> allConns; private final Queue<NHttpClientConnection> availableConns; private final Queue<AsyncConnectionRequest> pendingRequests; private volatile boolean shutdown; public AsyncConnectionManager( HttpHost target, int maxConnections, NHttpClientHandler handler, HttpParams params) throws IOReactorException { super(); this.target = target; this.maxConnections = maxConnections; this.handler = handler; this.params = params; this.lock = new Object(); this.allConns = new HashSet<NHttpClientConnection>(); this.availableConns = new LinkedList<NHttpClientConnection>(); this.pendingRequests = new LinkedList<AsyncConnectionRequest>(); this.ioreactor = new DefaultConnectingIOReactor(2, params); } public void execute() throws IOException { IOEventDispatch dispatch = new DefaultClientIOEventDispatch( new ManagedClientHandler(this.handler, this), this.params); this.ioreactor.execute(dispatch); } public void shutdown(long waitMs) throws IOException { synchronized (this.lock) { if (!this.shutdown) { this.shutdown = true; while (!this.pendingRequests.isEmpty()) { AsyncConnectionRequest request = this.pendingRequests.remove(); request.cancel(); } this.availableConns.clear(); this.allConns.clear(); } } this.ioreactor.shutdown(waitMs); } void addConnection(NHttpClientConnection conn) { if (conn == null) { return; } if (this.shutdown) { return; } synchronized (this.lock) { this.allConns.add(conn); } } void removeConnection(NHttpClientConnection conn) { if (conn == null) { return; } if (this.shutdown) { return; } synchronized (this.lock) { if (this.allConns.remove(conn)) { this.availableConns.remove(conn); } processRequests(); } } public AsyncConnectionRequest requestConnection() { if (this.shutdown) { throw new IllegalStateException("Connection manager has been shut down"); } AsyncConnectionRequest request = new AsyncConnectionRequest(); synchronized (this.lock) { while (!this.availableConns.isEmpty()) { NHttpClientConnection conn = this.availableConns.remove(); if (conn.isOpen()) { System.out.println("Re-using persistent connection"); request.setConnection(conn); break; } else { this.allConns.remove(conn); } } if (!request.isCompleted()) { this.pendingRequests.add(request); processRequests(); } } return request; } public void releaseConnection(NHttpClientConnection conn) { if (conn == null) { return; } if (this.shutdown) { return; } synchronized (this.lock) { if (this.allConns.contains(conn)) { if (conn.isOpen()) { conn.setSocketTimeout(0); AsyncConnectionRequest request = this.pendingRequests.poll(); if (request != null) { System.out.println("Re-using persistent connection"); request.setConnection(conn); } else { this.availableConns.add(conn); } } else { this.allConns.remove(conn); processRequests(); } } } } private void processRequests() { while (this.allConns.size() < this.maxConnections) { AsyncConnectionRequest request = this.pendingRequests.poll(); if (request == null) { break; } InetSocketAddress address = new InetSocketAddress( this.target.getHostName(), this.target.getPort()); ConnRequestCallback callback = new ConnRequestCallback(request); System.out.println("Opening new connection"); this.ioreactor.connect(address, null, request, callback); } } } static class ManagedClientHandler implements NHttpClientHandler { private final NHttpClientHandler handler; private final AsyncConnectionManager connMgr; public ManagedClientHandler(NHttpClientHandler handler, AsyncConnectionManager connMgr) { super(); this.handler = handler; this.connMgr = connMgr; } public void connected(NHttpClientConnection conn, Object attachment) { AsyncConnectionRequest request = (AsyncConnectionRequest) attachment; this.handler.connected(conn, attachment); this.connMgr.addConnection(conn); request.setConnection(conn); } public void closed(NHttpClientConnection conn) { this.connMgr.removeConnection(conn); this.handler.closed(conn); } public void requestReady(NHttpClientConnection conn) { this.handler.requestReady(conn); } public void outputReady(NHttpClientConnection conn, ContentEncoder encoder) { this.handler.outputReady(conn, encoder); } public void responseReceived(NHttpClientConnection conn) { this.handler.responseReceived(conn); } public void inputReady(NHttpClientConnection conn, ContentDecoder decoder) { this.handler.inputReady(conn, decoder); } public void exception(NHttpClientConnection conn, HttpException ex) { this.handler.exception(conn, ex); } public void exception(NHttpClientConnection conn, IOException ex) { this.handler.exception(conn, ex); } public void timeout(NHttpClientConnection conn) { this.handler.timeout(conn); } } static class RequestHandle { private final AsyncConnectionManager connMgr; private final NHttpClientConnection conn; private volatile boolean completed; public RequestHandle(AsyncConnectionManager connMgr, NHttpClientConnection conn) { super(); this.connMgr = connMgr; this.conn = conn; } public boolean isCompleted() { return this.completed; } public void completed() { if (this.completed) { return; } this.completed = true; this.connMgr.releaseConnection(this.conn); synchronized (this) { notifyAll(); } } public void cancel() { if (this.completed) { return; } this.completed = true; synchronized (this) { notifyAll(); } } public void waitFor() throws InterruptedException { if (this.completed) { return; } synchronized (this) { while (!this.completed) { wait(); } } } } static class ConnRequestCallback implements SessionRequestCallback { private final AsyncConnectionRequest request; ConnRequestCallback(AsyncConnectionRequest request) { super(); this.request = request; } public void completed(SessionRequest request) { System.out.println(request.getRemoteAddress() + " - request successful"); } public void cancelled(SessionRequest request) { System.out.println(request.getRemoteAddress() + " - request cancelled"); this.request.cancel(); } public void failed(SessionRequest request) { System.err.println(request.getRemoteAddress() + " - request failed"); IOException ex = request.getException(); if (ex != null) { ex.printStackTrace(); } this.request.cancel(); } public void timeout(SessionRequest request) { System.out.println(request.getRemoteAddress() + " - request timed out"); this.request.cancel(); } } static class EventLogger implements EventListener { public void connectionOpen(final NHttpConnection conn) { System.out.println("Connection open: " + conn); } public void connectionTimeout(final NHttpConnection conn) { System.out.println("Connection timed out: " + conn); } public void connectionClosed(final NHttpConnection conn) { System.out.println("Connection closed: " + conn); } public void fatalIOException(final IOException ex, final NHttpConnection conn) { System.err.println("I/O error: " + ex.getMessage()); } public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) { System.err.println("HTTP error: " + ex.getMessage()); } } }
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.protocol; import java.io.IOException; import java.util.Queue; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; abstract class RequestExecutionHandler implements NHttpRequestExecutionHandler, HttpRequestExecutionHandler { public void initalizeContext(final HttpContext context, final Object attachment) { context.setAttribute("queue", attachment); } protected abstract HttpRequest generateRequest(Job testjob); public HttpRequest submitRequest(final HttpContext context) { @SuppressWarnings("unchecked") Queue<Job> queue = (Queue<Job>) context.getAttribute("queue"); if (queue == null) { throw new IllegalStateException("Queue is null"); } Job testjob = queue.poll(); context.setAttribute("job", testjob); if (testjob != null) { return generateRequest(testjob); } else { return null; } } public ConsumingNHttpEntity responseEntity( final HttpResponse response, final HttpContext context) throws IOException { return new BufferingNHttpEntity(response.getEntity(), new HeapByteBufferAllocator()); } public void handleResponse(final HttpResponse response, final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob == null) { throw new IllegalStateException("TestJob is null"); } int statusCode = response.getStatusLine().getStatusCode(); String content = null; HttpEntity entity = response.getEntity(); if (entity != null) { try { content = EntityUtils.toString(entity); } catch (IOException ex) { content = "I/O exception: " + ex.getMessage(); } } testjob.setResult(statusCode, content); } public void finalizeContext(final HttpContext context) { Job testjob = (Job) context.removeAttribute("job"); if (testjob != null) { testjob.fail("Request failed"); } } }
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.protocol; 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.HttpStatus; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.NStringEntity; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; final class RequestHandler extends SimpleNHttpRequestHandler implements HttpRequestHandler { private final boolean chunking; RequestHandler() { this(false); } RequestHandler(boolean chunking) { super(); this.chunking = chunking; } public ConsumingNHttpEntity entityRequest( final HttpEntityEnclosingRequest request, final HttpContext context) { return new BufferingNHttpEntity( request.getEntity(), new HeapByteBufferAllocator()); } @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String content = null; if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { content = EntityUtils.toString(entity); } else { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); content = "Request entity not avaialble"; } } else { String s = request.getRequestLine().getUri(); int idx = s.indexOf('x'); if (idx == -1) { throw new HttpException("Unexpected request-URI format"); } String pattern = s.substring(0, idx); int count = Integer.parseInt(s.substring(idx + 1, s.length())); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < count; i++) { buffer.append(pattern); } content = buffer.toString(); } NStringEntity entity = new NStringEntity(content, "US-ASCII"); entity.setChunked(this.chunking); response.setEntity(entity); } }
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.protocol; import java.util.Random; public class Job { private static final Random RND = new Random(); private static final String TEST_CHARS = "0123456789ABCDEF"; private final int count; private final String pattern; private volatile boolean completed; private volatile int statusCode; private volatile String result; private volatile String failureMessage; private volatile Exception ex; public Job(int maxCount) { super(); this.count = RND.nextInt(maxCount - 1) + 1; StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 5; i++) { char rndchar = TEST_CHARS.charAt(RND.nextInt(TEST_CHARS.length() - 1)); buffer.append(rndchar); } this.pattern = buffer.toString(); } public Job() { this(1000); } public Job(final String pattern, int count) { super(); this.count = count; this.pattern = pattern; } public int getCount() { return this.count; } public String getPattern() { return this.pattern; } public String getExpected() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < this.count; i++) { buffer.append(this.pattern); } return buffer.toString(); } public int getStatusCode() { return this.statusCode; } public String getResult() { return this.result; } public boolean isSuccessful() { return this.result != null; } public String getFailureMessage() { return this.failureMessage; } public Exception getException() { return this.ex; } public boolean isCompleted() { return this.completed; } public synchronized void setResult(int statusCode, final String result) { if (this.completed) { return; } this.completed = true; this.statusCode = statusCode; this.result = result; notifyAll(); } public synchronized void fail(final String message, final Exception ex) { if (this.completed) { return; } this.completed = true; this.result = null; this.failureMessage = message; this.ex = ex; notifyAll(); } public void fail(final String message) { fail(message, null); } public synchronized void waitFor() throws InterruptedException { while (!this.completed) { wait(); } } }
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; public class OoopsieRuntimeException extends RuntimeException { private static final long serialVersionUID = 662807254163212266L; public OoopsieRuntimeException() { super("Ooopsie!!!"); } }
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; import java.io.IOException; import junit.framework.TestCase; import org.apache.http.mockup.HttpSSLClient; import org.apache.http.mockup.HttpSSLServer; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; /** * Base class for all HttpCore NIO tests */ public class HttpCoreNIOSSLTestBase extends TestCase { public HttpCoreNIOSSLTestBase(String testName) { super(testName); } protected HttpSSLServer server; protected HttpSSLClient client; @Override protected void setUp() throws Exception { HttpParams serverParams = new SyncBasicHttpParams(); serverParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1"); this.server = new HttpSSLServer(serverParams); this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler()); HttpParams clientParams = new SyncBasicHttpParams(); clientParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1"); this.client = new HttpSSLClient(clientParams); this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler()); } @Override protected void tearDown() { try { this.client.shutdown(); } catch (IOException ex) { ex.printStackTrace(System.out); } try { this.server.shutdown(); } catch (IOException ex) { ex.printStackTrace(System.out); } } }
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.mockup; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.nio.NHttpConnection; import org.apache.http.nio.protocol.EventListener; public class SimpleEventListener implements EventListener { public SimpleEventListener() { super(); } public void connectionOpen(final NHttpConnection conn) { } public void connectionTimeout(final NHttpConnection conn) { System.out.println("Connection timed out"); } public void connectionClosed(final NHttpConnection conn) { } public void fatalIOException(final IOException ex, final NHttpConnection conn) { ex.printStackTrace(System.out); } public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) { ex.printStackTrace(System.out); } }
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.mockup; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.params.HttpParams; public class HttpSSLClient { private final SSLContext sslcontext; private final DefaultConnectingIOReactor ioReactor; private final HttpParams params; private volatile IOReactorThread thread; public HttpSSLClient(final HttpParams params) throws Exception { super(); this.params = params; this.sslcontext = createSSLContext(); this.ioReactor = new DefaultConnectingIOReactor(2, this.params); } private TrustManagerFactory createTrustManagerFactory() throws NoSuchAlgorithmException { String algo = TrustManagerFactory.getDefaultAlgorithm(); try { return TrustManagerFactory.getInstance(algo); } catch (NoSuchAlgorithmException ex) { return TrustManagerFactory.getInstance("SunX509"); } } protected SSLContext createSSLContext() throws Exception { ClassLoader cl = getClass().getClassLoader(); URL url = cl.getResource("test.keystore"); KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "nopassword".toCharArray()); TrustManagerFactory tmfactory = createTrustManagerFactory(); tmfactory.init(keystore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, trustmanagers, null); return sslcontext; } public HttpParams getParams() { return this.params; } public IOReactorStatus getStatus() { return this.ioReactor.getStatus(); } public List<ExceptionEvent> getAuditLog() { return this.ioReactor.getAuditLog(); } public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.ioReactor.setExceptionHandler(exceptionHandler); } protected IOEventDispatch createIOEventDispatch( final NHttpClientHandler clientHandler, final SSLContext sslcontext, final HttpParams params) { return new SSLClientIOEventDispatch(clientHandler, sslcontext, params); } private void execute(final NHttpClientHandler clientHandler) throws IOException { IOEventDispatch ioEventDispatch = createIOEventDispatch( clientHandler, this.sslcontext, this.params); this.ioReactor.execute(ioEventDispatch); } public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) { return this.ioReactor.connect(address, null, attachment, null); } public void start(final NHttpClientHandler clientHandler) { this.thread = new IOReactorThread(clientHandler); this.thread.start(); } public void join(long timeout) throws InterruptedException { if (this.thread != null) { this.thread.join(timeout); } } public Exception getException() { if (this.thread != null) { return this.thread.getException(); } else { return null; } } public void shutdown() throws IOException { this.ioReactor.shutdown(); try { if (this.thread != null) { this.thread.join(500); } } catch (InterruptedException ignore) { } } private class IOReactorThread extends Thread { private final NHttpClientHandler clientHandler; private volatile Exception ex; public IOReactorThread(final NHttpClientHandler clientHandler) { super(); this.clientHandler = clientHandler; } @Override public void run() { try { execute(this.clientHandler); } catch (Exception ex) { this.ex = ex; } } public Exception getException() { return this.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.mockup; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.params.HttpParams; /** * Trivial test server based on HttpCore NIO * */ public class HttpServerNio { private final DefaultListeningIOReactor ioReactor; private final HttpParams params; private volatile IOReactorThread thread; private ListenerEndpoint endpoint; public HttpServerNio(final HttpParams params) throws IOException { super(); this.ioReactor = new DefaultListeningIOReactor(2, params); this.params = params; } public HttpParams getParams() { return this.params; } public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.ioReactor.setExceptionHandler(exceptionHandler); } protected IOEventDispatch createIOEventDispatch( final NHttpServiceHandler serviceHandler, final HttpParams params) { return new DefaultServerIOEventDispatch(serviceHandler, params); } private void execute(final NHttpServiceHandler serviceHandler) throws IOException { IOEventDispatch ioEventDispatch = createIOEventDispatch( serviceHandler, this.params); this.ioReactor.execute(ioEventDispatch); } public ListenerEndpoint getListenerEndpoint() { return this.endpoint; } public void setEndpoint(ListenerEndpoint endpoint) { this.endpoint = endpoint; } public void start(final NHttpServiceHandler serviceHandler) { this.endpoint = this.ioReactor.listen(new InetSocketAddress(0)); this.thread = new IOReactorThread(serviceHandler); this.thread.start(); } public IOReactorStatus getStatus() { return this.ioReactor.getStatus(); } public List<ExceptionEvent> getAuditLog() { return this.ioReactor.getAuditLog(); } public void join(long timeout) throws InterruptedException { if (this.thread != null) { this.thread.join(timeout); } } public Exception getException() { if (this.thread != null) { return this.thread.getException(); } else { return null; } } public void shutdown() throws IOException { this.ioReactor.shutdown(); try { join(500); } catch (InterruptedException ignore) { } } private class IOReactorThread extends Thread { private final NHttpServiceHandler serviceHandler; private volatile Exception ex; public IOReactorThread(final NHttpServiceHandler serviceHandler) { super(); this.serviceHandler = serviceHandler; } @Override public void run() { try { execute(this.serviceHandler); } catch (Exception ex) { this.ex = ex; } } public Exception getException() { return this.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.mockup; import java.io.IOException; import java.net.InetSocketAddress; import java.util.List; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.SessionRequest; import org.apache.http.params.HttpParams; public class HttpClientNio { private final DefaultConnectingIOReactor ioReactor; private final HttpParams params; private volatile IOReactorThread thread; public HttpClientNio(final HttpParams params) throws IOException { super(); this.ioReactor = new DefaultConnectingIOReactor(2, params); this.params = params; } public HttpParams getParams() { return this.params; } public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.ioReactor.setExceptionHandler(exceptionHandler); } protected IOEventDispatch createIOEventDispatch( final NHttpClientHandler clientHandler, final HttpParams params) { return new DefaultClientIOEventDispatch(clientHandler, params); } private void execute(final NHttpClientHandler clientHandler) throws IOException { IOEventDispatch ioEventDispatch = createIOEventDispatch( clientHandler, this.params); this.ioReactor.execute(ioEventDispatch); } public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) { return this.ioReactor.connect(address, null, attachment, null); } public void start(final NHttpClientHandler clientHandler) { this.thread = new IOReactorThread(clientHandler); this.thread.start(); } public IOReactorStatus getStatus() { return this.ioReactor.getStatus(); } public List<ExceptionEvent> getAuditLog() { return this.ioReactor.getAuditLog(); } public void join(long timeout) throws InterruptedException { if (this.thread != null) { this.thread.join(timeout); } } public Exception getException() { if (this.thread != null) { return this.thread.getException(); } else { return null; } } public void shutdown() throws IOException { this.ioReactor.shutdown(); try { join(500); } catch (InterruptedException ignore) { } } private class IOReactorThread extends Thread { private final NHttpClientHandler clientHandler; private volatile Exception ex; public IOReactorThread(final NHttpClientHandler clientHandler) { super(); this.clientHandler = clientHandler; } @Override public void run() { try { execute(this.clientHandler); } catch (Exception ex) { this.ex = ex; } } public Exception getException() { return this.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.mockup; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.impl.nio.reactor.ExceptionEvent; import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOReactorExceptionHandler; import org.apache.http.nio.reactor.IOReactorStatus; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.params.HttpParams; /** * Trivial test server based on HttpCore NIO SSL * */ public class HttpSSLServer { private final SSLContext sslcontext; private final DefaultListeningIOReactor ioReactor; private final HttpParams params; private volatile IOReactorThread thread; private ListenerEndpoint endpoint; public HttpSSLServer(final HttpParams params) throws Exception { super(); this.params = params; this.sslcontext = createSSLContext(); this.ioReactor = new DefaultListeningIOReactor(2, this.params); } private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException { String algo = KeyManagerFactory.getDefaultAlgorithm(); try { return KeyManagerFactory.getInstance(algo); } catch (NoSuchAlgorithmException ex) { return KeyManagerFactory.getInstance("SunX509"); } } protected SSLContext createSSLContext() throws Exception { ClassLoader cl = getClass().getClassLoader(); URL url = cl.getResource("test.keystore"); KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "nopassword".toCharArray()); KeyManagerFactory kmfactory = createKeyManagerFactory(); kmfactory.init(keystore, "nopassword".toCharArray()); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); return sslcontext; } public HttpParams getParams() { return this.params; } public IOReactorStatus getStatus() { return this.ioReactor.getStatus(); } public List<ExceptionEvent> getAuditLog() { return this.ioReactor.getAuditLog(); } public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) { this.ioReactor.setExceptionHandler(exceptionHandler); } protected IOEventDispatch createIOEventDispatch( final NHttpServiceHandler serviceHandler, final SSLContext sslcontext, final HttpParams params) { return new SSLServerIOEventDispatch(serviceHandler, sslcontext, params); } private void execute(final NHttpServiceHandler serviceHandler) throws IOException { IOEventDispatch ioEventDispatch = createIOEventDispatch( serviceHandler, this.sslcontext, this.params); this.ioReactor.execute(ioEventDispatch); } public ListenerEndpoint getListenerEndpoint() { return this.endpoint; } public void start(final NHttpServiceHandler serviceHandler) { this.endpoint = this.ioReactor.listen(new InetSocketAddress(0)); this.thread = new IOReactorThread(serviceHandler); this.thread.start(); } public void join(long timeout) throws InterruptedException { if (this.thread != null) { this.thread.join(timeout); } } public Exception getException() { if (this.thread != null) { return this.thread.getException(); } else { return null; } } public void shutdown() throws IOException { this.ioReactor.shutdown(); try { if (this.thread != null) { this.thread.join(500); } } catch (InterruptedException ignore) { } } private class IOReactorThread extends Thread { private final NHttpServiceHandler serviceHandler; private volatile Exception ex; public IOReactorThread(final NHttpServiceHandler serviceHandler) { super(); this.serviceHandler = serviceHandler; } @Override public void run() { try { execute(this.serviceHandler); } catch (Exception ex) { this.ex = ex; } } public Exception getException() { return this.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.mockup; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.impl.nio.codecs.AbstractContentEncoder; import org.apache.http.nio.reactor.SessionOutputBuffer; public class MockupEncoder extends AbstractContentEncoder { // TODO? remove this field and the complete() and isCompleted() methods private boolean completed; public MockupEncoder( final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { super(channel, buffer, metrics); } @Override public boolean isCompleted() { return this.completed; } @Override public void complete() throws IOException { this.completed = true; } public int write(final ByteBuffer src) throws IOException { if (src == null) { return 0; } if (this.completed) { throw new IllegalStateException("Decoding process already completed"); } return this.channel.write(src); } }
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.mockup; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerResolver; public class SimpleNHttpRequestHandlerResolver implements NHttpRequestHandlerResolver { private final NHttpRequestHandler handler; public SimpleNHttpRequestHandlerResolver(final NHttpRequestHandler handler) { this.handler = handler; } public NHttpRequestHandler lookup(final String requestURI) { return this.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.mockup; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.apache.http.util.EncodingUtils; public class ReadableByteChannelMockup implements ReadableByteChannel { private final String[] chunks; private final String charset; private int chunkCount = 0; private ByteBuffer currentChunk; private boolean closed = false; public ReadableByteChannelMockup(final String[] chunks, final String charset) { super(); this.chunks = chunks; this.charset = charset; } private void prepareChunk() { if (this.currentChunk == null || !this.currentChunk.hasRemaining()) { if (this.chunkCount < this.chunks.length) { String s = this.chunks[this.chunkCount]; this.chunkCount++; this.currentChunk = ByteBuffer.wrap(EncodingUtils.getBytes(s, this.charset)); } else { this.closed = true; } } } public int read(final ByteBuffer dst) throws IOException { prepareChunk(); if (this.closed) { return -1; } int i = 0; while (dst.hasRemaining() && this.currentChunk.hasRemaining()) { dst.put(this.currentChunk.get()); i++; } return i; } public void close() throws IOException { this.closed = true; } public boolean isOpen() { return !this.closed; } }
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.mockup; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.apache.http.nio.ContentDecoder; public class MockupDecoder implements ContentDecoder { private final ReadableByteChannel channel; private boolean completed; public MockupDecoder(final ReadableByteChannel channel) { super(); this.channel = channel; } 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 = this.channel.read(dst); if (bytesRead == -1) { this.completed = true; } return bytesRead; } 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.mockup; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerResolver; public class SimpleHttpRequestHandlerResolver implements HttpRequestHandlerResolver { private final HttpRequestHandler handler; public SimpleHttpRequestHandlerResolver(final HttpRequestHandler handler) { super(); this.handler = handler; } public HttpRequestHandler lookup(final String requestURI) { return this.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; import java.io.IOException; import org.apache.http.nio.reactor.IOReactorExceptionHandler; class SimpleIOReactorExceptionHandler implements IOReactorExceptionHandler { public boolean handle(final RuntimeException ex) { if (!(ex instanceof OoopsieRuntimeException)) { ex.printStackTrace(System.out); } return false; } public boolean handle(final IOException ex) { ex.printStackTrace(System.out); return false; } }
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; import java.io.IOException; import junit.framework.TestCase; import org.apache.http.mockup.HttpClientNio; import org.apache.http.mockup.HttpServerNio; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; /** * Base class for all HttpCore NIO tests * */ public class HttpCoreNIOTestBase extends TestCase { public HttpCoreNIOTestBase(String testName) { super(testName); } protected HttpServerNio server; protected HttpClientNio client; @Override protected void setUp() throws Exception { HttpParams serverParams = new SyncBasicHttpParams(); serverParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1"); this.server = new HttpServerNio(serverParams); this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler()); HttpParams clientParams = new SyncBasicHttpParams(); clientParams .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1"); this.client = new HttpClientNio(clientParams); this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler()); } @Override protected void tearDown() { try { this.client.shutdown(); } catch (IOException ex) { ex.printStackTrace(System.out); } try { this.server.shutdown(); } catch (IOException ex) { ex.printStackTrace(System.out); } } }
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.contrib.sip; import org.apache.http.Header; /** * Represents an SIP (or HTTP) header field with an optional compact name. * RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field * names have an abbreviated form which is equivalent to the full name. * All compact header names defined for SIP are registered at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a>. * <br/> * While all compact names defined so far are single-character names, * RFC 3261 does not mandate that. This interface therefore allows for * strings as the compact name. * * */ public interface CompactHeader extends Header { /** * Obtains the name of this header in compact form, if there is one. * * @return the compact name of this header, or * <code>null</code> if there is none */ String getCompactName() ; }
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.contrib.sip; import org.apache.http.FormattedHeader; import org.apache.http.HeaderElement; import org.apache.http.ParseException; import org.apache.http.util.CharArrayBuffer; import org.apache.http.message.ParserCursor; import org.apache.http.message.BasicHeaderValueParser; /** * Represents a SIP (or HTTP) header field parsed 'on demand'. * The name of the header will be parsed and mapped immediately, * the value only when accessed * * */ public class BufferedCompactHeader implements CompactHeader, FormattedHeader, Cloneable { /** The full header name. */ private final String fullName; /** The compact header name, if there is one. */ private final String compactName; /** * The buffer containing the entire header line. */ private final CharArrayBuffer buffer; /** * The beginning of the header value in the buffer */ private final int valuePos; /** * Creates a new header from a buffer. * The name of the header will be parsed and mapped immediately, * the value only if it is accessed. * * @param buffer the buffer containing the header to represent * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} * * @throws ParseException in case of a parse error */ public BufferedCompactHeader(final CharArrayBuffer buffer, CompactHeaderMapper mapper) throws ParseException { super(); if (buffer == null) { throw new IllegalArgumentException ("Char array buffer may not be null"); } final int colon = buffer.indexOf(':'); if (colon == -1) { throw new ParseException ("Missing colon after header name.\n" + buffer.toString()); } final String name = buffer.substringTrimmed(0, colon); if (name.length() == 0) { throw new ParseException ("Missing header name.\n" + buffer.toString()); } if (mapper == null) mapper = BasicCompactHeaderMapper.DEFAULT; final String altname = mapper.getAlternateName(name); String fname = name; String cname = altname; if ((altname != null) && (name.length() < altname.length())) { // the header uses the compact name fname = altname; cname = name; } this.fullName = fname; this.compactName = cname; this.buffer = buffer; this.valuePos = colon + 1; } // non-javadoc, see interface Header public String getName() { return this.fullName; } // non-javadoc, see interface CompactHeader public String getCompactName() { return this.compactName; } // non-javadoc, see interface Header public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } // non-javadoc, see interface Header public HeaderElement[] getElements() throws ParseException { ParserCursor cursor = new ParserCursor(0, this.buffer.length()); cursor.updatePos(this.valuePos); return BasicHeaderValueParser.DEFAULT .parseElements(this.buffer, cursor); } // non-javadoc, see interface BufferedHeader public int getValuePos() { return this.valuePos; } // non-javadoc, see interface BufferedHeader public CharArrayBuffer getBuffer() { return this.buffer; } @Override public String toString() { return this.buffer.toString(); } @Override public Object clone() throws CloneNotSupportedException { // buffer is considered immutable // no need to make a copy of it return super.clone(); } }
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.contrib.sip; import org.apache.http.message.BasicHeader; /** * Represents a SIP (or HTTP) header field with optional compact name. * * */ public class BasicCompactHeader extends BasicHeader implements CompactHeader { private static final long serialVersionUID = -8275767773930430518L; /** The compact name, if there is one. */ private final String compact; /** * Constructor with names and value. * * @param fullname the full header name * @param compactname the compact header name, or <code>null</code> * @param value the header value */ public BasicCompactHeader(final String fullname, final String compactname, final String value) { super(fullname, value); if ((compactname != null) && (compactname.length() >= fullname.length())) { throw new IllegalArgumentException ("Compact name must be shorter than full name. " + compactname + " -> " + fullname); } this.compact = compactname; } // non-javadoc, see interface CompactHeader public String getCompactName() { return this.compact; } /** * Creates a compact header with automatic lookup. * * @param name the header name, either full or compact * @param value the header value * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} */ public static BasicCompactHeader newHeader(final String name, final String value, CompactHeaderMapper mapper) { if (name == null) { throw new IllegalArgumentException ("The name must not be null."); } // value will be checked by constructor later if (mapper == null) mapper = BasicCompactHeaderMapper.DEFAULT; final String altname = mapper.getAlternateName(name); String fname = name; String cname = altname; if ((altname != null) && (name.length() < altname.length())) { // we were called with the compact name fname = altname; cname = name; } return new BasicCompactHeader(fname, cname, value); } // we might want a toString method that includes the short name, if defined // default cloning implementation is fine }
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.contrib.sip; import org.apache.http.HttpException; /** * Signals that an SIP exception has occurred. * This is for protocol errors specific to SIP, * as opposed to protocol errors shared with HTTP. * * */ public class SipException extends HttpException { private static final long serialVersionUID = 337592534308025800L; /** * Creates a new SipException with a <tt>null</tt> detail message. */ public SipException() { super(); } /** * Creates a new SipException with the specified detail message. * * @param message the exception detail message */ public SipException(final String message) { super(message); } /** * Creates a new SipException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or * <tt>null</tt> if the cause is unavailable, unknown, or * not a <tt>Throwable</tt> */ public SipException(final String message, final Throwable cause) { super(message, cause); } }
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.contrib.sip; /** * A mapper between full and compact header names. * RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field * names have an abbreviated form which is equivalent to the full name. * All compact header names defined for SIP are registered at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a>. * <br/> * While all compact names defined so far are single-character names, * RFC 3261 does not mandate that. This interface therefore allows for * strings as the compact name. * * */ public interface CompactHeaderMapper { /** * Obtains the compact name for the given full name. * * @param fullname the header name for which to look up the compact form * * @return the compact form of the argument header name, or * <code>null</code> if there is none */ String getCompactName(String fullname) ; /** * Obtains the full name for the given compact name. * * @param compactname the compact name for which to look up the full name * * @return the full name of the argument compact header name, or * <code>null</code> if there is none */ String getFullName(String compactname) ; /** * Obtains the alternate name for the given header name. * This performs a lookup in both directions, if necessary. * <br/> * If the returned name is shorter than the argument name, * the argument was a full header name and the result is * the compact name. * If the returned name is longer than the argument name, * the argument was a compact header name and the result * is the full name. * If the returned name has the same length as the argument name, * somebody didn't understand the concept of a <i>compact form</i> * when defining the mapping. You should expect malfunctioning * applications in this case. * * @param name the header name to map, either a full or compact name * * @return the alternate header name, or * <code>null</code> if there is none */ String getAlternateName(String name) ; }
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.contrib.sip; import java.util.Map; import java.util.HashMap; import java.util.Collections; /** * Basic implementation of a {@link CompactHeaderMapper}. * Header names are assumed to be case insensitive. * * */ public class BasicCompactHeaderMapper implements CompactHeaderMapper { /** * The map from compact names to full names. * Keys are converted to lower case, values may be mixed case. */ protected Map<String,String> mapCompactToFull; /** * The map from full names to compact names. * Keys are converted to lower case, values may be mixed case. */ protected Map<String,String> mapFullToCompact; /** * The default mapper. * This mapper is initialized with the compact header names defined at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * on 2008-01-02. */ // see below for static initialization public final static CompactHeaderMapper DEFAULT; /** * Creates a new header mapper with an empty mapping. */ public BasicCompactHeaderMapper() { createMaps(); } /** * Initializes the two maps. * The default implementation here creates an empty hash map for * each attribute that is <code>null</code>. * Derived implementations may choose to instantiate other * map implementations, or to populate the maps by default. * In the latter case, it is the responsibility of the dervied class * to guarantee consistent mappings in both directions. */ protected void createMaps() { if (mapCompactToFull == null) { mapCompactToFull = new HashMap<String,String>(); } if (mapFullToCompact == null) { mapFullToCompact = new HashMap<String,String>(); } } /** * Adds a header name mapping. * * @param compact the compact name of the header * @param full the full name of the header */ public void addMapping(final String compact, final String full) { if (compact == null) { throw new IllegalArgumentException ("The compact name must not be null."); } if (full == null) { throw new IllegalArgumentException ("The full name must not be null."); } if (compact.length() >= full.length()) { throw new IllegalArgumentException ("The compact name must be shorter than the full name. " + compact + " -> " + full); } mapCompactToFull.put(compact.toLowerCase(), full); mapFullToCompact.put(full.toLowerCase(), compact); } /** * Switches this mapper to read-only mode. * Subsequent invocations of {@link #addMapping addMapping} * will trigger an exception. * <br/> * The implementation here should be called only once. * It replaces the internal maps with unmodifiable ones. */ protected void makeReadOnly() { mapCompactToFull = Collections.unmodifiableMap(mapCompactToFull); mapFullToCompact = Collections.unmodifiableMap(mapFullToCompact); } // non-javadoc, see interface CompactHeaderMapper public String getCompactName(final String fullname) { if (fullname == null) { throw new IllegalArgumentException ("The full name must not be null."); } return mapFullToCompact.get(fullname.toLowerCase()); } // non-javadoc, see interface CompactHeaderMapper public String getFullName(final String compactname) { if (compactname == null) { throw new IllegalArgumentException ("The compact name must not be null."); } return mapCompactToFull.get(compactname.toLowerCase()); } // non-javadoc, see interface CompactHeaderMapper public String getAlternateName(final String name) { if (name == null) { throw new IllegalArgumentException ("The name must not be null."); } final String namelc = name.toLowerCase(); String result = null; // to minimize lookups, use a heuristic to determine the direction boolean iscompact = name.length() < 2; if (iscompact) { result = mapCompactToFull.get(namelc); } if (result == null) { result = mapFullToCompact.get(namelc); } if ((result == null) && !iscompact) { result = mapCompactToFull.get(namelc); } return result; } // initializes the default mapper and switches it to read-only mode static { BasicCompactHeaderMapper chm = new BasicCompactHeaderMapper(); chm.addMapping("a", "Accept-Contact"); chm.addMapping("u", "Allow-Events"); chm.addMapping("i", "Call-ID"); chm.addMapping("m", "Contact"); chm.addMapping("e", "Content-Encoding"); chm.addMapping("l", "Content-Length"); chm.addMapping("c", "Content-Type"); chm.addMapping("o", "Event"); chm.addMapping("f", "From"); chm.addMapping("y", "Identity"); chm.addMapping("n", "Identity-Info"); chm.addMapping("r", "Refer-To"); chm.addMapping("b", "Referred-By"); chm.addMapping("j", "Reject-Contact"); chm.addMapping("d", "Request-Disposition"); chm.addMapping("x", "Session-Expires"); chm.addMapping("s", "Subject"); chm.addMapping("k", "Supported"); chm.addMapping("t", "To"); chm.addMapping("v", "Via"); chm.makeReadOnly(); DEFAULT = chm; } }
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.contrib.sip; /** * Constants enumerating the SIP status codes. * All status codes registered at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * on 2007-12-30 are listed. * The defining RFCs include RFC 3261 (SIP/2.0), * RFC 3265 (SIP-Specific Event Notification), * RFC 4412 (Communications Resource Priority for SIP), * RFC 4474 (Enhancements for Authenticated Identity Management in SIP), * and others. * * */ public interface SipStatus { // --- 1xx Informational --- /** <tt>100 Trying</tt>. RFC 3261, section 21.1.1. */ public static final int SC_CONTINUE = 100; /** <tt>180 Ringing</tt>. RFC 3261, section 21.1.2. */ public static final int SC_RINGING = 180; /** <tt>181 Call Is Being Forwarded</tt>. RFC 3261, section 21.1.3. */ public static final int SC_CALL_IS_BEING_FORWARDED = 181; /** <tt>182 Queued</tt>. RFC 3261, section 21.1.4. */ public static final int SC_QUEUED = 182; /** <tt>183 Session Progress</tt>. RFC 3261, section 21.1.5. */ public static final int SC_SESSION_PROGRESS = 183; // --- 2xx Successful --- /** <tt>200 OK</tt>. RFC 3261, section 21.2.1. */ public static final int SC_OK = 200; /** <tt>202 Accepted</tt>. RFC 3265, section 6.4. */ public static final int SC_ACCEPTED = 202; // --- 3xx Redirection --- /** <tt>300 Multiple Choices</tt>. RFC 3261, section 21.3.1. */ public static final int SC_MULTIPLE_CHOICES = 300; /** <tt>301 Moved Permanently</tt>. RFC 3261, section 21.3.2. */ public static final int SC_MOVED_PERMANENTLY = 301; /** <tt>302 Moved Temporarily</tt>. RFC 3261, section 21.3.3. */ public static final int SC_MOVED_TEMPORARILY = 302; /** <tt>305 Use Proxy</tt>. RFC 3261, section 21.3.4. */ public static final int SC_USE_PROXY = 305; /** <tt>380 Alternative Service</tt>. RFC 3261, section 21.3.5. */ public static final int SC_ALTERNATIVE_SERVICE = 380; // --- 4xx Request Failure --- /** <tt>400 Bad Request</tt>. RFC 3261, section 21.4.1. */ public static final int SC_BAD_REQUEST = 400; /** <tt>401 Unauthorized</tt>. RFC 3261, section 21.4.2. */ public static final int SC_UNAUTHORIZED = 401; /** <tt>402 Payment Required</tt>. RFC 3261, section 21.4.3. */ public static final int SC_PAYMENT_REQUIRED = 402; /** <tt>403 Forbidden</tt>. RFC 3261, section 21.4.4. */ public static final int SC_FORBIDDEN = 403; /** <tt>404 Not Found</tt>. RFC 3261, section 21.4.5. */ public static final int SC_NOT_FOUND = 404; /** <tt>405 Method Not Allowed</tt>. RFC 3261, section 21.4.6. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** <tt>406 Not Acceptable</tt>. RFC 3261, section 21.4.7. */ public static final int SC_NOT_ACCEPTABLE = 406; /** * <tt>407 Proxy Authentication Required</tt>. * RFC 3261, section 21.4.8. */ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** <tt>408 Request Timeout</tt>. RFC 3261, section 21.4.9. */ public static final int SC_REQUEST_TIMEOUT = 408; /** <tt>410 Gone</tt>. RFC 3261, section 21.4.10. */ public static final int SC_GONE = 410; /** <tt>412 Conditional Request Failed</tt>. RFC 3903, section 11.2.1. */ public static final int SC_CONDITIONAL_REQUEST_FAILED = 412; /** <tt>413 Request Entity Too Large</tt>. RFC 3261, section 21.4.11. */ public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; /** <tt>414 Request-URI Too Long</tt>. RFC 3261, section 21.4.12. */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** <tt>415 Unsupported Media Type</tt>. RFC 3261, section 21.4.13. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** <tt>416 Unsupported URI Scheme</tt>. RFC 3261, section 21.4.14. */ public static final int SC_UNSUPPORTED_URI_SCHEME = 416; /** <tt>417 Unknown Resource-Priority</tt>. RFC 4412, section 12.4. */ public static final int SC_UNKNOWN_RESOURCE_PRIORITY = 417; /** <tt>420 Bad Extension</tt>. RFC 3261, section 21.4.15. */ public static final int SC_BAD_EXTENSION = 420; /** <tt>421 Extension Required</tt>. RFC 3261, section 21.4.16. */ public static final int SC_EXTENSION_REQUIRED = 421; /** <tt>422 Session Interval Too Small</tt>. RFC 4028, chapter 6. */ public static final int SC_SESSION_INTERVAL_TOO_SMALL = 422; /** <tt>423 Interval Too Brief</tt>. RFC 3261, section 21.4.17. */ public static final int SC_INTERVAL_TOO_BRIEF = 423; /** <tt>428 Use Identity Header</tt>. RFC 4474, section 14.2. */ public static final int SC_USE_IDENTITY_HEADER = 428; /** <tt>429 Provide Referrer Identity</tt>. RFC 3892, chapter 5. */ public static final int SC_PROVIDE_REFERRER_IDENTITY = 429; /** <tt>433 Anonymity Disallowed</tt>. RFC 5079, chapter 5. */ public static final int SC_ANONYMITY_DISALLOWED = 433; /** <tt>436 Bad Identity-Info</tt>. RFC 4474, section 14.3. */ public static final int SC_BAD_IDENTITY_INFO = 436; /** <tt>437 Unsupported Certificate</tt>. RFC 4474, section 14.4. */ public static final int SC_UNSUPPORTED_CERTIFICATE = 437; /** <tt>438 Invalid Identity Header</tt>. RFC 4474, section 14.5. */ public static final int SC_INVALID_IDENTITY_HEADER = 438; /** <tt>480 Temporarily Unavailable</tt>. RFC 3261, section 21.4.18. */ public static final int SC_TEMPORARILY_UNAVAILABLE = 480; /** * <tt>481 Call/Transaction Does Not Exist</tt>. * RFC 3261, section 21.4.19. */ public static final int SC_CALL_TRANSACTION_DOES_NOT_EXIST = 481; /** <tt>482 Loop Detected</tt>. RFC 3261, section 21.4.20. */ public static final int SC_LOOP_DETECTED = 482; /** <tt>483 Too Many Hops</tt>. RFC 3261, section 21.4.21. */ public static final int SC_TOO_MANY_HOPS = 483; /** <tt>484 Address Incomplete</tt>. RFC 3261, section 21.4.22. */ public static final int SC_ADDRESS_INCOMPLETE = 484; /** <tt>485 Ambiguous</tt>. RFC 3261, section 21.4.23. */ public static final int SC_AMBIGUOUS = 485; /** <tt>486 Busy Here</tt>. RFC 3261, section 21.4.24. */ public static final int SC_BUSY_HERE = 486; /** <tt>487 Request Terminated</tt>. RFC 3261, section 21.4.25. */ public static final int SC_REQUEST_TERMINATED = 487; /** <tt>488 Not Acceptable Here</tt>. RFC 3261, section 21.4.26. */ public static final int SC_NOT_ACCEPTABLE_HERE = 488; /** <tt>489 Bad Event</tt>. RFC 3265, section 6.4. */ public static final int SC_BAD_EVENT = 489; /** <tt>491 Request Pending</tt>. RFC 3261, section 21.4.27. */ public static final int SC_REQUEST_PENDING = 491; /** <tt>493 Undecipherable</tt>. RFC 3261, section 21.4.28. */ public static final int SC_UNDECIPHERABLE = 493; /** <tt>494 Security Agreement Required</tt>. RFC 3329, section 6.4. */ public static final int SC_SECURITY_AGREEMENT_REQUIRED = 494; // --- 5xx Server Failure --- /** <tt>500 Server Internal Error</tt>. RFC 3261, section 21.5.1. */ public static final int SC_SERVER_INTERNAL_ERROR = 500; /** <tt>501 Not Implemented</tt>. RFC 3261, section 21.5.2. */ public static final int SC_NOT_IMPLEMENTED = 501; /** <tt>502 Bad Gateway</tt>. RFC 3261, section 21.5.3. */ public static final int SC_BAD_GATEWAY = 502; /** <tt>503 Service Unavailable</tt>. RFC 3261, section 21.5.4. */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** <tt>504 Server Time-out</tt>. RFC 3261, section 21.5.5. */ public static final int SC_SERVER_TIMEOUT = 504; /** <tt>505 Version Not Supported</tt>. RFC 3261, section 21.5.6. */ public static final int SC_VERSION_NOT_SUPPORTED = 505; /** <tt>513 Message Too Large</tt>. RFC 3261, section 21.5.7. */ public static final int SC_MESSAGE_TOO_LARGE = 513; /** <tt>580 Precondition Failure</tt>. RFC 3312, chapter 8. */ public static final int SC_PRECONDITION_FAILURE = 580; // --- 6xx Global Failures --- /** <tt>600 Busy Everywhere</tt>. RFC 3261, section 21.6.1. */ public static final int SC_BUSY_EVERYWHERE = 600; /** <tt>603 Decline</tt>. RFC 3261, section 21.6.2. */ public static final int SC_DECLINE = 603; /** <tt>604 Does Not Exist Anywhere</tt>. RFC 3261, section 21.6.3. */ public static final int SC_DOES_NOT_EXIST_ANYWHERE = 604; /** * <tt>606 Not Acceptable</tt>. RFC 3261, section 21.6.4. * Status codes 606 and 406 both indicate "Not Acceptable", * but we can only define one constant with that name in this interface. * 406 is specific to an endpoint, while 606 is global and * indicates that the callee will not find the request acceptable * on any endpoint. */ public static final int SC_NOT_ACCEPTABLE_ANYWHERE = 606; }
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.contrib.sip; import org.apache.http.Header; import org.apache.http.ParseException; import org.apache.http.util.CharArrayBuffer; import org.apache.http.message.BasicLineParser; /** * Basic parser for lines in the head section of an SIP message. * * */ public class BasicSipLineParser extends BasicLineParser { /** The header name mapper to use, never <code>null</code>. */ protected final CompactHeaderMapper mapper; /** * A default instance of this class, for use as default or fallback. */ public final static BasicSipLineParser DEFAULT = new BasicSipLineParser(null); /** * Creates a new line parser for SIP protocol. * * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} */ public BasicSipLineParser(CompactHeaderMapper mapper) { super(SipVersion.SIP_2_0); this.mapper = (mapper != null) ? mapper : BasicCompactHeaderMapper.DEFAULT; } // non-javadoc, see interface LineParser @Override public Header parseHeader(CharArrayBuffer buffer) throws ParseException { // the actual parser code is in the constructor of BufferedHeader return new BufferedCompactHeader(buffer, mapper); } }
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.contrib.sip; import java.io.Serializable; import org.apache.http.ProtocolVersion; /** * Represents an SIP version, as specified in RFC 3261. * * */ public final class SipVersion extends ProtocolVersion implements Serializable { private static final long serialVersionUID = 6112302080954348220L; /** The protocol name. */ public static final String SIP = "SIP"; /** SIP protocol version 2.0 */ public static final SipVersion SIP_2_0 = new SipVersion(2, 0); /** * Create a SIP protocol version designator. * * @param major the major version number of the SIP protocol * @param minor the minor version number of the SIP protocol * * @throws IllegalArgumentException * if either major or minor version number is negative */ public SipVersion(int major, int minor) { super(SIP, major, minor); } /** * Obtains a specific SIP version. * * @param major the major version * @param minor the minor version * * @return an instance of {@link SipVersion} with the argument version */ @Override public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } if ((major == 2) && (minor == 0)) { return SIP_2_0; } // argument checking is done in the constructor return new SipVersion(major, minor); } }
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.contrib.sip; import java.util.Locale; import java.util.Map; import java.util.HashMap; import org.apache.http.ReasonPhraseCatalog; /** * English reason phrases for SIP status codes. * All status codes defined in {@link SipStatus} are supported. * See <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * for a full list of registered SIP status codes and the defining RFCs. * * */ public class EnglishSipReasonPhraseCatalog implements ReasonPhraseCatalog { // static map with english reason phrases defined below /** * The default instance of this catalog. * This catalog is thread safe, so there typically * is no need to create other instances. */ public final static EnglishSipReasonPhraseCatalog INSTANCE = new EnglishSipReasonPhraseCatalog(); /** * Restricted default constructor, for derived classes. * If you need an instance of this class, use {@link #INSTANCE INSTANCE}. */ protected EnglishSipReasonPhraseCatalog() { // no body } /** * Obtains the reason phrase for a status code. * * @param status the status code, in the range 100-699 * @param loc ignored * * @return the reason phrase, or <code>null</code> */ public String getReason(int status, Locale loc) { if ((status < 100) || (status >= 700)) { throw new IllegalArgumentException ("Unknown category for status code " + status + "."); } // Unlike HTTP status codes, those for SIP are not compact // in each category. We therefore use a map for lookup. return REASON_PHRASES.get(Integer.valueOf(status)); } /** * Reason phrases lookup table. * Since this attribute is private and never exposed, * we don't need to turn it into an unmodifiable map. */ // see below for static initialization private static final Map<Integer,String> REASON_PHRASES = new HashMap<Integer,String>(); /** * Stores the given reason phrase, by status code. * Helper method to initialize the static lookup map. * * @param status the status code for which to define the phrase * @param reason the reason phrase for this status code */ private static void setReason(int status, String reason) { REASON_PHRASES.put(Integer.valueOf(status), reason); } // ----------------------------------------------------- Static Initializer /** Set up status code to "reason phrase" map. */ static { // --- 1xx Informational --- setReason(SipStatus.SC_CONTINUE, "Trying"); setReason(SipStatus.SC_RINGING, "Ringing"); setReason(SipStatus.SC_CALL_IS_BEING_FORWARDED, "Call Is Being Forwarded"); setReason(SipStatus.SC_QUEUED, "Queued"); setReason(SipStatus.SC_SESSION_PROGRESS, "Session Progress"); // --- 2xx Successful --- setReason(SipStatus.SC_OK, "OK"); setReason(SipStatus.SC_ACCEPTED, "Accepted"); // --- 3xx Redirection --- setReason(SipStatus.SC_MULTIPLE_CHOICES, "Multiple Choices"); setReason(SipStatus.SC_MOVED_PERMANENTLY, "Moved Permanently"); setReason(SipStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily"); setReason(SipStatus.SC_USE_PROXY, "Use Proxy"); setReason(SipStatus.SC_ALTERNATIVE_SERVICE, "Alternative Service"); // --- 4xx Request Failure --- setReason(SipStatus.SC_BAD_REQUEST, "Bad Request"); setReason(SipStatus.SC_UNAUTHORIZED, "Unauthorized"); setReason(SipStatus.SC_PAYMENT_REQUIRED, "Payment Required"); setReason(SipStatus.SC_FORBIDDEN, "Forbidden"); setReason(SipStatus.SC_NOT_FOUND, "Not Found"); setReason(SipStatus.SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); setReason(SipStatus.SC_NOT_ACCEPTABLE, "Not Acceptable"); setReason(SipStatus.SC_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required"); setReason(SipStatus.SC_REQUEST_TIMEOUT, "Request Timeout"); setReason(SipStatus.SC_GONE, "Gone"); setReason(SipStatus.SC_CONDITIONAL_REQUEST_FAILED, "Conditional Request Failed"); setReason(SipStatus.SC_REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large"); setReason(SipStatus.SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long"); setReason(SipStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); setReason(SipStatus.SC_UNSUPPORTED_URI_SCHEME, "Unsupported URI Scheme"); setReason(SipStatus.SC_UNKNOWN_RESOURCE_PRIORITY, "Unknown Resource-Priority"); setReason(SipStatus.SC_BAD_EXTENSION, "Bad Extension"); setReason(SipStatus.SC_EXTENSION_REQUIRED, "Extension Required"); setReason(SipStatus.SC_SESSION_INTERVAL_TOO_SMALL, "Session Interval Too Small"); setReason(SipStatus.SC_INTERVAL_TOO_BRIEF, "Interval Too Brief"); setReason(SipStatus.SC_USE_IDENTITY_HEADER, "Use Identity Header"); setReason(SipStatus.SC_PROVIDE_REFERRER_IDENTITY, "Provide Referrer Identity"); setReason(SipStatus.SC_ANONYMITY_DISALLOWED, "Anonymity Disallowed"); setReason(SipStatus.SC_BAD_IDENTITY_INFO, "Bad Identity-Info"); setReason(SipStatus.SC_UNSUPPORTED_CERTIFICATE, "Unsupported Certificate"); setReason(SipStatus.SC_INVALID_IDENTITY_HEADER, "Invalid Identity Header"); setReason(SipStatus.SC_TEMPORARILY_UNAVAILABLE, "Temporarily Unavailable"); setReason(SipStatus.SC_CALL_TRANSACTION_DOES_NOT_EXIST, "Call/Transaction Does Not Exist"); setReason(SipStatus.SC_LOOP_DETECTED, "Loop Detected"); setReason(SipStatus.SC_TOO_MANY_HOPS, "Too Many Hops"); setReason(SipStatus.SC_ADDRESS_INCOMPLETE, "Address Incomplete"); setReason(SipStatus.SC_AMBIGUOUS, "Ambiguous"); setReason(SipStatus.SC_BUSY_HERE, "Busy Here"); setReason(SipStatus.SC_REQUEST_TERMINATED, "Request Terminated"); setReason(SipStatus.SC_NOT_ACCEPTABLE_HERE, "Not Acceptable Here"); setReason(SipStatus.SC_BAD_EVENT, "Bad Event"); setReason(SipStatus.SC_REQUEST_PENDING, "Request Pending"); setReason(SipStatus.SC_UNDECIPHERABLE, "Undecipherable"); setReason(SipStatus.SC_SECURITY_AGREEMENT_REQUIRED, "Security Agreement Required"); // --- 5xx Server Failure --- setReason(SipStatus.SC_SERVER_INTERNAL_ERROR, "Server Internal Error"); setReason(SipStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); setReason(SipStatus.SC_BAD_GATEWAY, "Bad Gateway"); setReason(SipStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); setReason(SipStatus.SC_SERVER_TIMEOUT, "Server Time-out"); setReason(SipStatus.SC_VERSION_NOT_SUPPORTED, "Version Not Supported"); setReason(SipStatus.SC_MESSAGE_TOO_LARGE, "Message Too Large"); setReason(SipStatus.SC_PRECONDITION_FAILURE, "Precondition Failure"); // --- 6xx Global Failures --- setReason(SipStatus.SC_BUSY_EVERYWHERE, "Busy Everywhere"); setReason(SipStatus.SC_DECLINE, "Decline"); setReason(SipStatus.SC_DOES_NOT_EXIST_ANYWHERE, "Does Not Exist Anywhere"); setReason(SipStatus.SC_NOT_ACCEPTABLE_ANYWHERE, "Not Acceptable"); } // static initializer }
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.contrib.logging; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; public class LoggingClientIOEventDispatch extends DefaultClientIOEventDispatch { public LoggingClientIOEventDispatch( final NHttpClientHandler handler, final HttpParams params) { super(new LoggingNHttpClientHandler(handler), params); } @Override protected NHttpClientIOTarget createConnection(final IOSession session) { return new LoggingNHttpClientConnection( new LoggingIOSession(session, "client"), createHttpResponseFactory(), this.allocator, this.params); } }
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.contrib.logging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; 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.DefaultNHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageWriter; 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; public class LoggingNHttpClientConnection extends DefaultNHttpClientConnection { private final Log log; private final Log headerlog; public LoggingNHttpClientConnection( final IOSession session, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, responseFactory, allocator, params); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } @Override public void close() throws IOException { this.log.debug("Close connection"); super.close(); } @Override public void shutdown() throws IOException { this.log.debug("Shutdown connection"); super.shutdown(); } @Override public void submitRequest(final HttpRequest request) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + this + ": " + request.getRequestLine().toString()); } super.submitRequest(request); } @Override public void consumeInput(final NHttpClientHandler handler) { this.log.debug("Consume input"); super.consumeInput(handler); } @Override public void produceOutput(final NHttpClientHandler handler) { this.log.debug("Produce output"); super.produceOutput(handler); } @Override protected NHttpMessageWriter<HttpRequest> createRequestWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new LoggingNHttpMessageWriter( super.createRequestWriter(buffer, params)); } @Override protected NHttpMessageParser<HttpResponse> createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { return new LoggingNHttpMessageParser( super.createResponseParser(buffer, responseFactory, params)); } class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpRequest> { private final NHttpMessageWriter<HttpRequest> writer; public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpRequest> writer) { super(); this.writer = writer; } public void reset() { this.writer.reset(); } public void write(final HttpRequest message) throws IOException, HttpException { if (message != null && headerlog.isDebugEnabled()) { headerlog.debug(">> " + message.getRequestLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug(">> " + headers[i].toString()); } } this.writer.write(message); } } class LoggingNHttpMessageParser implements NHttpMessageParser<HttpResponse> { private final NHttpMessageParser<HttpResponse> parser; public LoggingNHttpMessageParser(final NHttpMessageParser<HttpResponse> parser) { super(); this.parser = parser; } public void reset() { this.parser.reset(); } public int fillBuffer(final ReadableByteChannel channel) throws IOException { return this.parser.fillBuffer(channel); } public HttpResponse parse() throws IOException, HttpException { HttpResponse message = this.parser.parse(); if (message != null && headerlog.isDebugEnabled()) { headerlog.debug("<< " + message.getStatusLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug("<< " + headers[i].toString()); } } return message; } } }
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.contrib.logging; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; /** * Decorator class intended to transparently extend an {@link NHttpClientHandler} * with basic event logging capabilities using Commons Logging. * */ public class LoggingNHttpClientHandler implements NHttpClientHandler { private final Log log; private final Log headerlog; private final NHttpClientHandler handler; public LoggingNHttpClientHandler(final NHttpClientHandler handler) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP client handler may not be null"); } this.handler = handler; this.log = LogFactory.getLog(handler.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } public void connected(final NHttpClientConnection conn, final Object attachment) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Connected (" + attachment + ")"); } this.handler.connected(conn, attachment); } public void closed(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Closed"); } this.handler.closed(conn); } public void exception(final NHttpClientConnection conn, final IOException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void exception(final NHttpClientConnection conn, final HttpException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void requestReady(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Request ready"); } this.handler.requestReady(conn); } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Output ready"); } this.handler.outputReady(conn, encoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder); } } public void responseReceived(final NHttpClientConnection conn) { HttpResponse response = conn.getHttpResponse(); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": " + response.getStatusLine()); } this.handler.responseReceived(conn); if (this.headerlog.isDebugEnabled()) { this.headerlog.debug("<< " + response.getStatusLine().toString()); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { this.headerlog.debug("<< " + headers[i].toString()); } } } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Input ready"); } this.handler.inputReady(conn, decoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder); } } public void timeout(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Timeout"); } 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.contrib.logging; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; /** * Decorator class intended to transparently extend an {@link NHttpServiceHandler} * with basic event logging capabilities using Commons Logging. * */ public class LoggingNHttpServiceHandler implements NHttpServiceHandler { private final Log log; private final Log headerlog; private final NHttpServiceHandler handler; public LoggingNHttpServiceHandler(final NHttpServiceHandler handler) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP service handler may not be null"); } this.handler = handler; this.log = LogFactory.getLog(handler.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } public void connected(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Connected"); } this.handler.connected(conn); } public void closed(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Closed"); } this.handler.closed(conn); } public void exception(final NHttpServerConnection conn, final IOException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void exception(final NHttpServerConnection conn, final HttpException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void requestReceived(final NHttpServerConnection conn) { HttpRequest request = conn.getHttpRequest(); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": " + request.getRequestLine()); } this.handler.requestReceived(conn); if (this.headerlog.isDebugEnabled()) { this.headerlog.debug(">> " + request.getRequestLine().toString()); Header[] headers = request.getAllHeaders(); for (int i = 0; i < headers.length; i++) { this.headerlog.debug(">> " + headers[i].toString()); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Output ready"); } this.handler.outputReady(conn, encoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder); } } public void responseReady(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Response ready"); } this.handler.responseReady(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Input ready"); } this.handler.inputReady(conn, decoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder); } } public void timeout(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Timeout"); } 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.contrib.logging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; 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.DefaultNHttpServerConnection; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpServiceHandler; 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; public class LoggingNHttpServerConnection extends DefaultNHttpServerConnection { private final Log log; private final Log headerlog; public LoggingNHttpServerConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, requestFactory, allocator, params); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } @Override public void close() throws IOException { this.log.debug("Close connection"); super.close(); } @Override public void shutdown() throws IOException { this.log.debug("Shutdown connection"); super.shutdown(); } @Override public void submitResponse(final HttpResponse response) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + this + ": " + response.getStatusLine().toString()); } super.submitResponse(response); } @Override public void consumeInput(final NHttpServiceHandler handler) { this.log.debug("Consume input"); super.consumeInput(handler); } @Override public void produceOutput(final NHttpServiceHandler handler) { this.log.debug("Produce output"); super.produceOutput(handler); } @Override protected NHttpMessageWriter<HttpResponse> createResponseWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new LoggingNHttpMessageWriter( super.createResponseWriter(buffer, params)); } @Override protected NHttpMessageParser<HttpRequest> createRequestParser( final SessionInputBuffer buffer, final HttpRequestFactory requestFactory, final HttpParams params) { return new LoggingNHttpMessageParser( super.createRequestParser(buffer, requestFactory, params)); } class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpResponse> { private final NHttpMessageWriter<HttpResponse> writer; public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpResponse> writer) { super(); this.writer = writer; } public void reset() { this.writer.reset(); } public void write(final HttpResponse message) throws IOException, HttpException { if (message != null && headerlog.isDebugEnabled()) { headerlog.debug("<< " + message.getStatusLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug("<< " + headers[i].toString()); } } this.writer.write(message); } } class LoggingNHttpMessageParser implements NHttpMessageParser<HttpRequest> { private final NHttpMessageParser<HttpRequest> parser; public LoggingNHttpMessageParser(final NHttpMessageParser<HttpRequest> parser) { super(); this.parser = parser; } public void reset() { this.parser.reset(); } public int fillBuffer(final ReadableByteChannel channel) throws IOException { return this.parser.fillBuffer(channel); } public HttpRequest parse() throws IOException, HttpException { HttpRequest message = this.parser.parse(); if (message != null && headerlog.isDebugEnabled()) { headerlog.debug(">> " + message.getRequestLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug(">> " + headers[i].toString()); } } return message; } } }
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.contrib.logging; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; public class LoggingServerIOEventDispatch extends DefaultServerIOEventDispatch { public LoggingServerIOEventDispatch( final NHttpServiceHandler handler, final HttpParams params) { super(new LoggingNHttpServiceHandler(handler), params); } @Override protected NHttpServerIOTarget createConnection(final IOSession session) { return new LoggingNHttpServerConnection( new LoggingIOSession(session, "server"), createHttpRequestFactory(), this.allocator, this.params); } }
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.contrib.logging; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; /** * Decorator class intended to transparently extend an {@link IOSession} * with basic event logging capabilities using Commons Logging. * */ public class LoggingIOSession implements IOSession { private static AtomicLong COUNT = new AtomicLong(0); private final Log log; private final Wire wirelog; private final IOSession session; private final ByteChannel channel; private final String id; public LoggingIOSession(final IOSession session, final String id) { super(); if (session == null) { throw new IllegalArgumentException("I/O session may not be null"); } this.session = session; this.channel = new LoggingByteChannel(); this.id = id + "-" + COUNT.incrementAndGet(); this.log = LogFactory.getLog(session.getClass()); this.wirelog = new Wire(LogFactory.getLog("org.apache.http.wire")); } public ByteChannel channel() { return this.channel; } public SocketAddress getLocalAddress() { return this.session.getLocalAddress(); } public SocketAddress getRemoteAddress() { return this.session.getRemoteAddress(); } public int getEventMask() { return this.session.getEventMask(); } private static String formatOps(int ops) { StringBuffer buffer = new StringBuffer(6); 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(']'); return buffer.toString(); } public void setEventMask(int ops) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set event mask " + formatOps(ops)); } this.session.setEventMask(ops); } public void setEvent(int op) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set event " + formatOps(op)); } this.session.setEvent(op); } public void clearEvent(int op) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Clear event " + formatOps(op)); } this.session.clearEvent(op); } public void close() { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Close"); } this.session.close(); } public int getStatus() { return this.session.getStatus(); } public boolean isClosed() { return this.session.isClosed(); } public void shutdown() { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Shutdown"); } this.session.shutdown(); } public int getSocketTimeout() { return this.session.getSocketTimeout(); } public void setSocketTimeout(int timeout) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set timeout " + timeout); } this.session.setSocketTimeout(timeout); } public void setBufferStatus(final SessionBufferStatus status) { this.session.setBufferStatus(status); } public boolean hasBufferedInput() { return this.session.hasBufferedInput(); } public boolean hasBufferedOutput() { return this.session.hasBufferedOutput(); } public Object getAttribute(final String name) { return this.session.getAttribute(name); } public void setAttribute(final String name, final Object obj) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set attribute " + name); } this.session.setAttribute(name, obj); } public Object removeAttribute(final String name) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Remove attribute " + name); } return this.session.removeAttribute(name); } class LoggingByteChannel implements ByteChannel { public int read(final ByteBuffer dst) throws IOException { int bytesRead = session.channel().read(dst); if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": " + bytesRead + " bytes read"); } if (bytesRead > 0 && wirelog.isEnabled()) { ByteBuffer b = dst.duplicate(); int p = b.position(); b.limit(p); b.position(p - bytesRead); wirelog.input(b); } return bytesRead; } public int write(final ByteBuffer src) throws IOException { int byteWritten = session.channel().write(src); if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": " + byteWritten + " bytes written"); } if (byteWritten > 0 && wirelog.isEnabled()) { ByteBuffer b = src.duplicate(); int p = b.position(); b.limit(p); b.position(p - byteWritten); wirelog.output(b); } return byteWritten; } public void close() throws IOException { if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": Channel close"); } session.channel().close(); } public boolean isOpen() { return session.channel().isOpen(); } } }
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.contrib.logging; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; class Wire { private final Log log; public Wire(final Log log) { super(); this.log = log; } private void wire(final String header, final byte[] b, int pos, int off) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < off; i++) { int ch = b[pos + i]; if (ch == 13) { buffer.append("[\\r]"); } else if (ch == 10) { buffer.append("[\\n]\""); buffer.insert(0, "\""); buffer.insert(0, header); this.log.debug(buffer.toString()); buffer.setLength(0); } else if ((ch < 32) || (ch > 127)) { buffer.append("[0x"); buffer.append(Integer.toHexString(ch)); buffer.append("]"); } else { buffer.append((char) ch); } } if (buffer.length() > 0) { buffer.append('\"'); buffer.insert(0, '\"'); buffer.insert(0, header); this.log.debug(buffer.toString()); } } public boolean isEnabled() { return this.log.isDebugEnabled(); } public void output(final byte[] b, int pos, int off) { wire("<< ", b, pos, off); } public void input(final byte[] b, int pos, int off) { wire(">> ", b, pos, off); } public void output(byte[] b) { output(b, 0, b.length); } public void input(byte[] b) { input(b, 0, b.length); } public void output(int b) { output(new byte[] {(byte) b}); } public void input(int b) { input(new byte[] {(byte) b}); } public void output(final ByteBuffer b) { if (b.hasArray()) { output(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { byte[] tmp = new byte[b.remaining()]; b.get(tmp); output(tmp); } } public void input(final ByteBuffer b) { if (b.hasArray()) { input(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { byte[] tmp = new byte[b.remaining()]; b.get(tmp); input(tmp); } } }
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.contrib.compress; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; /** * Wrapping entity that compresses content when {@link #writeTo writing}. * * * @since 4.0 */ public class GzipCompressingEntity extends HttpEntityWrapper { private static final String GZIP_CODEC = "gzip"; public GzipCompressingEntity(final HttpEntity entity) { super(entity); } @Override public Header getContentEncoding() { return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC); } @Override public long getContentLength() { return -1; } @Override public boolean isChunked() { // force content chunking return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } GZIPOutputStream gzip = new GZIPOutputStream(outstream); InputStream in = wrappedEntity.getContent(); byte[] tmp = new byte[2048]; int l; while ((l = in.read(tmp)) != -1) { gzip.write(tmp, 0, l); } gzip.close(); } } // class GzipCompressingEntity
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.contrib.compress; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; /** * Wrapping entity that decompresses {@link #getContent content}. * * * @since 4.0 */ public class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content not known in advance return -1; } } // class GzipDecompressingEntity
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.contrib.compress; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.ExecutionContext; /** * Server-side interceptor to handle Gzip-encoded responses. * * * @since 4.0 */ public class ResponseGzipCompress implements HttpResponseInterceptor { private static final String ACCEPT_ENCODING = "Accept-Encoding"; private static final String GZIP_CODEC = "gzip"; public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpEntity entity = response.getEntity(); if (entity != null) { HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); Header aeheader = request.getFirstHeader(ACCEPT_ENCODING); if (aeheader != null) { HeaderElement[] codecs = aeheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) { response.setEntity(new GzipCompressingEntity(entity)); return; } } } } } }
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.contrib.compress; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; /** * Client-side interceptor to handle Gzip-compressed responses. * * * @since 4.0 */ public class ResponseGzipUncompress implements HttpResponseInterceptor { private static final String GZIP_CODEC = "gzip"; public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }
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.contrib.compress; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.protocol.HttpContext; /** * Client-side interceptor to indicate support for Gzip content compression. * * * @since 4.0 */ public class RequestAcceptEncoding implements HttpRequestInterceptor { private static final String ACCEPT_ENCODING = "Accept-Encoding"; private static final String GZIP_CODEC = "gzip"; public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader(ACCEPT_ENCODING)) { request.addHeader(ACCEPT_ENCODING, GZIP_CODEC); } } }
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.benchmark; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.http.benchmark.httpcore.HttpCoreNIOServer; import org.apache.http.benchmark.httpcore.HttpCoreServer; import org.apache.http.benchmark.jetty.JettyNIOServer; import org.apache.http.benchmark.jetty.JettyServer; import org.apache.http.benchmark.CommandLineUtils; import org.apache.http.benchmark.Config; import org.apache.http.benchmark.HttpBenchmark; public class Benchmark { private static final int PORT = 8989; public static void main(String[] args) throws Exception { Config config = new Config(); if (args.length > 0) { Options options = CommandLineUtils.getOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Benchmark [options]", options); System.exit(1); } CommandLineUtils.parseCommandLine(cmd, config); } else { config.setKeepAlive(true); config.setRequests(20000); config.setThreads(25); } URL target = new URL("http", "localhost", PORT, "/rnd?c=2048"); config.setUrl(target); Benchmark benchmark = new Benchmark(); benchmark.run(new JettyServer(PORT), config); benchmark.run(new HttpCoreServer(PORT), config); benchmark.run(new JettyNIOServer(PORT), config); benchmark.run(new HttpCoreNIOServer(PORT), config); } public Benchmark() { super(); } public void run(final HttpServer server, final Config config) throws Exception { server.start(); try { System.out.println("---------------------------------------------------------------"); System.out.println(server.getName() + "; version: " + server.getVersion()); System.out.println("---------------------------------------------------------------"); HttpBenchmark ab = new HttpBenchmark(config); ab.execute(); System.out.println("---------------------------------------------------------------"); } finally { server.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.benchmark.jetty; import java.io.IOException; import org.apache.http.benchmark.HttpServer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class JettyNIOServer implements HttpServer { private final Server server; public JettyNIOServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setRequestBufferSize(12 * 1024); connector.setResponseBufferSize(12 * 1024); connector.setAcceptors(2); QueuedThreadPool threadpool = new QueuedThreadPool(); threadpool.setMinThreads(25); threadpool.setMaxThreads(200); this.server = new Server(); this.server.addConnector(connector); this.server.setThreadPool(threadpool); this.server.setHandler(new RandomDataHandler()); } public String getName() { return "Jetty (NIO)"; } public String getVersion() { return Server.getVersion(); } public void start() throws Exception { this.server.start(); } public void shutdown() { try { this.server.stop(); } catch (Exception ex) { } try { this.server.join(); } catch (InterruptedException ex) { } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final JettyNIOServer server = new JettyNIOServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.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.benchmark.jetty; import java.io.IOException; import org.apache.http.benchmark.HttpServer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class JettyServer implements HttpServer { private final Server server; public JettyServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } SocketConnector connector = new SocketConnector(); connector.setPort(port); connector.setRequestBufferSize(12 * 1024); connector.setResponseBufferSize(12 * 1024); connector.setAcceptors(2); QueuedThreadPool threadpool = new QueuedThreadPool(); threadpool.setMinThreads(25); threadpool.setMaxThreads(200); this.server = new Server(); this.server.addConnector(connector); this.server.setThreadPool(threadpool); this.server.setHandler(new RandomDataHandler()); } public String getName() { return "Jetty (blocking I/O)"; } public String getVersion() { return Server.getVersion(); } public void start() throws Exception { this.server.start(); } public void shutdown() { try { this.server.stop(); } catch (Exception ex) { } try { this.server.join(); } catch (InterruptedException ex) { } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final JettyServer server = new JettyServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.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.benchmark.jetty; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; class RandomDataHandler extends AbstractHandler { public RandomDataHandler() { super(); } public void handle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (target.equals("/rnd")) { rnd(request, response); } else { response.setStatus(HttpStatus.NOT_FOUND_404); Writer writer = response.getWriter(); writer.write("Target not found: " + target); writer.flush(); } } private void rnd( final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { int count = 100; String s = request.getParameter("c"); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatus(500); Writer writer = response.getWriter(); writer.write("Invalid query format: " + request.getQueryString()); writer.flush(); return; } response.setStatus(200); response.setContentLength(count); OutputStream outstream = response.getOutputStream(); byte[] tmp = new byte[1024]; int r = Math.abs(tmp.hashCode()); int remaining = count; while (remaining > 0) { int chunk = Math.min(tmp.length, remaining); for (int i = 0; i < chunk; i++) { tmp[i] = (byte) ((r + i) % 96 + 32); } outstream.write(tmp, 0, chunk); remaining -= chunk; } 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.benchmark.httpcore; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.protocol.HttpService; class HttpListener extends Thread { private final ServerSocket serversocket; private final HttpService httpservice; private final HttpWorkerCallback workercallback; private volatile boolean shutdown; private volatile Exception exception; public HttpListener( final ServerSocket serversocket, final HttpService httpservice, final HttpWorkerCallback workercallback) { super(); this.serversocket = serversocket; this.httpservice = httpservice; this.workercallback = workercallback; } public boolean isShutdown() { return this.shutdown; } public Exception getException() { return this.exception; } @Override public void run() { while (!Thread.interrupted() && !this.shutdown) { try { // Set up HTTP connection Socket socket = this.serversocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(socket, this.httpservice.getParams()); // Start worker thread HttpWorker t = new HttpWorker(this.httpservice, conn, this.workercallback); t.start(); } catch (InterruptedIOException ex) { terminate(); } catch (IOException ex) { this.exception = ex; terminate(); } } } public void terminate() { if (this.shutdown) { return; } this.shutdown = true; try { this.serversocket.close(); } catch (IOException ex) { if (this.exception != null) { this.exception = ex; } } } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
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.benchmark.httpcore; import java.io.IOException; import org.apache.http.HttpServerConnection; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpService; class HttpWorker extends Thread { private final HttpService httpservice; private final HttpServerConnection conn; private final HttpWorkerCallback workercallback; private volatile boolean shutdown; private volatile Exception exception; public HttpWorker( final HttpService httpservice, final HttpServerConnection conn, final HttpWorkerCallback workercallback) { super(); this.httpservice = httpservice; this.conn = conn; this.workercallback = workercallback; } public boolean isShutdown() { return this.shutdown; } public Exception getException() { return this.exception; } @Override public void run() { this.workercallback.started(this); try { HttpContext context = new BasicHttpContext(); while (!Thread.interrupted() && !this.shutdown) { this.httpservice.handleRequest(this.conn, context); } } catch (Exception ex) { this.exception = ex; } finally { terminate(); this.workercallback.shutdown(this); } } public void terminate() { if (this.shutdown) { return; } this.shutdown = true; try { this.conn.shutdown(); } catch (IOException ex) { if (this.exception != null) { this.exception = ex; } } } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
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.benchmark.httpcore; interface HttpWorkerCallback { void started(HttpWorker worker); void shutdown(HttpWorker worker); }
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.benchmark.httpcore; import java.io.IOException; import java.net.ServerSocket; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.http.HttpResponseInterceptor; import org.apache.http.benchmark.HttpServer; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.HttpService; 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.VersionInfo; public class HttpCoreServer implements HttpServer { private final Queue<HttpWorker> workers; private final HttpListener listener; public HttpCoreServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024) .setIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-Test/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/rnd", new RandomDataHandler()); HttpService httpservice = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, params); this.workers = new ConcurrentLinkedQueue<HttpWorker>(); this.listener = new HttpListener( new ServerSocket(port), httpservice, new StdHttpWorkerCallback(this.workers)); } public String getName() { return "HttpCore (blocking I/O)"; } public String getVersion() { VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http", Thread.currentThread().getContextClassLoader()); return vinfo.getRelease(); } public void start() { this.listener.start(); } public void shutdown() { this.listener.terminate(); try { this.listener.awaitTermination(1000); } catch (InterruptedException ex) { } Exception ex = this.listener.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } while (!this.workers.isEmpty()) { HttpWorker worker = this.workers.remove(); worker.terminate(); try { worker.awaitTermination(1000); } catch (InterruptedException iex) { } ex = worker.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final HttpCoreServer server = new HttpCoreServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.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.benchmark.httpcore; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.http.HttpResponseInterceptor; import org.apache.http.benchmark.HttpServer; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.protocol.AsyncNHttpServiceHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.VersionInfo; public class HttpCoreNIOServer implements HttpServer { private final int port; private final NHttpListener listener; public HttpCoreNIOServer(int port) throws IOException { if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } this.port = port; HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-NIO-Test/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry(); reqistry.register("/rnd", new NRandomDataHandler()); handler.setHandlerResolver(reqistry); ListeningIOReactor ioreactor = new DefaultListeningIOReactor(2, params); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); this.listener = new NHttpListener(ioreactor, ioEventDispatch); } public String getName() { return "HttpCore (NIO)"; } public String getVersion() { VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http", Thread.currentThread().getContextClassLoader()); return vinfo.getRelease(); } public void start() throws Exception { this.listener.start(); this.listener.listen(new InetSocketAddress(this.port)); } public void shutdown() { this.listener.terminate(); try { this.listener.awaitTermination(1000); } catch (InterruptedException ex) { } Exception ex = this.listener.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final HttpCoreNIOServer server = new HttpCoreNIOServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.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.benchmark.httpcore; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; class RandomDataHandler implements HttpRequestHandler { public RandomDataHandler() { super(); } 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(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); } static class RandomEntity extends AbstractHttpEntity { private int count; private final byte[] buf; public RandomEntity(int count) { super(); this.count = count; this.buf = new byte[1024]; setContentType("text/plain"); } public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("Method not supported"); } public long getContentLength() { return this.count; } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public void writeTo(final OutputStream outstream) throws IOException { int r = Math.abs(this.buf.hashCode()); int remaining = this.count; while (remaining > 0) { int chunk = Math.min(this.buf.length, remaining); for (int i = 0; i < chunk; i++) { this.buf[i] = (byte) ((r + i) % 96 + 32); } outstream.write(this.buf, 0, chunk); remaining -= chunk; } } } }
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.benchmark.httpcore; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Queue; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; class StdHttpWorkerCallback implements HttpWorkerCallback { private final Queue<HttpWorker> queue; public StdHttpWorkerCallback(final Queue<HttpWorker> queue) { super(); this.queue = queue; } public void started(final HttpWorker worker) { this.queue.add(worker); } public void shutdown(final HttpWorker worker) { this.queue.remove(worker); Exception ex = worker.getException(); if (ex != null) { if (ex instanceof HttpException) { System.err.println("HTTP protocol error: " + ex.getMessage()); } else if (ex instanceof SocketTimeoutException) { // ignore } else if (ex instanceof ConnectionClosedException) { // ignore } else if (ex instanceof IOException) { System.err.println("I/O error: " + ex); } else { System.err.println("Unexpected error: " + ex.getMessage()); } } } }
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.benchmark.httpcore; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.ListeningIOReactor; public class NHttpListener extends Thread { private final ListeningIOReactor ioreactor; private final IOEventDispatch ioEventDispatch; private volatile Exception exception; public NHttpListener( final ListeningIOReactor ioreactor, final IOEventDispatch ioEventDispatch) throws IOException { super(); this.ioreactor = ioreactor; this.ioEventDispatch = ioEventDispatch; } @Override public void run() { try { this.ioreactor.execute(this.ioEventDispatch); } catch (Exception ex) { this.exception = ex; } } public void listen(final InetSocketAddress address) throws InterruptedException { ListenerEndpoint endpoint = this.ioreactor.listen(address); endpoint.waitFor(); } public void terminate() { try { this.ioreactor.shutdown(); } catch (IOException ex) { } } public Exception getException() { return this.exception; } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
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.benchmark.httpcore; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; class NRandomDataHandler implements NHttpRequestHandler { public NRandomDataHandler() { super(); } public ConsumingNHttpEntity entityRequest( final HttpEntityEnclosingRequest request, final HttpContext context) throws HttpException, IOException { // Use buffering entity for simplicity return new BufferingNHttpEntity(request.getEntity(), new HeapByteBufferAllocator()); } public void handle( final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, 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(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); trigger.submitResponse(response); } 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(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); } static class RandomEntity extends AbstractHttpEntity implements ProducingNHttpEntity { private final int count; private final ByteBuffer buf; private int remaining; public RandomEntity(int count) { super(); this.count = count; this.remaining = count; this.buf = ByteBuffer.allocate(1024); setContentType("text/plain"); } public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("Method not supported"); } public long getContentLength() { return this.count; } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public void writeTo(final OutputStream outstream) throws IOException { throw new IllegalStateException("Method not supported"); } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { int r = Math.abs(this.buf.hashCode()); int chunk = Math.min(this.buf.remaining(), this.remaining); if (chunk > 0) { for (int i = 0; i < chunk; i++) { byte b = (byte) ((r + i) % 96 + 32); this.buf.put(b); } } this.buf.flip(); int bytesWritten = encoder.write(this.buf); this.remaining -= bytesWritten; if (this.remaining == 0 && this.buf.remaining() == 0) { encoder.complete(); } this.buf.compact(); } public void finish() throws IOException { this.remaining = this.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.benchmark; public interface HttpServer { String getName(); String getVersion(); void start() throws Exception; void 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.benchmark; import java.io.File; import java.net.URL; public class Config { private URL url; private int requests; private int threads; private boolean keepAlive; private int verbosity; private boolean headInsteadOfGet; private boolean useHttp1_0; private String contentType; private String[] headers; private int socketTimeout; private String method = "GET"; private boolean useChunking; private boolean useExpectContinue; private boolean useAcceptGZip; private File payloadFile = null; private String payloadText = null; private String soapAction = null; private boolean disableSSLVerification = true; private String trustStorePath = null; private String identityStorePath = null; private String trustStorePassword = null; private String identityStorePassword = null; public Config() { super(); this.url = null; this.requests = 1; this.threads = 1; this.keepAlive = false; this.verbosity = 0; this.headInsteadOfGet = false; this.useHttp1_0 = false; this.payloadFile = null; this.payloadText = null; this.contentType = null; this.headers = null; this.socketTimeout = 60000; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } public int getRequests() { return requests; } public void setRequests(int requests) { this.requests = requests; } public int getThreads() { return threads; } public void setThreads(int threads) { this.threads = threads; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public int getVerbosity() { return verbosity; } public void setVerbosity(int verbosity) { this.verbosity = verbosity; } public boolean isHeadInsteadOfGet() { return headInsteadOfGet; } public void setHeadInsteadOfGet(boolean headInsteadOfGet) { this.headInsteadOfGet = headInsteadOfGet; this.method = "HEAD"; } public boolean isUseHttp1_0() { return useHttp1_0; } public void setUseHttp1_0(boolean useHttp1_0) { this.useHttp1_0 = useHttp1_0; } public File getPayloadFile() { return payloadFile; } public void setPayloadFile(File payloadFile) { this.payloadFile = payloadFile; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String[] getHeaders() { return headers; } public void setHeaders(String[] headers) { this.headers = headers; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public void setMethod(String method) { this.method = method; } public void setUseChunking(boolean useChunking) { this.useChunking = useChunking; } public void setUseExpectContinue(boolean useExpectContinue) { this.useExpectContinue = useExpectContinue; } public void setUseAcceptGZip(boolean useAcceptGZip) { this.useAcceptGZip = useAcceptGZip; } public String getMethod() { return method; } public boolean isUseChunking() { return useChunking; } public boolean isUseExpectContinue() { return useExpectContinue; } public boolean isUseAcceptGZip() { return useAcceptGZip; } public String getPayloadText() { return payloadText; } public String getSoapAction() { return soapAction; } public boolean isDisableSSLVerification() { return disableSSLVerification; } public String getTrustStorePath() { return trustStorePath; } public String getIdentityStorePath() { return identityStorePath; } public String getTrustStorePassword() { return trustStorePassword; } public String getIdentityStorePassword() { return identityStorePassword; } public void setPayloadText(String payloadText) { this.payloadText = payloadText; } public void setSoapAction(String soapAction) { this.soapAction = soapAction; } public void setDisableSSLVerification(boolean disableSSLVerification) { this.disableSSLVerification = disableSSLVerification; } public void setTrustStorePath(String trustStorePath) { this.trustStorePath = trustStorePath; } public void setIdentityStorePath(String identityStorePath) { this.identityStorePath = identityStorePath; } public void setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = trustStorePassword; } public void setIdentityStorePassword(String identityStorePassword) { this.identityStorePassword = identityStorePassword; } }
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.benchmark; /** * Helper to gather statistics for an {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ public class Stats { private long startTime = -1; // nano seconds - does not represent an actual time private long finishTime = -1; // nano seconds - does not represent an actual time private int successCount = 0; private int failureCount = 0; private int writeErrors = 0; private int keepAliveCount = 0; private String serverName = null; private long totalBytesRecv = 0; private long contentLength = -1; public Stats() { super(); } public void start() { this.startTime = System.nanoTime(); } public void finish() { this.finishTime = System.nanoTime(); } public long getFinishTime() { return this.finishTime; } public long getStartTime() { return this.startTime; } /** * Total execution time measured in nano seconds * * @return duration in nanoseconds */ public long getDuration() { // we are using System.nanoTime() and the return values could be negative // but its only the difference that we are concerned about return this.finishTime - this.startTime; } public void incSuccessCount() { this.successCount++; } public int getSuccessCount() { return this.successCount; } public void incFailureCount() { this.failureCount++; } public int getFailureCount() { return this.failureCount; } public void incWriteErrors() { this.writeErrors++; } public int getWriteErrors() { return this.writeErrors; } public void incKeepAliveCount() { this.keepAliveCount++; } public int getKeepAliveCount() { return this.keepAliveCount; } public long getTotalBytesRecv() { return this.totalBytesRecv; } public void incTotalBytesRecv(int n) { this.totalBytesRecv += n; } public long getContentLength() { return this.contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public String getServerName() { return this.serverName; } public void setServerName(final String serverName) { this.serverName = serverName; } }
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.benchmark; import org.apache.http.HttpHost; import java.text.NumberFormat; public class ResultProcessor { static NumberFormat nf2 = NumberFormat.getInstance(); static NumberFormat nf3 = NumberFormat.getInstance(); static NumberFormat nf6 = NumberFormat.getInstance(); static { nf2.setMaximumFractionDigits(2); nf2.setMinimumFractionDigits(2); nf3.setMaximumFractionDigits(3); nf3.setMinimumFractionDigits(3); nf6.setMaximumFractionDigits(6); nf6.setMinimumFractionDigits(6); } static String printResults(BenchmarkWorker[] workers, HttpHost host, String uri, long contentLength) { double totalTimeNano = 0; long successCount = 0; long failureCount = 0; long writeErrors = 0; long keepAliveCount = 0; long totalBytesRcvd = 0; Stats stats = workers[0].getStats(); for (int i = 0; i < workers.length; i++) { Stats s = workers[i].getStats(); totalTimeNano += s.getDuration(); successCount += s.getSuccessCount(); failureCount += s.getFailureCount(); writeErrors += s.getWriteErrors(); keepAliveCount += s.getKeepAliveCount(); totalBytesRcvd += s.getTotalBytesRecv(); } int threads = workers.length; double totalTimeMs = (totalTimeNano / threads) / 1000000; // convert nano secs to milli secs double timePerReqMs = totalTimeMs / successCount; double totalTimeSec = totalTimeMs / 1000; double reqsPerSec = successCount / totalTimeSec; long totalBytesSent = contentLength * successCount; long totalBytes = totalBytesRcvd + (totalBytesSent > 0 ? totalBytesSent : 0); StringBuilder sb = new StringBuilder(1024); printAndAppend(sb,"\nServer Software:\t\t" + stats.getServerName()); printAndAppend(sb, "Server Hostname:\t\t" + host.getHostName()); printAndAppend(sb, "Server Port:\t\t\t" + (host.getPort() > 0 ? host.getPort() : uri.startsWith("https") ? "443" : "80") + "\n"); printAndAppend(sb, "Document Path:\t\t\t" + uri); printAndAppend(sb, "Document Length:\t\t" + stats.getContentLength() + " bytes\n"); printAndAppend(sb, "Concurrency Level:\t\t" + workers.length); printAndAppend(sb, "Time taken for tests:\t\t" + nf6.format(totalTimeSec) + " seconds"); printAndAppend(sb, "Complete requests:\t\t" + successCount); printAndAppend(sb, "Failed requests:\t\t" + failureCount); printAndAppend(sb, "Write errors:\t\t\t" + writeErrors); printAndAppend(sb, "Kept alive:\t\t\t" + keepAliveCount); printAndAppend(sb, "Total transferred:\t\t" + totalBytes + " bytes"); printAndAppend(sb, "Requests per second:\t\t" + nf2.format(reqsPerSec) + " [#/sec] (mean)"); printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs * workers.length) + " [ms] (mean)"); printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs) + " [ms] (mean, across all concurrent requests)"); printAndAppend(sb, "Transfer rate:\t\t\t" + nf2.format(totalBytesRcvd/1000/totalTimeSec) + " [Kbytes/sec] received"); printAndAppend(sb, "\t\t\t\t" + (totalBytesSent > 0 ? nf2.format(totalBytesSent/1000/totalTimeSec) : -1) + " kb/s sent"); printAndAppend(sb, "\t\t\t\t" + nf2.format(totalBytes/1000/totalTimeSec) + " kb/s total"); return sb.toString(); } private static void printAndAppend(StringBuilder sb, String s) { System.out.println(s); sb.append(s).append("\r\n"); } }
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.benchmark; import java.io.UnsupportedEncodingException; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.entity.FileEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; /** * Main program of the HTTP benchmark. * * * @since 4.0 */ public class HttpBenchmark { private final Config config; private HttpParams params = null; private HttpRequest[] request = null; private HttpHost host = null; private long contentLength = -1; public static void main(String[] args) throws Exception { Options options = CommandLineUtils.getOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption('h') || cmd.getArgs().length != 1) { CommandLineUtils.showUsage(options); System.exit(1); } Config config = new Config(); CommandLineUtils.parseCommandLine(cmd, config); if (config.getUrl() == null) { CommandLineUtils.showUsage(options); System.exit(1); } HttpBenchmark httpBenchmark = new HttpBenchmark(config); httpBenchmark.execute(); } public HttpBenchmark(final Config config) { super(); this.config = config != null ? config : new Config(); } private void prepare() throws UnsupportedEncodingException { // prepare http params params = getHttpParams(config.getSocketTimeout(), config.isUseHttp1_0(), config.isUseExpectContinue()); URL url = config.getUrl(); host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); HttpEntity entity = null; // Prepare requests for each thread if (config.getPayloadFile() != null) { entity = new FileEntity(config.getPayloadFile(), config.getContentType()); ((FileEntity) entity).setChunked(config.isUseChunking()); contentLength = config.getPayloadFile().length(); } else if (config.getPayloadText() != null) { entity = new StringEntity(config.getPayloadText(), config.getContentType(), "UTF-8"); ((StringEntity) entity).setChunked(config.isUseChunking()); contentLength = config.getPayloadText().getBytes().length; } request = new HttpRequest[config.getThreads()]; for (int i = 0; i < request.length; i++) { if ("POST".equals(config.getMethod())) { BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST", url.getPath()); httppost.setEntity(entity); request[i] = httppost; } else if ("PUT".equals(config.getMethod())) { BasicHttpEntityEnclosingRequest httpput = new BasicHttpEntityEnclosingRequest("PUT", url.getPath()); httpput.setEntity(entity); request[i] = httpput; } else { String path = url.getPath(); if (url.getQuery() != null && url.getQuery().length() > 0) { path += "?" + url.getQuery(); } else if (path.trim().length() == 0) { path = "/"; } request[i] = new BasicHttpRequest(config.getMethod(), path); } } if (!config.isKeepAlive()) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } } String[] headers = config.getHeaders(); if (headers != null) { for (int i = 0; i < headers.length; i++) { String s = headers[i]; int pos = s.indexOf(':'); if (pos != -1) { Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1)); for (int j = 0; j < request.length; j++) { request[j].addHeader(header); } } } } if (config.isUseAcceptGZip()) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader("Accept-Encoding", "gzip")); } } if (config.getSoapAction() != null && config.getSoapAction().length() > 0) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader("SOAPAction", config.getSoapAction())); } } } public String execute() throws Exception { prepare(); ThreadPoolExecutor workerPool = new ThreadPoolExecutor( config.getThreads(), config.getThreads(), 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(r, "ClientPool"); } }); workerPool.prestartAllCoreThreads(); BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()]; for (int i = 0; i < workers.length; i++) { workers[i] = new BenchmarkWorker( params, config.getVerbosity(), request[i], host, config.getRequests(), config.isKeepAlive(), config.isDisableSSLVerification(), config.getTrustStorePath(), config.getTrustStorePassword(), config.getIdentityStorePath(), config.getIdentityStorePassword()); workerPool.execute(workers[i]); } while (workerPool.getCompletedTaskCount() < config.getThreads()) { Thread.yield(); try { Thread.sleep(1000); } catch (InterruptedException ignore) { } } workerPool.shutdown(); return ResultProcessor.printResults(workers, host, config.getUrl().toString(), contentLength); } private HttpParams getHttpParams( int socketTimeout, boolean useHttp1_0, boolean useExpectContinue) { HttpParams params = new BasicHttpParams(); params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, useHttp1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1) .setParameter(HttpProtocolParams.USER_AGENT, "HttpCore-AB/1.1") .setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, useExpectContinue) .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false) .setIntParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeout); return params; } }
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.benchmark; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import java.io.File; import java.net.MalformedURLException; import java.net.URL; public class CommandLineUtils { public static Options getOptions() { Option iopt = new Option("i", false, "Do HEAD requests instead of GET (deprecated)"); iopt.setRequired(false); Option oopt = new Option("o", false, "Use HTTP/S 1.0 instead of 1.1 (default)"); oopt.setRequired(false); Option kopt = new Option("k", false, "Enable the HTTP KeepAlive feature, " + "i.e., perform multiple requests within one HTTP session. " + "Default is no KeepAlive"); kopt.setRequired(false); Option uopt = new Option("u", false, "Chunk entity. Default is false"); uopt.setRequired(false); Option xopt = new Option("x", false, "Use Expect-Continue. Default is false"); xopt.setRequired(false); Option gopt = new Option("g", false, "Accept GZip. Default is false"); gopt.setRequired(false); Option nopt = new Option("n", true, "Number of requests to perform for the " + "benchmarking session. The default is to just perform a single " + "request which usually leads to non-representative benchmarking " + "results"); nopt.setRequired(false); nopt.setArgName("requests"); Option copt = new Option("c", true, "Concurrency while performing the " + "benchmarking session. The default is to just use a single thread/client"); copt.setRequired(false); copt.setArgName("concurrency"); Option popt = new Option("p", true, "File containing data to POST or PUT"); popt.setRequired(false); popt.setArgName("Payload file"); Option mopt = new Option("m", true, "HTTP Method. Default is POST. " + "Possible options are GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE"); mopt.setRequired(false); mopt.setArgName("HTTP method"); Option Topt = new Option("T", true, "Content-type header to use for POST/PUT data"); Topt.setRequired(false); Topt.setArgName("content-type"); Option topt = new Option("t", true, "Client side socket timeout (in ms) - default 60 Secs"); topt.setRequired(false); topt.setArgName("socket-Timeout"); Option Hopt = new Option("H", true, "Add arbitrary header line, " + "eg. 'Accept-Encoding: gzip' inserted after all normal " + "header lines. (repeatable as -H \"h1: v1\",\"h2: v2\" etc)"); Hopt.setRequired(false); Hopt.setArgName("header"); Option vopt = new Option("v", true, "Set verbosity level - 4 and above " + "prints response content, 3 and above prints " + "information on headers, 2 and above prints response codes (404, 200, " + "etc.), 1 and above prints warnings and info"); vopt.setRequired(false); vopt.setArgName("verbosity"); Option hopt = new Option("h", false, "Display usage information"); nopt.setRequired(false); Options options = new Options(); options.addOption(iopt); options.addOption(mopt); options.addOption(uopt); options.addOption(xopt); options.addOption(gopt); options.addOption(kopt); options.addOption(nopt); options.addOption(copt); options.addOption(popt); options.addOption(Topt); options.addOption(vopt); options.addOption(Hopt); options.addOption(hopt); options.addOption(topt); options.addOption(oopt); return options; } public static void parseCommandLine(CommandLine cmd, Config config) { if (cmd.hasOption('v')) { String s = cmd.getOptionValue('v'); try { config.setVerbosity(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid verbosity level: " + s); } } if (cmd.hasOption('k')) { config.setKeepAlive(true); } if (cmd.hasOption('c')) { String s = cmd.getOptionValue('c'); try { config.setThreads(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid number for concurrency: " + s); } } if (cmd.hasOption('n')) { String s = cmd.getOptionValue('n'); try { config.setRequests(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid number of requests: " + s); } } if (cmd.hasOption('p')) { File file = new File(cmd.getOptionValue('p')); if (!file.exists()) { printError("File not found: " + file); } config.setPayloadFile(file); } if (cmd.hasOption('T')) { config.setContentType(cmd.getOptionValue('T')); } if (cmd.hasOption('i')) { config.setHeadInsteadOfGet(true); } if (cmd.hasOption('H')) { String headerStr = cmd.getOptionValue('H'); config.setHeaders(headerStr.split(",")); } if (cmd.hasOption('t')) { String t = cmd.getOptionValue('t'); try { config.setSocketTimeout(Integer.parseInt(t)); } catch (NumberFormatException ex) { printError("Invalid socket timeout: " + t); } } if (cmd.hasOption('o')) { config.setUseHttp1_0(true); } if (cmd.hasOption('m')) { config.setMethod(cmd.getOptionValue('m')); } else if (cmd.hasOption('p')) { config.setMethod("POST"); } if (cmd.hasOption('u')) { config.setUseChunking(true); } if (cmd.hasOption('x')) { config.setUseExpectContinue(true); } if (cmd.hasOption('g')) { config.setUseAcceptGZip(true); } String[] cmdargs = cmd.getArgs(); if (cmdargs.length > 0) { try { config.setUrl(new URL(cmdargs[0])); } catch (MalformedURLException e) { printError("Invalid request URL : " + cmdargs[0]); } } } static void showUsage(final Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path?query", options); } static void printError(String msg) { System.err.println(msg); showUsage(getOptions()); System.exit(-1); } }
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.benchmark; import org.apache.http.message.BasicHeader; public class DefaultHeader extends BasicHeader { public DefaultHeader(final String name, final String value) { super(name, value); } }
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.benchmark; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.security.KeyStore; import javax.net.SocketFactory; import javax.net.ssl.*; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpClientConnection; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Worker thread for the {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ public class BenchmarkWorker implements Runnable { private byte[] buffer = new byte[4096]; private final int verbosity; private final HttpParams params; private final HttpContext context; private final BasicHttpProcessor httpProcessor; private final HttpRequestExecutor httpexecutor; private final ConnectionReuseStrategy connstrategy; private final HttpRequest request; private final HttpHost targetHost; private final int count; private final boolean keepalive; private final boolean disableSSLVerification; private final Stats stats = new Stats(); private final TrustManager[] trustAllCerts; private final String trustStorePath; private final String trustStorePassword; private final String identityStorePath; private final String identityStorePassword; public BenchmarkWorker( final HttpParams params, int verbosity, final HttpRequest request, final HttpHost targetHost, int count, boolean keepalive, boolean disableSSLVerification, String trustStorePath, String trustStorePassword, String identityStorePath, String identityStorePassword) { super(); this.params = params; this.context = new BasicHttpContext(null); this.request = request; this.targetHost = targetHost; this.count = count; this.keepalive = keepalive; this.httpProcessor = new BasicHttpProcessor(); this.httpexecutor = new HttpRequestExecutor(); // Required request interceptors this.httpProcessor.addInterceptor(new RequestContent()); this.httpProcessor.addInterceptor(new RequestTargetHost()); // Recommended request interceptors this.httpProcessor.addInterceptor(new RequestConnControl()); this.httpProcessor.addInterceptor(new RequestUserAgent()); this.httpProcessor.addInterceptor(new RequestExpectContinue()); this.connstrategy = new DefaultConnectionReuseStrategy(); this.verbosity = verbosity; this.disableSSLVerification = disableSSLVerification; this.trustStorePath = trustStorePath; this.trustStorePassword = trustStorePassword; this.identityStorePath = identityStorePath; this.identityStorePassword = identityStorePassword; // Create a trust manager that does not validate certificate chains trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; } public void run() { HttpResponse response = null; DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); String hostname = targetHost.getHostName(); int port = targetHost.getPort(); if (port == -1) { port = 80; } // Populate the execution context this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost); this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request); stats.start(); request.setParams(new DefaultedHttpParams(new BasicHttpParams(), this.params)); for (int i = 0; i < count; i++) { try { resetHeader(request); if (!conn.isOpen()) { Socket socket = null; if ("https".equals(targetHost.getSchemeName())) { if (disableSSLVerification) { SSLContext sc = SSLContext.getInstance("SSL"); if (identityStorePath != null) { KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(identityStorePath); try { identityStore.load(instream, identityStorePassword.toCharArray()); } finally { try { instream.close(); } catch (IOException ignore) {} } KeyManagerFactory kmf = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmf.init(identityStore, identityStorePassword.toCharArray()); sc.init(kmf.getKeyManagers(), trustAllCerts, null); } else { sc.init(null, trustAllCerts, null); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); socket = sc.getSocketFactory().createSocket(hostname, port); } else { if (trustStorePath != null) { System.setProperty("javax.net.ssl.trustStore", trustStorePath); } if (trustStorePassword != null) { System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(hostname, port); } } else { socket = new Socket(hostname, port); } conn.bind(socket, params); } try { // Prepare request this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context); // Execute request and get a response response = this.httpexecutor.execute(this.request, conn, this.context); // Finalize response this.httpexecutor.postProcess(response, this.httpProcessor, this.context); } catch (HttpException e) { stats.incWriteErrors(); if (this.verbosity >= 2) { System.err.println("Failed HTTP request : " + e.getMessage()); } continue; } verboseOutput(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { stats.incSuccessCount(); } else { stats.incFailureCount(); continue; } HttpEntity entity = response.getEntity(); if (entity != null) { String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } long contentlen = 0; InputStream instream = entity.getContent(); int l = 0; while ((l = instream.read(this.buffer)) != -1) { stats.incTotalBytesRecv(l); contentlen += l; if (this.verbosity >= 4) { String s = new String(this.buffer, 0, l, charset); System.out.print(s); } } instream.close(); stats.setContentLength(contentlen); } if (this.verbosity >= 4) { System.out.println(); System.out.println(); } if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) { conn.close(); } else { stats.incKeepAliveCount(); } } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("Generic error: " + ex.getMessage()); } } } stats.finish(); if (response != null) { Header header = response.getFirstHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } } try { conn.close(); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } } private void verboseOutput(HttpResponse response) { if (this.verbosity >= 3) { System.out.println(">> " + request.getRequestLine().toString()); Header[] headers = request.getAllHeaders(); for (int h = 0; h < headers.length; h++) { System.out.println(">> " + headers[h].toString()); } System.out.println(); } if (this.verbosity >= 2) { System.out.println(response.getStatusLine().getStatusCode()); } if (this.verbosity >= 3) { System.out.println("<< " + response.getStatusLine().toString()); Header[] headers = response.getAllHeaders(); for (int h = 0; h < headers.length; h++) { System.out.println("<< " + headers[h].toString()); } System.out.println(); } } private static void resetHeader(final HttpRequest request) { for (HeaderIterator it = request.headerIterator(); it.hasNext();) { Header header = it.nextHeader(); if (!(header instanceof DefaultHeader)) { it.remove(); } } } public Stats getStats() { return stats; } }
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.ogt.http; import java.net.InetAddress; /** * An HTTP connection over the Internet Protocol (IP). * * @since 4.0 */ public interface HttpInetConnection extends HttpConnection { InetAddress getLocalAddress(); int getLocalPort(); InetAddress getRemoteAddress(); int getRemotePort(); }
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.ogt.http; /** * Constants enumerating the HTTP status codes. * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and * RFC2518 (WebDAV) are listed. * * @see StatusLine * * @since 4.0 */ public interface HttpStatus { // --- 1xx Informational --- /** <tt>100 Continue</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_CONTINUE = 100; /** <tt>101 Switching Protocols</tt> (HTTP/1.1 - RFC 2616)*/ public static final int SC_SWITCHING_PROTOCOLS = 101; /** <tt>102 Processing</tt> (WebDAV - RFC 2518) */ public static final int SC_PROCESSING = 102; // --- 2xx Success --- /** <tt>200 OK</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_OK = 200; /** <tt>201 Created</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_CREATED = 201; /** <tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_ACCEPTED = 202; /** <tt>203 Non Authoritative Information</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** <tt>204 No Content</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NO_CONTENT = 204; /** <tt>205 Reset Content</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_RESET_CONTENT = 205; /** <tt>206 Partial Content</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PARTIAL_CONTENT = 206; /** * <tt>207 Multi-Status</tt> (WebDAV - RFC 2518) or <tt>207 Partial Update * OK</tt> (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) */ public static final int SC_MULTI_STATUS = 207; // --- 3xx Redirection --- /** <tt>300 Mutliple Choices</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_MULTIPLE_CHOICES = 300; /** <tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_PERMANENTLY = 301; /** <tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_TEMPORARILY = 302; /** <tt>303 See Other</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_SEE_OTHER = 303; /** <tt>304 Not Modified</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_MODIFIED = 304; /** <tt>305 Use Proxy</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_USE_PROXY = 305; /** <tt>307 Temporary Redirect</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- /** <tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_BAD_REQUEST = 400; /** <tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_UNAUTHORIZED = 401; /** <tt>402 Payment Required</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PAYMENT_REQUIRED = 402; /** <tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_FORBIDDEN = 403; /** <tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_FOUND = 404; /** <tt>405 Method Not Allowed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** <tt>406 Not Acceptable</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_NOT_ACCEPTABLE = 406; /** <tt>407 Proxy Authentication Required</tt> (HTTP/1.1 - RFC 2616)*/ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** <tt>408 Request Timeout</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TIMEOUT = 408; /** <tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_CONFLICT = 409; /** <tt>410 Gone</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_GONE = 410; /** <tt>411 Length Required</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_LENGTH_REQUIRED = 411; /** <tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PRECONDITION_FAILED = 412; /** <tt>413 Request Entity Too Large</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TOO_LONG = 413; /** <tt>414 Request-URI Too Long</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** <tt>415 Unsupported Media Type</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** <tt>416 Requested Range Not Satisfiable</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** <tt>417 Expectation Failed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_EXPECTATION_FAILED = 417; /** * Static constant for a 418 error. * <tt>418 Unprocessable Entity</tt> (WebDAV drafts?) * or <tt>418 Reauthentication Required</tt> (HTTP/1.1 drafts?) */ // not used // public static final int SC_UNPROCESSABLE_ENTITY = 418; /** * Static constant for a 419 error. * <tt>419 Insufficient Space on Resource</tt> * (WebDAV - draft-ietf-webdav-protocol-05?) * or <tt>419 Proxy Reauthentication Required</tt> * (HTTP/1.1 drafts?) */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; /** * Static constant for a 420 error. * <tt>420 Method Failure</tt> * (WebDAV - draft-ietf-webdav-protocol-05?) */ public static final int SC_METHOD_FAILURE = 420; /** <tt>422 Unprocessable Entity</tt> (WebDAV - RFC 2518) */ public static final int SC_UNPROCESSABLE_ENTITY = 422; /** <tt>423 Locked</tt> (WebDAV - RFC 2518) */ public static final int SC_LOCKED = 423; /** <tt>424 Failed Dependency</tt> (WebDAV - RFC 2518) */ public static final int SC_FAILED_DEPENDENCY = 424; // --- 5xx Server Error --- /** <tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** <tt>501 Not Implemented</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_IMPLEMENTED = 501; /** <tt>502 Bad Gateway</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_BAD_GATEWAY = 502; /** <tt>503 Service Unavailable</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** <tt>504 Gateway Timeout</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_GATEWAY_TIMEOUT = 504; /** <tt>505 HTTP Version Not Supported</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; /** <tt>507 Insufficient Storage</tt> (WebDAV - RFC 2518) */ public static final int SC_INSUFFICIENT_STORAGE = 507; }
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.ogt.http; /** * A factory for {@link HttpRequest HttpRequest} objects. * * @since 4.0 */ public interface HttpRequestFactory { HttpRequest newHttpRequest(RequestLine requestline) throws MethodNotSupportedException; HttpRequest newHttpRequest(String method, String uri) throws MethodNotSupportedException; }
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.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.params.HttpProtocolParams; /** * RequestUserAgent is responsible for adding <code>User-Agent</code> header. * This interceptor is recommended for client side protocol processors. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li> * </ul> * * @since 4.0 */ public class RequestUserAgent implements HttpRequestInterceptor { public RequestUserAgent() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (!request.containsHeader(HTTP.USER_AGENT)) { String useragent = HttpProtocolParams.getUserAgent(request.getParams()); if (useragent != null) { request.addHeader(HTTP.USER_AGENT, useragent); } } } }
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.ogt.http.protocol; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; /** * Defines an interface to verify whether an incoming HTTP request meets * the target server's expectations. *<p> * The Expect request-header field is used to indicate that particular * server behaviors are required by the client. *</p> *<pre> * Expect = "Expect" ":" 1#expectation * * expectation = "100-continue" | expectation-extension * expectation-extension = token [ "=" ( token | quoted-string ) * *expect-params ] * expect-params = ";" token [ "=" ( token | quoted-string ) ] *</pre> *<p> * A server that does not understand or is unable to comply with any of * the expectation values in the Expect field of a request MUST respond * with appropriate error status. The server MUST respond with a 417 * (Expectation Failed) status if any of the expectations cannot be met * or, if there are other problems with the request, some other 4xx * status. *</p> * * @since 4.0 */ public interface HttpExpectationVerifier { /** * Verifies whether the given request meets the server's expectations. * <p> * If the request fails to meet particular criteria, this method can * trigger a terminal response back to the client by setting the status * code of the response object to a value greater or equal to * <code>200</code>. In this case the client will not have to transmit * the request body. If the request meets expectations this method can * terminate without modifying the response object. Per default the status * code of the response object will be set to <code>100</code>. * * @param request the HTTP request. * @param response the HTTP response. * @param context the HTTP context. * @throws HttpException in case of an HTTP protocol violation. */ void verify(HttpRequest request, HttpResponse response, HttpContext context) throws 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.ogt.http.protocol; /** * Constants and static helpers related to the HTTP protocol. * * @since 4.0 */ public final class HTTP { public static final int CR = 13; // <US-ASCII CR, carriage return (13)> public static final int LF = 10; // <US-ASCII LF, linefeed (10)> public static final int SP = 32; // <US-ASCII SP, space (32)> public static final int HT = 9; // <US-ASCII HT, horizontal-tab (9)> /** HTTP header definitions */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; public static final String CONTENT_LEN = "Content-Length"; public static final String CONTENT_TYPE = "Content-Type"; public static final String CONTENT_ENCODING = "Content-Encoding"; public static final String EXPECT_DIRECTIVE = "Expect"; public static final String CONN_DIRECTIVE = "Connection"; public static final String TARGET_HOST = "Host"; public static final String USER_AGENT = "User-Agent"; public static final String DATE_HEADER = "Date"; public static final String SERVER_HEADER = "Server"; /** HTTP expectations */ public static final String EXPECT_CONTINUE = "100-continue"; /** HTTP connection control */ public static final String CONN_CLOSE = "Close"; public static final String CONN_KEEP_ALIVE = "Keep-Alive"; /** Transfer encoding definitions */ public static final String CHUNK_CODING = "chunked"; public static final String IDENTITY_CODING = "identity"; /** Common charset definitions */ public static final String UTF_8 = "UTF-8"; public static final String UTF_16 = "UTF-16"; public static final String US_ASCII = "US-ASCII"; public static final String ASCII = "ASCII"; public static final String ISO_8859_1 = "ISO-8859-1"; /** Default charsets */ public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1; public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII; /** Content type definitions */ public final static String OCTET_STREAM_TYPE = "application/octet-stream"; public final static String PLAIN_TEXT_TYPE = "text/plain"; public final static String CHARSET_PARAM = "; charset="; /** Default content type */ public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE; public static boolean isWhitespace(char ch) { return ch == SP || ch == HT || ch == CR || ch == LF; } private HTTP() { } }
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.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; /** * RequestDate interceptor is responsible for adding <code>Date</code> header * to the outgoing requests This interceptor is optional for client side * protocol processors. * * @since 4.0 */ public class RequestDate implements HttpRequestInterceptor { private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); public RequestDate() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException ("HTTP request may not be null."); } if ((request instanceof HttpEntityEnclosingRequest) && !request.containsHeader(HTTP.DATE_HEADER)) { String httpdate = DATE_GENERATOR.getCurrentDate(); request.setHeader(HTTP.DATE_HEADER, httpdate); } } }
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.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; /** * HttpRequestHandler represents a routine for processing of a specific group * of HTTP requests. Protocol handlers are designed to take care of protocol * specific aspects, whereas individual request handlers are expected to take * care of application specific HTTP processing. The main purpose of a request * handler is to generate a response object with a content entity to be sent * back to the client in response to the given request * * @since 4.0 */ public interface HttpRequestHandler { /** * Handles the request and produces a response to be sent back to * the client. * * @param request the HTTP request. * @param response the HTTP response. * @param context the HTTP execution context. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, 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.ogt.http.protocol; /** * HttpRequestHandlerResolver can be used to resolve an instance of * {@link HttpRequestHandler} matching a particular request URI. Usually the * resolved request handler will be used to process the request with the * specified request URI. * * @since 4.0 */ public interface HttpRequestHandlerResolver { /** * Looks up a handler matching the given request URI. * * @param requestURI the request URI * @return HTTP request handler or <code>null</code> if no match * is found. */ HttpRequestHandler lookup(String requestURI); }
Java