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.ogt.http.impl; import java.io.IOException; import org.apache.ogt.http.HttpClientConnection; import org.apache.ogt.http.HttpConnectionMetrics; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.entity.ContentLengthStrategy; import org.apache.ogt.http.impl.entity.EntityDeserializer; import org.apache.ogt.http.impl.entity.EntitySerializer; import org.apache.ogt.http.impl.entity.LaxContentLengthStrategy; import org.apache.ogt.http.impl.entity.StrictContentLengthStrategy; import org.apache.ogt.http.impl.io.HttpRequestWriter; import org.apache.ogt.http.impl.io.HttpResponseParser; import org.apache.ogt.http.io.EofSensor; import org.apache.ogt.http.io.HttpMessageParser; import org.apache.ogt.http.io.HttpMessageWriter; import org.apache.ogt.http.io.HttpTransportMetrics; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.message.LineFormatter; import org.apache.ogt.http.message.LineParser; import org.apache.ogt.http.params.HttpParams; /** * Abstract client-side HTTP connection capable of transmitting and receiving * data using arbitrary {@link SessionInputBuffer} and * {@link SessionOutputBuffer} implementations. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * </ul> * * @since 4.0 */ public abstract class AbstractHttpClientConnection implements HttpClientConnection { private final EntitySerializer entityserializer; private final EntityDeserializer entitydeserializer; private SessionInputBuffer inbuffer = null; private SessionOutputBuffer outbuffer = null; private EofSensor eofSensor = null; private HttpMessageParser responseParser = null; private HttpMessageWriter requestWriter = null; private HttpConnectionMetricsImpl metrics = null; /** * Creates an instance of this class. * <p> * This constructor will invoke {@link #createEntityDeserializer()} * and {@link #createEntitySerializer()} methods in order to initialize * HTTP entity serializer and deserializer implementations for this * connection. */ public AbstractHttpClientConnection() { super(); this.entityserializer = createEntitySerializer(); this.entitydeserializer = createEntityDeserializer(); } /** * Asserts if the connection is open. * * @throws IllegalStateException if the connection is not open. */ protected abstract void assertOpen() throws IllegalStateException; /** * Creates an instance of {@link EntityDeserializer} with the * {@link LaxContentLengthStrategy} implementation to be used for * de-serializing entities received over this connection. * <p> * This method can be overridden in a super class in order to create * instances of {@link EntityDeserializer} using a custom * {@link ContentLengthStrategy}. * * @return HTTP entity deserializer */ protected EntityDeserializer createEntityDeserializer() { return new EntityDeserializer(new LaxContentLengthStrategy()); } /** * Creates an instance of {@link EntitySerializer} with the * {@link StrictContentLengthStrategy} implementation to be used for * serializing HTTP entities sent over this connection. * <p> * This method can be overridden in a super class in order to create * instances of {@link EntitySerializer} using a custom * {@link ContentLengthStrategy}. * * @return HTTP entity serialzier. */ protected EntitySerializer createEntitySerializer() { return new EntitySerializer(new StrictContentLengthStrategy()); } /** * Creates an instance of {@link DefaultHttpResponseFactory} to be used * for creating {@link HttpResponse} objects received by over this * connection. * <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 HttpMessageParser} to be used for parsing * HTTP responses received over this connection. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link HttpMessageParser} interface or * to pass a different implementation of {@link LineParser} to the * the default implementation {@link HttpResponseParser}. * * @param buffer the session input buffer. * @param responseFactory the HTTP response factory. * @param params HTTP parameters. * @return HTTP message parser. */ protected HttpMessageParser createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { return new HttpResponseParser(buffer, null, responseFactory, params); } /** * Creates an instance of {@link HttpMessageWriter} to be used for * writing out HTTP requests sent over this connection. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link HttpMessageWriter} interface or * to pass a different implementation of {@link LineFormatter} to the * the default implementation {@link HttpRequestWriter}. * * @param buffer the session output buffer * @param params HTTP parameters * @return HTTP message writer */ protected HttpMessageWriter createRequestWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new HttpRequestWriter(buffer, null, params); } /** * @since 4.1 */ protected HttpConnectionMetricsImpl createConnectionMetrics( final HttpTransportMetrics inTransportMetric, final HttpTransportMetrics outTransportMetric) { return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric); } /** * Initializes this connection object with {@link SessionInputBuffer} and * {@link SessionOutputBuffer} instances to be used for sending and * receiving data. These session buffers can be bound to any arbitrary * physical output medium. * <p> * This method will invoke {@link #createHttpResponseFactory()}, * {@link #createRequestWriter(SessionOutputBuffer, HttpParams)} * and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)} * methods to initialize HTTP request writer and response parser for this * connection. * * @param inbuffer the session input buffer. * @param outbuffer the session output buffer. * @param params HTTP parameters. */ protected void init( final SessionInputBuffer inbuffer, final SessionOutputBuffer outbuffer, final HttpParams params) { if (inbuffer == null) { throw new IllegalArgumentException("Input session buffer may not be null"); } if (outbuffer == null) { throw new IllegalArgumentException("Output session buffer may not be null"); } this.inbuffer = inbuffer; this.outbuffer = outbuffer; if (inbuffer instanceof EofSensor) { this.eofSensor = (EofSensor) inbuffer; } this.responseParser = createResponseParser( inbuffer, createHttpResponseFactory(), params); this.requestWriter = createRequestWriter( outbuffer, params); this.metrics = createConnectionMetrics( inbuffer.getMetrics(), outbuffer.getMetrics()); } public boolean isResponseAvailable(int timeout) throws IOException { assertOpen(); return this.inbuffer.isDataAvailable(timeout); } public void sendRequestHeader(final HttpRequest request) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } assertOpen(); this.requestWriter.write(request); this.metrics.incrementRequestCount(); } public void sendRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } assertOpen(); if (request.getEntity() == null) { return; } this.entityserializer.serialize( this.outbuffer, request, request.getEntity()); } protected void doFlush() throws IOException { this.outbuffer.flush(); } public void flush() throws IOException { assertOpen(); doFlush(); } public HttpResponse receiveResponseHeader() throws HttpException, IOException { assertOpen(); HttpResponse response = (HttpResponse) this.responseParser.parse(); if (response.getStatusLine().getStatusCode() >= 200) { this.metrics.incrementResponseCount(); } return response; } public void receiveResponseEntity(final HttpResponse response) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } assertOpen(); HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response); response.setEntity(entity); } protected boolean isEof() { return this.eofSensor != null && this.eofSensor.isEof(); } public boolean isStale() { if (!isOpen()) { return true; } if (isEof()) { return true; } try { this.inbuffer.isDataAvailable(1); return isEof(); } catch (IOException ex) { return true; } } public HttpConnectionMetrics getMetrics() { return this.metrics; } }
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.impl; import org.apache.ogt.http.ConnectionReuseStrategy; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.HttpConnection; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.TokenIterator; import org.apache.ogt.http.message.BasicTokenIterator; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.protocol.HttpContext; /** * Default implementation of a strategy deciding about connection re-use. * The default implementation first checks some basics, for example * whether the connection is still open or whether the end of the * request entity can be determined without closing the connection. * If these checks pass, the tokens in the <code>Connection</code> header will * be examined. In the absence of a <code>Connection</code> header, the * non-standard but commonly used <code>Proxy-Connection</code> header takes * it's role. A token <code>close</code> indicates that the connection cannot * be reused. If there is no such token, a token <code>keep-alive</code> * indicates that the connection should be re-used. If neither token is found, * or if there are no <code>Connection</code> headers, the default policy for * the HTTP version is applied. Since <code>HTTP/1.1</code>, connections are * re-used by default. Up until <code>HTTP/1.0</code>, connections are not * re-used by default. * * @since 4.0 */ public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy { public DefaultConnectionReuseStrategy() { super(); } // see interface ConnectionReuseStrategy public boolean keepAlive(final HttpResponse response, final HttpContext context) { if (response == null) { throw new IllegalArgumentException ("HTTP response may not be null."); } if (context == null) { throw new IllegalArgumentException ("HTTP context may not be null."); } HttpConnection conn = (HttpConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn != null && !conn.isOpen()) return false; // do NOT check for stale connection, that is an expensive operation // Check for a self-terminating entity. If the end of the entity will // be indicated by closing the connection, there is no keep-alive. HttpEntity entity = response.getEntity(); ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); if (entity != null) { if (entity.getContentLength() < 0) { if (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0)) { // if the content length is not known and is not chunk // encoded, the connection cannot be reused return false; } } } // Check for the "Connection" header. If that is absent, check for // the "Proxy-Connection" header. The latter is an unspecified and // broken but unfortunately common extension of HTTP. HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE); if (!hit.hasNext()) hit = response.headerIterator("Proxy-Connection"); // Experimental usage of the "Connection" header in HTTP/1.0 is // documented in RFC 2068, section 19.7.1. A token "keep-alive" is // used to indicate that the connection should be persistent. // Note that the final specification of HTTP/1.1 in RFC 2616 does not // include this information. Neither is the "Connection" header // mentioned in RFC 1945, which informally describes HTTP/1.0. // // RFC 2616 specifies "close" as the only connection token with a // specific meaning: it disables persistent connections. // // The "Proxy-Connection" header is not formally specified anywhere, // but is commonly used to carry one token, "close" or "keep-alive". // The "Connection" header, on the other hand, is defined as a // sequence of tokens, where each token is a header name, and the // token "close" has the above-mentioned additional meaning. // // To get through this mess, we treat the "Proxy-Connection" header // in exactly the same way as the "Connection" header, but only if // the latter is missing. We scan the sequence of tokens for both // "close" and "keep-alive". As "close" is specified by RFC 2068, // it takes precedence and indicates a non-persistent connection. // If there is no "close" but a "keep-alive", we take the hint. if (hit.hasNext()) { try { TokenIterator ti = createTokenIterator(hit); boolean keepalive = false; while (ti.hasNext()) { final String token = ti.nextToken(); if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) { return false; } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) { // continue the loop, there may be a "close" afterwards keepalive = true; } } if (keepalive) return true; // neither "close" nor "keep-alive", use default policy } catch (ParseException px) { // invalid connection header means no persistent connection // we don't have logging in HttpCore, so the exception is lost return false; } } // default since HTTP/1.1 is persistent, before it was non-persistent return !ver.lessEquals(HttpVersion.HTTP_1_0); } /** * Creates a token iterator from a header iterator. * This method can be overridden to replace the implementation of * the token iterator. * * @param hit the header iterator * * @return the token iterator */ protected TokenIterator createTokenIterator(HeaderIterator hit) { return new BasicTokenIterator(hit); } }
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.impl; import java.util.Locale; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.ReasonPhraseCatalog; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.impl.EnglishReasonPhraseCatalog; import org.apache.ogt.http.message.BasicHttpResponse; import org.apache.ogt.http.message.BasicStatusLine; import org.apache.ogt.http.protocol.HttpContext; /** * Default factory for creating {@link HttpResponse} objects. * * @since 4.0 */ public class DefaultHttpResponseFactory implements HttpResponseFactory { /** The catalog for looking up reason phrases. */ protected final ReasonPhraseCatalog reasonCatalog; /** * Creates a new response factory with the given catalog. * * @param catalog the catalog of reason phrases */ public DefaultHttpResponseFactory(ReasonPhraseCatalog catalog) { if (catalog == null) { throw new IllegalArgumentException ("Reason phrase catalog must not be null."); } this.reasonCatalog = catalog; } /** * Creates a new response factory with the default catalog. * The default catalog is {@link EnglishReasonPhraseCatalog}. */ public DefaultHttpResponseFactory() { this(EnglishReasonPhraseCatalog.INSTANCE); } // non-javadoc, see interface HttpResponseFactory public HttpResponse newHttpResponse(final ProtocolVersion ver, final int status, HttpContext context) { if (ver == null) { throw new IllegalArgumentException("HTTP version may not be null"); } final Locale loc = determineLocale(context); final String reason = reasonCatalog.getReason(status, loc); StatusLine statusline = new BasicStatusLine(ver, status, reason); return new BasicHttpResponse(statusline, reasonCatalog, loc); } // non-javadoc, see interface HttpResponseFactory public HttpResponse newHttpResponse(final StatusLine statusline, HttpContext context) { if (statusline == null) { throw new IllegalArgumentException("Status line may not be null"); } final Locale loc = determineLocale(context); return new BasicHttpResponse(statusline, reasonCatalog, loc); } /** * Determines the locale of the response. * The implementation in this class always returns the default locale. * * @param context the context from which to determine the locale, or * <code>null</code> to use the default locale * * @return the locale for the response, never <code>null</code> */ protected Locale determineLocale(HttpContext context) { return Locale.getDefault(); } }
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.impl.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.entity.ContentLengthStrategy; import org.apache.ogt.http.impl.io.ChunkedOutputStream; import org.apache.ogt.http.impl.io.ContentLengthOutputStream; import org.apache.ogt.http.impl.io.IdentityOutputStream; import org.apache.ogt.http.io.SessionOutputBuffer; /** * HTTP entity serializer. * <p> * This entity serializer currently supports "chunked" and "identitiy" * transfer-coding and content length delimited content. * <p> * This class relies on a specific implementation of * {@link ContentLengthStrategy} to determine the content length or transfer * encoding of the entity. * <p> * This class writes out the content of {@link HttpEntity} to the data stream * using a transfer coding based on properties on the HTTP message. * * @since 4.0 */ public class EntitySerializer { private final ContentLengthStrategy lenStrategy; public EntitySerializer(final ContentLengthStrategy lenStrategy) { super(); if (lenStrategy == null) { throw new IllegalArgumentException("Content length strategy may not be null"); } this.lenStrategy = lenStrategy; } /** * Creates a transfer codec based on properties of the given HTTP message * and returns {@link OutputStream} instance that transparently encodes * output data as it is being written out to the output stream. * <p> * This method is called by the public * {@link #serialize(SessionOutputBuffer, HttpMessage, HttpEntity)}. * * @param outbuffer the session output buffer. * @param message the HTTP message. * @return output stream. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ protected OutputStream doSerialize( final SessionOutputBuffer outbuffer, final HttpMessage message) throws HttpException, IOException { long len = this.lenStrategy.determineLength(message); if (len == ContentLengthStrategy.CHUNKED) { return new ChunkedOutputStream(outbuffer); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityOutputStream(outbuffer); } else { return new ContentLengthOutputStream(outbuffer, len); } } /** * Writes out the content of the given HTTP entity to the session output * buffer based on properties of the given HTTP message. * * @param outbuffer the output session buffer. * @param message the HTTP message. * @param entity the HTTP entity to be written out. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ public void serialize( final SessionOutputBuffer outbuffer, final HttpMessage message, final HttpEntity entity) throws HttpException, IOException { if (outbuffer == null) { throw new IllegalArgumentException("Session output buffer may not be null"); } if (message == null) { throw new IllegalArgumentException("HTTP message may not be null"); } if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } OutputStream outstream = doSerialize(outbuffer, message); entity.writeTo(outstream); outstream.close(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.entity; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.entity.ContentLengthStrategy; import org.apache.ogt.http.protocol.HTTP; /** * The strict implementation of the content length strategy. This class * will throw {@link ProtocolException} if it encounters an unsupported * transfer encoding or a malformed <code>Content-Length</code> header * value. * <p> * This class recognizes "chunked" and "identitiy" transfer-coding only. * * @since 4.0 */ public class StrictContentLengthStrategy implements ContentLengthStrategy { public StrictContentLengthStrategy() { super(); } public long determineLength(final HttpMessage message) throws HttpException { if (message == null) { throw new IllegalArgumentException("HTTP message may not be null"); } // Although Transfer-Encoding is specified as a list, in practice // it is either missing or has the single value "chunked". So we // treat it as a single-valued header here. Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); if (transferEncodingHeader != null) { String s = transferEncodingHeader.getValue(); if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) { if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) { throw new ProtocolException( "Chunked transfer encoding not allowed for " + message.getProtocolVersion()); } return CHUNKED; } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) { return IDENTITY; } else { throw new ProtocolException( "Unsupported transfer encoding: " + s); } } else if (contentLengthHeader != null) { String s = contentLengthHeader.getValue(); try { long len = Long.parseLong(s); return len; } catch (NumberFormatException e) { throw new ProtocolException("Invalid content length: " + s); } } else { return IDENTITY; } } }
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.impl.entity; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.entity.ContentLengthStrategy; import org.apache.ogt.http.params.CoreProtocolPNames; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HTTP; /** * The lax implementation of the content length strategy. This class will ignore * unrecognized transfer encodings and malformed <code>Content-Length</code> * header values if the {@link CoreProtocolPNames#STRICT_TRANSFER_ENCODING} * parameter of the given message is not set or set to <code>false</code>. * <p> * This class recognizes "chunked" and "identitiy" transfer-coding only. * <p> * The following parameters can be used to customize the behavior of this class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li> * </ul> * * @since 4.0 */ public class LaxContentLengthStrategy implements ContentLengthStrategy { public LaxContentLengthStrategy() { super(); } public long determineLength(final HttpMessage message) throws HttpException { if (message == null) { throw new IllegalArgumentException("HTTP message may not be null"); } HttpParams params = message.getParams(); boolean strict = params.isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING); Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING); Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN); // We use Transfer-Encoding if present and ignore Content-Length. // RFC2616, 4.4 item number 3 if (transferEncodingHeader != null) { HeaderElement[] encodings = null; try { encodings = transferEncodingHeader.getElements(); } catch (ParseException px) { throw new ProtocolException ("Invalid Transfer-Encoding header value: " + transferEncodingHeader, px); } if (strict) { // Currently only chunk and identity are supported for (int i = 0; i < encodings.length; i++) { String encoding = encodings[i].getName(); if (encoding != null && encoding.length() > 0 && !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING) && !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) { throw new ProtocolException("Unsupported transfer encoding: " + encoding); } } } // The chunked encoding must be the last one applied RFC2616, 14.41 int len = encodings.length; if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) { return IDENTITY; } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase( encodings[len - 1].getName()))) { return CHUNKED; } else { if (strict) { throw new ProtocolException("Chunk-encoding must be the last one applied"); } return IDENTITY; } } else if (contentLengthHeader != null) { long contentlen = -1; Header[] headers = message.getHeaders(HTTP.CONTENT_LEN); if (strict && headers.length > 1) { throw new ProtocolException("Multiple content length headers"); } for (int i = headers.length - 1; i >= 0; i--) { Header header = headers[i]; try { contentlen = Long.parseLong(header.getValue()); break; } catch (NumberFormatException e) { if (strict) { throw new ProtocolException("Invalid content length: " + header.getValue()); } } // See if we can have better luck with another header, if present } if (contentlen >= 0) { return contentlen; } else { return IDENTITY; } } else { return IDENTITY; } } }
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.impl.entity; import java.io.IOException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.entity.BasicHttpEntity; import org.apache.ogt.http.entity.ContentLengthStrategy; import org.apache.ogt.http.impl.io.ChunkedInputStream; import org.apache.ogt.http.impl.io.ContentLengthInputStream; import org.apache.ogt.http.impl.io.IdentityInputStream; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.protocol.HTTP; /** * HTTP entity deserializer. * <p> * This entity deserializer supports "chunked" and "identitiy" transfer-coding * and content length delimited content. * <p> * This class relies on a specific implementation of * {@link ContentLengthStrategy} to determine the content length or transfer * encoding of the entity. * <p> * This class generates an instance of {@link HttpEntity} based on * properties of the message. The content of the entity will be decoded * transparently for the consumer. * * @since 4.0 */ public class EntityDeserializer { private final ContentLengthStrategy lenStrategy; public EntityDeserializer(final ContentLengthStrategy lenStrategy) { super(); if (lenStrategy == null) { throw new IllegalArgumentException("Content length strategy may not be null"); } this.lenStrategy = lenStrategy; } /** * Creates a {@link BasicHttpEntity} based on properties of the given * message. The content of the entity is created by wrapping * {@link SessionInputBuffer} with a content decoder depending on the * transfer mechanism used by the message. * <p> * This method is called by the public * {@link #deserialize(SessionInputBuffer, HttpMessage)}. * * @param inbuffer the session input buffer. * @param message the message. * @return HTTP entity. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ protected BasicHttpEntity doDeserialize( final SessionInputBuffer inbuffer, final HttpMessage message) throws HttpException, IOException { BasicHttpEntity entity = new BasicHttpEntity(); long len = this.lenStrategy.determineLength(message); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); entity.setContent(new ChunkedInputStream(inbuffer)); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); entity.setContent(new IdentityInputStream(inbuffer)); } else { entity.setChunked(false); entity.setContentLength(len); entity.setContent(new ContentLengthInputStream(inbuffer, len)); } Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } return entity; } /** * Creates an {@link HttpEntity} based on properties of the given message. * The content of the entity is created by wrapping * {@link SessionInputBuffer} with a content decoder depending on the * transfer mechanism used by the message. * <p> * The content of the entity is NOT retrieved by this method. * * @param inbuffer the session input buffer. * @param message the message. * @return HTTP entity. * @throws HttpException in case of HTTP protocol violation. * @throws IOException in case of an I/O error. */ public HttpEntity deserialize( final SessionInputBuffer inbuffer, final HttpMessage message) throws HttpException, IOException { if (inbuffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } if (message == null) { throw new IllegalArgumentException("HTTP message may not be null"); } return doDeserialize(inbuffer, 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.ogt.http.impl; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestFactory; import org.apache.ogt.http.MethodNotSupportedException; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest; import org.apache.ogt.http.message.BasicHttpRequest; /** * Default factory for creating {@link HttpRequest} objects. * * @since 4.0 */ public class DefaultHttpRequestFactory implements HttpRequestFactory { private static final String[] RFC2616_COMMON_METHODS = { "GET" }; private static final String[] RFC2616_ENTITY_ENC_METHODS = { "POST", "PUT" }; private static final String[] RFC2616_SPECIAL_METHODS = { "HEAD", "OPTIONS", "DELETE", "TRACE", "CONNECT" }; public DefaultHttpRequestFactory() { super(); } private static boolean isOneOf(final String[] methods, final String method) { for (int i = 0; i < methods.length; i++) { if (methods[i].equalsIgnoreCase(method)) { return true; } } return false; } public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } } public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException { if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(method, uri); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(method, uri); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(method, uri); } else { throw new MethodNotSupportedException(method + " method not supported"); } } }
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.impl; import java.util.HashMap; import org.apache.ogt.http.HttpConnectionMetrics; import org.apache.ogt.http.io.HttpTransportMetrics; /** * Default implementation of the {@link HttpConnectionMetrics} interface. * * @since 4.0 */ public class HttpConnectionMetricsImpl implements HttpConnectionMetrics { public static final String REQUEST_COUNT = "http.request-count"; public static final String RESPONSE_COUNT = "http.response-count"; public static final String SENT_BYTES_COUNT = "http.sent-bytes-count"; public static final String RECEIVED_BYTES_COUNT = "http.received-bytes-count"; private final HttpTransportMetrics inTransportMetric; private final HttpTransportMetrics outTransportMetric; private long requestCount = 0; private long responseCount = 0; /** * The cache map for all metrics values. */ private HashMap metricsCache; public HttpConnectionMetricsImpl( final HttpTransportMetrics inTransportMetric, final HttpTransportMetrics outTransportMetric) { super(); this.inTransportMetric = inTransportMetric; this.outTransportMetric = outTransportMetric; } /* ------------------ Public interface method -------------------------- */ public long getReceivedBytesCount() { if (this.inTransportMetric != null) { return this.inTransportMetric.getBytesTransferred(); } else { return -1; } } public long getSentBytesCount() { if (this.outTransportMetric != null) { return this.outTransportMetric.getBytesTransferred(); } else { return -1; } } public long getRequestCount() { return this.requestCount; } public void incrementRequestCount() { this.requestCount++; } public long getResponseCount() { return this.responseCount; } public void incrementResponseCount() { this.responseCount++; } public Object getMetric(final String metricName) { Object value = null; if (this.metricsCache != null) { value = this.metricsCache.get(metricName); } if (value == null) { if (REQUEST_COUNT.equals(metricName)) { value = new Long(requestCount); } else if (RESPONSE_COUNT.equals(metricName)) { value = new Long(responseCount); } else if (RECEIVED_BYTES_COUNT.equals(metricName)) { if (this.inTransportMetric != null) { return new Long(this.inTransportMetric.getBytesTransferred()); } else { return null; } } else if (SENT_BYTES_COUNT.equals(metricName)) { if (this.outTransportMetric != null) { return new Long(this.outTransportMetric.getBytesTransferred()); } else { return null; } } } return value; } public void setMetric(final String metricName, Object obj) { if (this.metricsCache == null) { this.metricsCache = new HashMap(); } this.metricsCache.put(metricName, obj); } public void reset() { if (this.outTransportMetric != null) { this.outTransportMetric.reset(); } if (this.inTransportMetric != null) { this.inTransportMetric.reset(); } this.requestCount = 0; this.responseCount = 0; this.metricsCache = 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.ogt.http; import org.apache.ogt.http.util.CharArrayBuffer; /** * An HTTP header which is already formatted. * For example when headers are received, the original formatting * can be preserved. This allows for the header to be sent without * another formatting step. * * @since 4.0 */ public interface FormattedHeader extends Header { /** * Obtains the buffer with the formatted header. * The returned buffer MUST NOT be modified. * * @return the formatted header, in a buffer that must not be modified */ CharArrayBuffer getBuffer(); /** * Obtains the start of the header value in the {@link #getBuffer buffer}. * By accessing the value in the buffer, creation of a temporary string * can be avoided. * * @return index of the first character of the header value * in the buffer returned by {@link #getBuffer getBuffer}. */ int getValuePos(); }
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 org.apache.ogt.http.util.ExceptionUtils; /** * Signals that an HTTP exception has occurred. * * @since 4.0 */ public class HttpException extends Exception { private static final long serialVersionUID = -5437299376222011036L; /** * Creates a new HttpException with a <tt>null</tt> detail message. */ public HttpException() { super(); } /** * Creates a new HttpException with the specified detail message. * * @param message the exception detail message */ public HttpException(final String message) { super(message); } /** * Creates a new HttpException 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 HttpException(final String message, final Throwable cause) { super(message); ExceptionUtils.initCause(this, 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.ogt.http; import java.util.Locale; /** * Interface for obtaining reason phrases for HTTP status codes. * * @since 4.0 */ public interface ReasonPhraseCatalog { /** * Obtains the reason phrase for a status code. * The optional context allows for catalogs that detect * the language for the reason phrase. * * @param status the status code, in the range 100-599 * @param loc the preferred locale for the reason phrase * * @return the reason phrase, or <code>null</code> if unknown */ public String getReason(int status, Locale loc); }
Java
/* * $Header: $ * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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 request with an entity. * * @since 4.0 */ public interface HttpEntityEnclosingRequest extends HttpRequest { /** * Tells if this request should use the expect-continue handshake. * The expect continue handshake gives the server a chance to decide * whether to accept the entity enclosing request before the possibly * lengthy entity is sent across the wire. * @return true if the expect continue handshake should be used, false if * not. */ boolean expectContinue(); /** * Associates the entity with this request. * * @param entity the entity to send. */ void setEntity(HttpEntity entity); /** * Returns the entity associated with this request. * * @return entity */ HttpEntity getEntity(); }
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; /** * Signals that an HTTP protocol violation has occurred. * For example a malformed status line or headers, a missing message body, etc. * * * @since 4.0 */ public class ProtocolException extends HttpException { private static final long serialVersionUID = -2143571074341228994L; /** * Creates a new ProtocolException with a <tt>null</tt> detail message. */ public ProtocolException() { super(); } /** * Creates a new ProtocolException with the specified detail message. * * @param message The exception detail message */ public ProtocolException(String message) { super(message); } /** * Creates a new ProtocolException 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 ProtocolException(String message, 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.ogt.http; /** * Signals a parse error. * Parse errors when receiving a message will typically trigger * {@link ProtocolException}. Parse errors that do not occur during * protocol execution may be handled differently. * This is an unchecked exception, since there are cases where * the data to be parsed has been generated and is therefore * known to be parseable. * * @since 4.0 */ public class ParseException extends RuntimeException { private static final long serialVersionUID = -7288819855864183578L; /** * Creates a {@link ParseException} without details. */ public ParseException() { super(); } /** * Creates a {@link ParseException} with a detail message. * * @param message the exception detail message, or <code>null</code> */ public ParseException(String message) { super(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.ogt.http; import java.io.IOException; /** * Signals that the connection has been closed unexpectedly. * * @since 4.0 */ public class ConnectionClosedException extends IOException { private static final long serialVersionUID = 617550366255636674L; /** * Creates a new ConnectionClosedException with the specified detail message. * * @param message The exception detail message */ public ConnectionClosedException(final String message) { super(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.ogt.http; import java.io.IOException; import org.apache.ogt.http.protocol.HttpContext; /** * HTTP protocol interceptor is a routine that implements a specific aspect of * the HTTP protocol. Usually protocol interceptors are expected to act upon * one specific header or a group of related headers of the incoming message * or populate the outgoing message with one specific header or a group of * related headers. * <p> * Protocol Interceptors can also manipulate content entities enclosed with messages. * Usually this is accomplished by using the 'Decorator' pattern where a wrapper * entity class is used to decorate the original entity. * <p> * Protocol interceptors must be implemented as thread-safe. Similarly to * servlets, protocol interceptors should not use instance variables unless * access to those variables is synchronized. * * @since 4.0 */ public interface HttpRequestInterceptor { /** * Processes a request. * On the client side, this step is performed before the request is * sent to the server. On the server side, this step is performed * on incoming messages before the message body is evaluated. * * @param request the request to preprocess * @param context the context for the request * * @throws HttpException in case of an HTTP protocol violation * @throws IOException in case of an I/O error */ void process(HttpRequest request, 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.util; import java.io.Serializable; /** * A resizable byte array. * * @since 4.0 */ public final class ByteArrayBuffer implements Serializable { private static final long serialVersionUID = 4359112959524048036L; private byte[] buffer; private int len; /** * Creates an instance of {@link ByteArrayBuffer} with the given initial * capacity. * * @param capacity the capacity */ public ByteArrayBuffer(int capacity) { super(); if (capacity < 0) { throw new IllegalArgumentException("Buffer capacity may not be negative"); } this.buffer = new byte[capacity]; } private void expand(int newlen) { byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)]; System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); this.buffer = newbuffer; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final byte[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends <code>b</code> byte to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional byte. * * @param b the byte to be appended. */ public void append(int b) { int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = (byte)b; this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased if necessary to accommodate all <code>len</code> chars. * <p> * The chars are converted to bytes using simple cast. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final char[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int oldlen = this.len; int newlen = oldlen + len; if (newlen > this.buffer.length) { expand(newlen); } for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { this.buffer[i2] = (byte) b[i1]; } this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * char array buffer starting at index <code>off</code>. The capacity * of the buffer is increased if necessary to accommodate all * <code>len</code> chars. * <p> * The chars are converted to bytes using simple cast. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final CharArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer(), off, len); } /** * Clears content of the buffer. The underlying byte array is not resized. */ public void clear() { this.len = 0; } /** * Converts the content of this buffer to an array of bytes. * * @return byte array */ public byte[] toByteArray() { byte[] b = new byte[this.len]; if (this.len > 0) { System.arraycopy(this.buffer, 0, b, 0, this.len); } return b; } /** * Returns the <code>byte</code> value in this buffer at the specified * index. The index argument must be greater than or equal to * <code>0</code>, and less than the length of this buffer. * * @param i the index of the desired byte value. * @return the byte value at the specified index. * @throws IndexOutOfBoundsException if <code>index</code> is * negative or greater than or equal to {@link #length()}. */ public int byteAt(int i) { return this.buffer[i]; } /** * Returns the current capacity. The capacity is the amount of storage * available for newly appended bytes, beyond which an allocation * will occur. * * @return the current capacity */ public int capacity() { return this.buffer.length; } /** * Returns the length of the buffer (byte count). * * @return the length of the buffer */ public int length() { return this.len; } /** * Ensures that the capacity is at least equal to the specified minimum. * If the current capacity is less than the argument, then a new internal * array is allocated with greater capacity. If the <code>required</code> * argument is non-positive, this method takes no action. * * @param required the minimum required capacity. * * @since 4.1 */ public void ensureCapacity(int required) { if (required <= 0) { return; } int available = this.buffer.length - this.len; if (required > available) { expand(this.len + required); } } /** * Returns reference to the underlying byte array. * * @return the byte array. */ public byte[] buffer() { return this.buffer; } /** * Sets the length of the buffer. The new length value is expected to be * less than the current capacity and greater than or equal to * <code>0</code>. * * @param len the new length * @throws IndexOutOfBoundsException if the * <code>len</code> argument is greater than the current * capacity of the buffer or less than <code>0</code>. */ public void setLength(int len) { if (len < 0 || len > this.buffer.length) { throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); } this.len = len; } /** * Returns <code>true</code> if this buffer is empty, that is, its * {@link #length()} is equal to <code>0</code>. * @return <code>true</code> if this buffer is empty, <code>false</code> * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns <code>true</code> if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return <code>true</code> if this buffer is full, <code>false</code> * otherwise. */ public boolean isFull() { return this.len == this.buffer.length; } /** * Returns the index within this buffer of the first occurrence of the * specified byte, starting the search at the specified * <code>beginIndex</code> and finishing at <code>endIndex</code>. * If no such byte occurs in this buffer within the specified bounds, * <code>-1</code> is returned. * <p> * There is no restriction on the value of <code>beginIndex</code> and * <code>endIndex</code>. If <code>beginIndex</code> is negative, * it has the same effect as if it were zero. If <code>endIndex</code> is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the <code>beginIndex</code> is greater than * the <code>endIndex</code>, <code>-1</code> is returned. * * @param b the byte to search for. * @param beginIndex the index to start the search from. * @param endIndex the index to finish the search at. * @return the index of the first occurrence of the byte in the buffer * within the given bounds, or <code>-1</code> if the byte does * not occur. * * @since 4.1 */ public int indexOf(byte b, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == b) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified byte, starting the search at <code>0</code> and finishing * at {@link #length()}. If no such byte occurs in this buffer within * those bounds, <code>-1</code> is returned. * * @param b the byte to search for. * @return the index of the first occurrence of the byte in the * buffer, or <code>-1</code> if the byte does not occur. * * @since 4.1 */ public int indexOf(byte b) { return indexOf(b, 0, this.len); } }
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.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.protocol.HTTP; /** * Static helpers for dealing with {@link HttpEntity}s. * * @since 4.0 */ public final class EntityUtils { private EntityUtils() { } /** * Ensures that the entity content is fully consumed and the content stream, if exists, * is closed. * * @param entity * @throws IOException if an error occurs reading the input stream * * @since 4.1 */ public static void consume(final HttpEntity entity) throws IOException { if (entity == null) { return; } if (entity.isStreaming()) { InputStream instream = entity.getContent(); if (instream != null) { instream.close(); } } } /** * Read the contents of an entity and return it as a byte array. * * @param entity * @return byte array containing the entity content. May be null if * {@link HttpEntity#getContent()} is null. * @throws IOException if an error occurs reading the input stream * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE */ public static byte[] toByteArray(final HttpEntity entity) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); byte[] tmp = new byte[4096]; int l; while((l = instream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } finally { instream.close(); } } /** * Obtains character set of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null */ public static String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; } /** * Obtains mime type of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null * * @since 4.1 */ public static String getContentMimeType(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String mimeType = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { mimeType = values[0].getName(); } } return mimeType; } /** * Get the entity content as a String, using the provided default character set * if none is found in the entity. * If defaultCharset is null, the default "ISO-8859-1" is used. * * @param entity must not be null * @param defaultCharset character set to be applied if none found in the entity * @return the entity content as a String. May be null if * {@link HttpEntity#getContent()} is null. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream */ public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } String charset = getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } } /** * Read the contents of an entity and return it as a String. * The content is converted using the character set from the entity (if any), * failing that, "ISO-8859-1" is used. * * @param entity * @return String containing the content. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream */ public static String toString(final HttpEntity entity) throws IOException, ParseException { return toString(entity, 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.ogt.http.util; /** * A set of utility methods to help produce consistent * {@link Object#equals equals} and {@link Object#hashCode hashCode} methods. * * * @since 4.0 */ public final class LangUtils { public static final int HASH_SEED = 17; public static final int HASH_OFFSET = 37; /** Disabled default constructor. */ private LangUtils() { } public static int hashCode(final int seed, final int hashcode) { return seed * HASH_OFFSET + hashcode; } public static int hashCode(final int seed, final boolean b) { return hashCode(seed, b ? 1 : 0); } public static int hashCode(final int seed, final Object obj) { return hashCode(seed, obj != null ? obj.hashCode() : 0); } /** * Check if two objects are equal. * * @param obj1 first object to compare, may be {@code null} * @param obj2 second object to compare, may be {@code null} * @return {@code true} if the objects are equal or both null */ public static boolean equals(final Object obj1, final Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); } /** * Check if two object arrays are equal. * <p> * <ul> * <li>If both parameters are null, return {@code true}</li> * <li>If one parameter is null, return {@code false}</li> * <li>If the array lengths are different, return {@code false}</li> * <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li> * <li>Return {@code true}</li> * </ul> * * @param a1 first array to compare, may be {@code null} * @param a2 second array to compare, may be {@code null} * @return {@code true} if the arrays are equal or both null */ public static boolean equals(final Object[] a1, final Object[] a2) { if (a1 == null) { if (a2 == null) { return true; } else { return false; } } else { if (a2 != null && a1.length == a2.length) { for (int i = 0; i < a1.length; i++) { if (!equals(a1[i], a2[i])) { return false; } } return true; } else { 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.ogt.http.util; import java.io.Serializable; import org.apache.ogt.http.protocol.HTTP; /** * A resizable char array. * * @since 4.0 */ public final class CharArrayBuffer implements Serializable { private static final long serialVersionUID = -6208952725094867135L; private char[] buffer; private int len; /** * Creates an instance of {@link CharArrayBuffer} with the given initial * capacity. * * @param capacity the capacity */ public CharArrayBuffer(int capacity) { super(); if (capacity < 0) { throw new IllegalArgumentException("Buffer capacity may not be negative"); } this.buffer = new char[capacity]; } private void expand(int newlen) { char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)]; System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); this.buffer = newbuffer; } /** * Appends <code>len</code> chars to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> chars. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final char[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends chars of the given string to this buffer. The capacity of the * buffer is increased, if necessary, to accommodate all chars. * * @param str the string. */ public void append(String str) { if (str == null) { str = "null"; } int strlen = str.length(); int newlen = this.len + strlen; if (newlen > this.buffer.length) { expand(newlen); } str.getChars(0, strlen, this.buffer, this.len); this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * buffer starting at index <code>off</code>. The capacity of the * destination buffer is increased, if necessary, to accommodate all * <code>len</code> chars. * * @param b the source buffer to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final CharArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer, off, len); } /** * Appends all chars to this buffer from the given source buffer starting * at index <code>0</code>. The capacity of the destination buffer is * increased, if necessary, to accommodate all {@link #length()} chars. * * @param b the source buffer to be appended. */ public void append(final CharArrayBuffer b) { if (b == null) { return; } append(b.buffer,0, b.len); } /** * Appends <code>ch</code> char to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional char. * * @param ch the char to be appended. */ public void append(char ch) { int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = ch; this.len = newlen; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * <p> * The bytes are converted to chars using simple cast. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final byte[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int oldlen = this.len; int newlen = oldlen + len; if (newlen > this.buffer.length) { expand(newlen); } for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { this.buffer[i2] = (char) (b[i1] & 0xff); } this.len = newlen; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * <p> * The bytes are converted to chars using simple cast. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final ByteArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer(), off, len); } /** * Appends chars of the textual representation of the given object to this * buffer. The capacity of the buffer is increased, if necessary, to * accommodate all chars. * * @param obj the object. */ public void append(final Object obj) { append(String.valueOf(obj)); } /** * Clears content of the buffer. The underlying char array is not resized. */ public void clear() { this.len = 0; } /** * Converts the content of this buffer to an array of chars. * * @return char array */ public char[] toCharArray() { char[] b = new char[this.len]; if (this.len > 0) { System.arraycopy(this.buffer, 0, b, 0, this.len); } return b; } /** * Returns the <code>char</code> value in this buffer at the specified * index. The index argument must be greater than or equal to * <code>0</code>, and less than the length of this buffer. * * @param i the index of the desired char value. * @return the char value at the specified index. * @throws IndexOutOfBoundsException if <code>index</code> is * negative or greater than or equal to {@link #length()}. */ public char charAt(int i) { return this.buffer[i]; } /** * Returns reference to the underlying char array. * * @return the char array. */ public char[] buffer() { return this.buffer; } /** * Returns the current capacity. The capacity is the amount of storage * available for newly appended chars, beyond which an allocation will * occur. * * @return the current capacity */ public int capacity() { return this.buffer.length; } /** * Returns the length of the buffer (char count). * * @return the length of the buffer */ public int length() { return this.len; } /** * Ensures that the capacity is at least equal to the specified minimum. * If the current capacity is less than the argument, then a new internal * array is allocated with greater capacity. If the <code>required</code> * argument is non-positive, this method takes no action. * * @param required the minimum required capacity. */ public void ensureCapacity(int required) { if (required <= 0) { return; } int available = this.buffer.length - this.len; if (required > available) { expand(this.len + required); } } /** * Sets the length of the buffer. The new length value is expected to be * less than the current capacity and greater than or equal to * <code>0</code>. * * @param len the new length * @throws IndexOutOfBoundsException if the * <code>len</code> argument is greater than the current * capacity of the buffer or less than <code>0</code>. */ public void setLength(int len) { if (len < 0 || len > this.buffer.length) { throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); } this.len = len; } /** * Returns <code>true</code> if this buffer is empty, that is, its * {@link #length()} is equal to <code>0</code>. * @return <code>true</code> if this buffer is empty, <code>false</code> * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns <code>true</code> if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return <code>true</code> if this buffer is full, <code>false</code> * otherwise. */ public boolean isFull() { return this.len == this.buffer.length; } /** * Returns the index within this buffer of the first occurrence of the * specified character, starting the search at the specified * <code>beginIndex</code> and finishing at <code>endIndex</code>. * If no such character occurs in this buffer within the specified bounds, * <code>-1</code> is returned. * <p> * There is no restriction on the value of <code>beginIndex</code> and * <code>endIndex</code>. If <code>beginIndex</code> is negative, * it has the same effect as if it were zero. If <code>endIndex</code> is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the <code>beginIndex</code> is greater than * the <code>endIndex</code>, <code>-1</code> is returned. * * @param ch the char to search for. * @param beginIndex the index to start the search from. * @param endIndex the index to finish the search at. * @return the index of the first occurrence of the character in the buffer * within the given bounds, or <code>-1</code> if the character does * not occur. */ public int indexOf(int ch, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == ch) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified character, starting the search at <code>0</code> and finishing * at {@link #length()}. If no such character occurs in this buffer within * those bounds, <code>-1</code> is returned. * * @param ch the char to search for. * @return the index of the first occurrence of the character in the * buffer, or <code>-1</code> if the character does not occur. */ public int indexOf(int ch) { return indexOf(ch, 0, this.len); } /** * Returns a substring of this buffer. The substring begins at the specified * <code>beginIndex</code> and extends to the character at index * <code>endIndex - 1</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception StringIndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of this * buffer, or <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substring(int beginIndex, int endIndex) { return new String(this.buffer, beginIndex, endIndex - beginIndex); } /** * Returns a substring of this buffer with leading and trailing whitespace * omitted. The substring begins with the first non-whitespace character * from <code>beginIndex</code> and extends to the last * non-whitespace character with the index lesser than * <code>endIndex</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of this * buffer, or <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substringTrimmed(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex); } while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) { beginIndex++; } while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) { endIndex--; } return new String(this.buffer, beginIndex, endIndex - beginIndex); } public String toString() { return new String(this.buffer, 0, this.len); } }
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.util; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.ArrayList; /** * Provides access to version information for HTTP components. * Static methods are used to extract version information from property * files that are automatically packaged with HTTP component release JARs. * <br/> * All available version information is provided in strings, where * the string format is informal and subject to change without notice. * Version information is provided for debugging output and interpretation * by humans, not for automated processing in applications. * * @since 4.0 */ public class VersionInfo { /** A string constant for unavailable information. */ public final static String UNAVAILABLE = "UNAVAILABLE"; /** The filename of the version information files. */ public final static String VERSION_PROPERTY_FILE = "version.properties"; // the property names public final static String PROPERTY_MODULE = "info.module"; public final static String PROPERTY_RELEASE = "info.release"; public final static String PROPERTY_TIMESTAMP = "info.timestamp"; /** The package that contains the version information. */ private final String infoPackage; /** The module from the version info. */ private final String infoModule; /** The release from the version info. */ private final String infoRelease; /** The timestamp from the version info. */ private final String infoTimestamp; /** The classloader from which the version info was obtained. */ private final String infoClassloader; /** * Instantiates version information. * * @param pckg the package * @param module the module, or <code>null</code> * @param release the release, or <code>null</code> * @param time the build time, or <code>null</code> * @param clsldr the class loader, or <code>null</code> */ protected VersionInfo(String pckg, String module, String release, String time, String clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } infoPackage = pckg; infoModule = (module != null) ? module : UNAVAILABLE; infoRelease = (release != null) ? release : UNAVAILABLE; infoTimestamp = (time != null) ? time : UNAVAILABLE; infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE; } /** * Obtains the package name. * The package name identifies the module or informal unit. * * @return the package name, never <code>null</code> */ public final String getPackage() { return infoPackage; } /** * Obtains the name of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the module name, never <code>null</code> */ public final String getModule() { return infoModule; } /** * Obtains the release of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the release version, never <code>null</code> */ public final String getRelease() { return infoRelease; } /** * Obtains the timestamp of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the timestamp, never <code>null</code> */ public final String getTimestamp() { return infoTimestamp; } /** * Obtains the classloader used to read the version information. * This is just the <code>toString</code> output of the classloader, * since the version information should not keep a reference to * the classloader itself. That could prevent garbage collection. * * @return the classloader description, never <code>null</code> */ public final String getClassloader() { return infoClassloader; } /** * Provides the version information in human-readable format. * * @return a string holding this version information */ public String toString() { StringBuffer sb = new StringBuffer (20 + infoPackage.length() + infoModule.length() + infoRelease.length() + infoTimestamp.length() + infoClassloader.length()); sb.append("VersionInfo(") .append(infoPackage).append(':').append(infoModule); // If version info is missing, a single "UNAVAILABLE" for the module // is sufficient. Everything else just clutters the output. if (!UNAVAILABLE.equals(infoRelease)) sb.append(':').append(infoRelease); if (!UNAVAILABLE.equals(infoTimestamp)) sb.append(':').append(infoTimestamp); sb.append(')'); if (!UNAVAILABLE.equals(infoClassloader)) sb.append('@').append(infoClassloader); return sb.toString(); } /** * Loads version information for a list of packages. * * @param pckgs the packages for which to load version info * @param clsldr the classloader to load from, or * <code>null</code> for the thread context classloader * * @return the version information for all packages found, * never <code>null</code> */ public final static VersionInfo[] loadVersionInfo(String[] pckgs, ClassLoader clsldr) { if (pckgs == null) { throw new IllegalArgumentException ("Package identifier list must not be null."); } ArrayList vil = new ArrayList(pckgs.length); for (int i=0; i<pckgs.length; i++) { VersionInfo vi = loadVersionInfo(pckgs[i], clsldr); if (vi != null) vil.add(vi); } return (VersionInfo[]) vil.toArray(new VersionInfo[vil.size()]); } /** * Loads version information for a package. * * @param pckg the package for which to load version information, * for example "org.apache.ogt.http". * The package name should NOT end with a dot. * @param clsldr the classloader to load from, or * <code>null</code> for the thread context classloader * * @return the version information for the argument package, or * <code>null</code> if not available */ public final static VersionInfo loadVersionInfo(final String pckg, ClassLoader clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } if (clsldr == null) clsldr = Thread.currentThread().getContextClassLoader(); Properties vip = null; // version info properties, if available try { // org.apache.ogt.http becomes // org/apache/http/version.properties InputStream is = clsldr.getResourceAsStream (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE); if (is != null) { try { Properties props = new Properties(); props.load(is); vip = props; } finally { is.close(); } } } catch (IOException ex) { // shamelessly munch this exception } VersionInfo result = null; if (vip != null) result = fromMap(pckg, vip, clsldr); return result; } /** * Instantiates version information from properties. * * @param pckg the package for the version information * @param info the map from string keys to string values, * for example {@link java.util.Properties} * @param clsldr the classloader, or <code>null</code> * * @return the version information */ protected final static VersionInfo fromMap(String pckg, Map info, ClassLoader clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } String module = null; String release = null; String timestamp = null; if (info != null) { module = (String) info.get(PROPERTY_MODULE); if ((module != null) && (module.length() < 1)) module = null; release = (String) info.get(PROPERTY_RELEASE); if ((release != null) && ((release.length() < 1) || (release.equals("${pom.version}")))) release = null; timestamp = (String) info.get(PROPERTY_TIMESTAMP); if ((timestamp != null) && ((timestamp.length() < 1) || (timestamp.equals("${mvn.timestamp}"))) ) timestamp = null; } // if info String clsldrstr = null; if (clsldr != null) clsldrstr = clsldr.toString(); return new VersionInfo(pckg, module, release, timestamp, clsldrstr); } } // class VersionInfo
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.util; import java.lang.reflect.Method; /** * The home for utility methods that handle various exception-related tasks. * * * @since 4.0 */ public final class ExceptionUtils { /** A reference to Throwable's initCause method, or null if it's not there in this JVM */ static private final Method INIT_CAUSE_METHOD = getInitCauseMethod(); /** * Returns a <code>Method<code> allowing access to * {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable}, * or <code>null</code> if the method * does not exist. * * @return A <code>Method<code> for <code>Throwable.initCause</code>, or * <code>null</code> if unavailable. */ static private Method getInitCauseMethod() { try { Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (NoSuchMethodException e) { return null; } } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. */ public static void initCause(Throwable throwable, Throwable cause) { if (INIT_CAUSE_METHOD != null) { try { INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause }); } catch (Exception e) { // Well, with no logging, the only option is to munch the exception } } } private ExceptionUtils() { } }
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.util; import java.io.UnsupportedEncodingException; import org.apache.ogt.http.protocol.HTTP; /** * The home for utility methods that handle various encoding tasks. * * * @since 4.0 */ public final class EncodingUtils { /** * Converts the byte array of HTTP content characters to a string. If * the specified charset is not supported, default system encoding * is used. * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @param charset the desired character encoding * @return The result of the conversion. */ public static String getString( final byte[] data, int offset, int length, String charset ) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return new String(data, offset, length, charset); } catch (UnsupportedEncodingException e) { return new String(data, offset, length); } } /** * Converts the byte array of HTTP content characters to a string. If * the specified charset is not supported, default system encoding * is used. * * @param data the byte array to be encoded * @param charset the desired character encoding * @return The result of the conversion. */ public static String getString(final byte[] data, final String charset) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } return getString(data, 0, data.length, charset); } /** * Converts the specified string to a byte array. If the charset is not supported the * default system charset is used. * * @param data the string to be encoded * @param charset the desired character encoding * @return The resulting byte array. */ public static byte[] getBytes(final String data, final String charset) { if (data == null) { throw new IllegalArgumentException("data may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return data.getBytes(charset); } catch (UnsupportedEncodingException e) { return data.getBytes(); } } /** * Converts the specified string to byte array of ASCII characters. * * @param data the string to be encoded * @return The string as a byte array. */ public static byte[] getAsciiBytes(final String data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return data.getBytes(HTTP.US_ASCII); } catch (UnsupportedEncodingException e) { throw new Error("HttpClient requires ASCII support"); } } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data, int offset, int length) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return new String(data, offset, length, HTTP.US_ASCII); } catch (UnsupportedEncodingException e) { throw new Error("HttpClient requires ASCII support"); } } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } return getAsciiString(data, 0, data.length); } /** * This class should not be instantiated. */ private EncodingUtils() { } }
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 org.apache.ogt.http.params.HttpParams; /** * HTTP messages consist of requests from client to server and responses * from server to client. * <pre> * HTTP-message = Request | Response ; HTTP/1.1 messages * </pre> * <p> * HTTP messages use the generic message format of RFC 822 for * transferring entities (the payload of the message). Both types * of message consist of a start-line, zero or more header fields * (also known as "headers"), an empty line (i.e., a line with nothing * preceding the CRLF) indicating the end of the header fields, * and possibly a message-body. * </p> * <pre> * generic-message = start-line * *(message-header CRLF) * CRLF * [ message-body ] * start-line = Request-Line | Status-Line * </pre> * * @since 4.0 */ public interface HttpMessage { /** * Returns the protocol version this message is compatible with. */ ProtocolVersion getProtocolVersion(); /** * Checks if a certain header is present in this message. Header values are * ignored. * * @param name the header name to check for. * @return true if at least one header with this name is present. */ boolean containsHeader(String name); /** * Returns all the headers with a specified name of this message. Header values * are ignored. Headers are orderd in the sequence they will be sent over a * connection. * * @param name the name of the headers to return. * @return the headers whose name property equals <code>name</code>. */ Header[] getHeaders(String name); /** * Returns the first header with a specified name of this message. Header * values are ignored. If there is more than one matching header in the * message the first element of {@link #getHeaders(String)} is returned. * If there is no matching header in the message <code>null</code> is * returned. * * @param name the name of the header to return. * @return the first header whose name property equals <code>name</code> * or <code>null</code> if no such header could be found. */ Header getFirstHeader(String name); /** * Returns the last header with a specified name of this message. Header values * are ignored. If there is more than one matching header in the message the * last element of {@link #getHeaders(String)} is returned. If there is no * matching header in the message <code>null</code> is returned. * * @param name the name of the header to return. * @return the last header whose name property equals <code>name</code>. * or <code>null</code> if no such header could be found. */ Header getLastHeader(String name); /** * Returns all the headers of this message. Headers are orderd in the sequence * they will be sent over a connection. * * @return all the headers of this message */ Header[] getAllHeaders(); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param header the header to append. */ void addHeader(Header header); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param name the name of the header. * @param value the value of the header. */ void addHeader(String name, String value); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param header the header to set. */ void setHeader(Header header); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param name the name of the header. * @param value the value of the header. */ void setHeader(String name, String value); /** * Overwrites all the headers in the message. * * @param headers the array of headers to set. */ void setHeaders(Header[] headers); /** * Removes a header from this message. * * @param header the header to remove. */ void removeHeader(Header header); /** * Removes all headers with a certain name from this message. * * @param name The name of the headers to remove. */ void removeHeaders(String name); /** * Returns an iterator of all the headers. * * @return Iterator that returns Header objects in the sequence they are * sent over a connection. */ HeaderIterator headerIterator(); /** * Returns an iterator of the headers with a given name. * * @param name the name of the headers over which to iterate, or * <code>null</code> for all headers * * @return Iterator that returns Header objects with the argument name * in the sequence they are sent over a connection. */ HeaderIterator headerIterator(String name); /** * Returns the parameters effective for this message as set by * {@link #setParams(HttpParams)}. */ HttpParams getParams(); /** * Provides parameters to be used for the processing of this message. * @param params the parameters */ void setParams(HttpParams 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.ogt.http; import java.io.IOException; /** * A server-side HTTP connection, which can be used for receiving * requests and sending responses. * * @since 4.0 */ public interface HttpServerConnection extends HttpConnection { /** * Receives the request line and all headers available from this connection. * The caller should examine the returned request and decide if to receive a * request entity as well. * * @return a new HttpRequest object whose request line and headers are * initialized. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpRequest receiveRequestHeader() throws HttpException, IOException; /** * Receives the next request entity available from this connection and attaches it to * an existing request. * @param request the request to attach the entity to. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void receiveRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException; /** * Sends the response line and headers of a response over this connection. * @param response the response whose headers to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendResponseHeader(HttpResponse response) throws HttpException, IOException; /** * Sends the response entity of a response over this connection. * @param response the response whose entity to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendResponseEntity(HttpResponse response) throws HttpException, IOException; /** * Sends all pending buffered data over this connection. * @throws IOException in case of an I/O error */ void flush() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * The Request-Line begins with a method token, followed by the * Request-URI and the protocol version, and ending with CRLF. The * elements are separated by SP characters. No CR or LF is allowed * except in the final CRLF sequence. * <pre> * Request-Line = Method SP Request-URI SP HTTP-Version CRLF * </pre> * * @since 4.0 */ public interface RequestLine { String getMethod(); ProtocolVersion getProtocolVersion(); String getUri(); }
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; import java.io.Serializable; import java.util.Locale; import org.apache.ogt.http.util.CharArrayBuffer; import org.apache.ogt.http.util.LangUtils; /** * Holds all of the variables needed to describe an HTTP connection to a host. * This includes remote host name, port and scheme. * * * @since 4.0 */ //@Immutable public final class HttpHost implements Cloneable, Serializable { private static final long serialVersionUID = -7529410654042457626L; /** The default scheme is "http". */ public static final String DEFAULT_SCHEME_NAME = "http"; /** The host to use. */ protected final String hostname; /** The lowercase host, for {@link #equals} and {@link #hashCode}. */ protected final String lcHostname; /** The port to use. */ protected final int port; /** The scheme (lowercased) */ protected final String schemeName; /** * Creates a new {@link HttpHost HttpHost}, specifying all values. * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * <code>-1</code> indicates the scheme default port. * @param scheme the name of the scheme. * <code>null</code> indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} */ public HttpHost(final String hostname, int port, final String scheme) { super(); if (hostname == null) { throw new IllegalArgumentException("Host name may not be null"); } this.hostname = hostname; this.lcHostname = hostname.toLowerCase(Locale.ENGLISH); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ENGLISH); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; } /** * Creates a new {@link HttpHost HttpHost}, with default scheme. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * <code>-1</code> indicates the scheme default port. */ public HttpHost(final String hostname, int port) { this(hostname, port, null); } /** * Creates a new {@link HttpHost HttpHost}, with default scheme and port. * * @param hostname the hostname (IP or DNS name) */ public HttpHost(final String hostname) { this(hostname, -1, null); } /** * Copy constructor for {@link HttpHost HttpHost}. * * @param httphost the HTTP host to copy details from */ public HttpHost (final HttpHost httphost) { this(httphost.hostname, httphost.port, httphost.schemeName); } /** * Returns the host name. * * @return the host name (IP or DNS name) */ public String getHostName() { return this.hostname; } /** * Returns the port. * * @return the host port, or <code>-1</code> if not set */ public int getPort() { return this.port; } /** * Returns the scheme name. * * @return the scheme name */ public String getSchemeName() { return this.schemeName; } /** * Return the host URI, as a string. * * @return the host URI */ public String toURI() { CharArrayBuffer buffer = new CharArrayBuffer(32); buffer.append(this.schemeName); buffer.append("://"); buffer.append(this.hostname); if (this.port != -1) { buffer.append(':'); buffer.append(Integer.toString(this.port)); } return buffer.toString(); } /** * Obtains the host string, without scheme prefix. * * @return the host string, for example <code>localhost:8080</code> */ public String toHostString() { if (this.port != -1) { //the highest port number is 65535, which is length 6 with the addition of the colon CharArrayBuffer buffer = new CharArrayBuffer(this.hostname.length() + 6); buffer.append(this.hostname); buffer.append(":"); buffer.append(Integer.toString(this.port)); return buffer.toString(); } else { return this.hostname; } } public String toString() { return toURI(); } public boolean equals(final Object obj) { if (this == obj) return true; if (obj instanceof HttpHost) { HttpHost that = (HttpHost) obj; return this.lcHostname.equals(that.lcHostname) && this.port == that.port && this.schemeName.equals(that.schemeName); } else { return false; } } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.lcHostname); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.schemeName); return hash; } public Object clone() throws CloneNotSupportedException { 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.ogt.http; import java.io.IOException; /** * A client-side HTTP connection, which can be used for sending * requests and receiving responses. * * @since 4.0 */ public interface HttpClientConnection extends HttpConnection { /** * Checks if response data is available from the connection. May wait for * the specified time until some data becomes available. Note that some * implementations may completely ignore the timeout parameter. * * @param timeout the maximum time in milliseconds to wait for data * @return true if data is available; false if there was no data available * even after waiting for <code>timeout</code> milliseconds. * @throws IOException if an error happens on the connection */ boolean isResponseAvailable(int timeout) throws IOException; /** * Sends the request line and all headers over the connection. * @param request the request whose headers to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestHeader(HttpRequest request) throws HttpException, IOException; /** * Sends the request entity over the connection. * @param request the request whose entity to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException; /** * Receives the request line and headers of the next response available from * this connection. The caller should examine the HttpResponse object to * find out if it should try to receive a response entity as well. * * @return a new HttpResponse object with status line and headers * initialized. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpResponse receiveResponseHeader() throws HttpException, IOException; /** * Receives the next response entity available from this connection and * attaches it to an existing HttpResponse object. * * @param response the response to attach the entity to * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void receiveResponseEntity(HttpResponse response) throws HttpException, IOException; /** * Writes out all pending buffered data over the open connection. * * @throws IOException in case of an I/O error */ void flush() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.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; /** * Signals a truncated chunk in a chunked stream. * * @since 4.1 */ public class TruncatedChunkException extends MalformedChunkCodingException { private static final long serialVersionUID = -23506263930279460L; /** * Creates a TruncatedChunkException with the specified detail message. * * @param message The exception detail message */ public TruncatedChunkException(final String message) { super(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.ogt.http; /** * Represents an HTTP header field. * * <p>The HTTP header fields follow the same generic format as * that given in Section 3.1 of RFC 822. Each header field consists * of a name followed by a colon (":") and the field value. Field names * are case-insensitive. The field value MAY be preceded by any amount * of LWS, though a single SP is preferred. * *<pre> * message-header = field-name ":" [ field-value ] * field-name = token * field-value = *( field-content | LWS ) * field-content = &lt;the OCTETs making up the field-value * and consisting of either *TEXT or combinations * of token, separators, and quoted-string&gt; *</pre> * * @since 4.0 */ public interface Header { /** * Get the name of the Header. * * @return the name of the Header, never {@code null} */ String getName(); /** * Get the value of the Header. * * @return the value of the Header, may be {@code null} */ String getValue(); /** * Parses the value. * * @return an array of {@link HeaderElement} entries, may be empty, but is never {@code null} * @throws ParseException */ HeaderElement[] getElements() throws ParseException; }
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; /** * One element of an HTTP {@link Header header} value consisting of * a name / value pair and a number of optional name / value parameters. * <p> * Some HTTP headers (such as the set-cookie header) have values that * can be decomposed into multiple elements. Such headers must be in the * following form: * </p> * <pre> * header = [ element ] *( "," [ element ] ) * element = name [ "=" [ value ] ] *( ";" [ param ] ) * param = name [ "=" [ value ] ] * * name = token * value = ( token | quoted-string ) * * token = 1*&lt;any char except "=", ",", ";", &lt;"&gt; and * white space&gt; * quoted-string = &lt;"&gt; *( text | quoted-char ) &lt;"&gt; * text = any char except &lt;"&gt; * quoted-char = "\" char * </pre> * <p> * Any amount of white space is allowed between any part of the * header, element or param and is ignored. A missing value in any * element or param will be stored as the empty {@link String}; * if the "=" is also missing <var>null</var> will be stored instead. * * @since 4.0 */ public interface HeaderElement { /** * Returns header element name. * * @return header element name */ String getName(); /** * Returns header element value. * * @return header element value */ String getValue(); /** * Returns an array of name / value pairs. * * @return array of name / value pairs */ NameValuePair[] getParameters(); /** * Returns the first parameter with the given name. * * @param name parameter name * * @return name / value pair */ NameValuePair getParameterByName(String name); /** * Returns the total count of parameters. * * @return parameter count */ int getParameterCount(); /** * Returns parameter with the given index. * * @param index * @return name / value pair */ NameValuePair getParameter(int index); }
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; /** * The point of access to the statistics of an {@link HttpConnection}. * * @since 4.0 */ public interface HttpConnectionMetrics { /** * Returns the number of requests transferred over the connection, * 0 if not available. */ long getRequestCount(); /** * Returns the number of responses transferred over the connection, * 0 if not available. */ long getResponseCount(); /** * Returns the number of bytes transferred over the connection, * 0 if not available. */ long getSentBytesCount(); /** * Returns the number of bytes transferred over the connection, * 0 if not available. */ long getReceivedBytesCount(); /** * Return the value for the specified metric. * *@param metricName the name of the metric to query. * *@return the object representing the metric requested, * <code>null</code> if the metric cannot not found. */ Object getMetric(String metricName); /** * Resets the counts * */ void reset(); }
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.io.Serializable; /** * Represents an HTTP version. HTTP uses a "major.minor" numbering * scheme to indicate versions of the protocol. * <p> * The version of an HTTP message is indicated by an HTTP-Version field * in the first line of the message. * </p> * <pre> * HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT * </pre> * * @since 4.0 */ public final class HttpVersion extends ProtocolVersion implements Serializable { private static final long serialVersionUID = -5856653513894415344L; /** The protocol name. */ public static final String HTTP = "HTTP"; /** HTTP protocol version 0.9 */ public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9); /** HTTP protocol version 1.0 */ public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0); /** HTTP protocol version 1.1 */ public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1); /** * Create an HTTP protocol version designator. * * @param major the major version number of the HTTP protocol * @param minor the minor version number of the HTTP protocol * * @throws IllegalArgumentException if either major or minor version number is negative */ public HttpVersion(int major, int minor) { super(HTTP, major, minor); } /** * Obtains a specific HTTP version. * * @param major the major version * @param minor the minor version * * @return an instance of {@link HttpVersion} with the argument version */ public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } if (major == 1) { if (minor == 0) { return HTTP_1_0; } if (minor == 1) { return HTTP_1_1; } } if ((major == 0) && (minor == 9)) { return HTTP_0_9; } // argument checking is done in the constructor return new HttpVersion(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.ogt.http; import org.apache.ogt.http.protocol.HttpContext; /** * Interface for deciding whether a connection can be re-used for * subsequent requests and should be kept alive. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface ConnectionReuseStrategy { /** * Decides whether a connection can be kept open after a request. * If this method returns <code>false</code>, the caller MUST * close the connection to correctly comply with the HTTP protocol. * If it returns <code>true</code>, the caller SHOULD attempt to * keep the connection open for reuse with another request. * <br/> * One can use the HTTP context to retrieve additional objects that * may be relevant for the keep-alive strategy: the actual HTTP * connection, the original HTTP request, target host if known, * number of times the connection has been reused already and so on. * <br/> * If the connection is already closed, <code>false</code> is returned. * The stale connection check MUST NOT be triggered by a * connection reuse strategy. * * @param response * The last response received over that connection. * @param context the context in which the connection is being * used. * * @return <code>true</code> if the connection is allowed to be reused, or * <code>false</code> if it MUST NOT be reused */ boolean keepAlive(HttpResponse response, HttpContext context); }
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.io.Serializable; import org.apache.ogt.http.util.CharArrayBuffer; /** * Represents a protocol version. The "major.minor" numbering * scheme is used to indicate versions of the protocol. * <p> * This class defines a protocol version as a combination of * protocol name, major version number, and minor version number. * Note that {@link #equals} and {@link #hashCode} are defined as * final here, they cannot be overridden in derived classes. * </p> * * @since 4.0 */ public class ProtocolVersion implements Serializable, Cloneable { private static final long serialVersionUID = 8950662842175091068L; /** Name of the protocol. */ protected final String protocol; /** Major version number of the protocol */ protected final int major; /** Minor version number of the protocol */ protected final int minor; /** * Create a protocol version designator. * * @param protocol the name of the protocol, for example "HTTP" * @param major the major version number of the protocol * @param minor the minor version number of the protocol */ public ProtocolVersion(String protocol, int major, int minor) { if (protocol == null) { throw new IllegalArgumentException ("Protocol name must not be null."); } if (major < 0) { throw new IllegalArgumentException ("Protocol major version number must not be negative."); } if (minor < 0) { throw new IllegalArgumentException ("Protocol minor version number may not be negative"); } this.protocol = protocol; this.major = major; this.minor = minor; } /** * Returns the name of the protocol. * * @return the protocol name */ public final String getProtocol() { return protocol; } /** * Returns the major version number of the protocol. * * @return the major version number. */ public final int getMajor() { return major; } /** * Returns the minor version number of the HTTP protocol. * * @return the minor version number. */ public final int getMinor() { return minor; } /** * Obtains a specific version of this protocol. * This can be used by derived classes to instantiate themselves instead * of the base class, and to define constants for commonly used versions. * <br/> * The default implementation in this class returns <code>this</code> * if the version matches, and creates a new {@link ProtocolVersion} * otherwise. * * @param major the major version * @param minor the minor version * * @return a protocol version with the same protocol name * and the argument version */ public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } // argument checking is done in the constructor return new ProtocolVersion(this.protocol, major, minor); } /** * Obtains a hash code consistent with {@link #equals}. * * @return the hashcode of this protocol version */ public final int hashCode() { return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor; } /** * Checks equality of this protocol version with an object. * The object is equal if it is a protocl version with the same * protocol name, major version number, and minor version number. * The specific class of the object is <i>not</i> relevant, * instances of derived classes with identical attributes are * equal to instances of the base class and vice versa. * * @param obj the object to compare with * * @return <code>true</code> if the argument is the same protocol version, * <code>false</code> otherwise */ public final boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ProtocolVersion)) { return false; } ProtocolVersion that = (ProtocolVersion) obj; return ((this.protocol.equals(that.protocol)) && (this.major == that.major) && (this.minor == that.minor)); } /** * Checks whether this protocol can be compared to another one. * Only protocol versions with the same protocol name can be * {@link #compareToVersion compared}. * * @param that the protocol version to consider * * @return <code>true</code> if {@link #compareToVersion compareToVersion} * can be called with the argument, <code>false</code> otherwise */ public boolean isComparable(ProtocolVersion that) { return (that != null) && this.protocol.equals(that.protocol); } /** * Compares this protocol version with another one. * Only protocol versions with the same protocol name can be compared. * This method does <i>not</i> define a total ordering, as it would be * required for {@link java.lang.Comparable}. * * @param that the protocl version to compare with * * @return a negative integer, zero, or a positive integer * as this version is less than, equal to, or greater than * the argument version. * * @throws IllegalArgumentException * if the argument has a different protocol name than this object, * or if the argument is <code>null</code> */ public int compareToVersion(ProtocolVersion that) { if (that == null) { throw new IllegalArgumentException ("Protocol version must not be null."); } if (!this.protocol.equals(that.protocol)) { throw new IllegalArgumentException ("Versions for different protocols cannot be compared. " + this + " " + that); } int delta = getMajor() - that.getMajor(); if (delta == 0) { delta = getMinor() - that.getMinor(); } return delta; } /** * Tests if this protocol version is greater or equal to the given one. * * @param version the version against which to check this version * * @return <code>true</code> if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as greater or equal, * <code>false</code> otherwise */ public final boolean greaterEquals(ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) >= 0); } /** * Tests if this protocol version is less or equal to the given one. * * @param version the version against which to check this version * * @return <code>true</code> if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as less or equal, * <code>false</code> otherwise */ public final boolean lessEquals(ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) <= 0); } /** * Converts this protocol version to a string. * * @return a protocol version string, like "HTTP/1.1" */ public String toString() { CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(this.protocol); buffer.append('/'); buffer.append(Integer.toString(this.major)); buffer.append('.'); buffer.append(Integer.toString(this.minor)); return buffer.toString(); } public Object clone() throws CloneNotSupportedException { 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.ogt.http; import java.io.IOException; /** * Signals a malformed chunked stream. * * @since 4.0 */ public class MalformedChunkCodingException extends IOException { private static final long serialVersionUID = 2158560246948994524L; /** * Creates a MalformedChunkCodingException without a detail message. */ public MalformedChunkCodingException() { super(); } /** * Creates a MalformedChunkCodingException with the specified detail message. * * @param message The exception detail message */ public MalformedChunkCodingException(final String message) { super(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.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A generic streamed, non-repeatable entity that obtains its content * from an {@link InputStream}. * * @since 4.0 */ public class BasicHttpEntity extends AbstractHttpEntity { private InputStream content; private long length; /** * Creates a new basic entity. * The content is initially missing, the content length * is set to a negative number. */ public BasicHttpEntity() { super(); this.length = -1; } public long getContentLength() { return this.length; } /** * Obtains the content, once only. * * @return the content, if this is the first call to this method * since {@link #setContent setContent} has been called * * @throws IllegalStateException * if the content has not been provided */ public InputStream getContent() throws IllegalStateException { if (this.content == null) { throw new IllegalStateException("Content has not been provided"); } return this.content; } /** * Tells that this entity is not repeatable. * * @return <code>false</code> */ public boolean isRepeatable() { return false; } /** * Specifies the length of the content. * * @param len the number of bytes in the content, or * a negative number to indicate an unknown length */ public void setContentLength(long len) { this.length = len; } /** * Specifies the content. * * @param instream the stream to return with the next call to * {@link #getContent getContent} */ public void setContent(final InputStream instream) { this.content = instream; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = getContent(); try { int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } } finally { instream.close(); } } public boolean isStreaming() { return this.content != null; } /** * Closes the content InputStream. * * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { if (content != null) { content.close(); // reads to the end of the 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.ogt.http.entity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; /** * Represents a strategy to determine length of the enclosed content entity * based on properties of the HTTP message. * * @since 4.0 */ public interface ContentLengthStrategy { public static final int IDENTITY = -1; public static final int CHUNKED = -2; /** * Returns length of the given message in bytes. The returned value * must be a non-negative number, {@link #IDENTITY} if the end of the * message will be delimited by the end of connection, or {@link #CHUNKED} * if the message is chunk coded * * @param message * @return content length, {@link #IDENTITY}, or {@link #CHUNKED} * * @throws HttpException in case of HTTP protocol violation */ long determineLength(HttpMessage message) 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.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.util.EntityUtils; /** * A wrapping entity that buffers it content if necessary. * The buffered entity is always repeatable. * If the wrapped entity is repeatable itself, calls are passed through. * If the wrapped entity is not repeatable, the content is read into a * buffer once and provided from there as often as required. * * @since 4.0 */ public class BufferedHttpEntity extends HttpEntityWrapper { private final byte[] buffer; /** * Creates a new buffered entity wrapper. * * @param entity the entity to wrap, not null * @throws IllegalArgumentException if wrapped is null */ public BufferedHttpEntity(final HttpEntity entity) throws IOException { super(entity); if (!entity.isRepeatable() || entity.getContentLength() < 0) { this.buffer = EntityUtils.toByteArray(entity); } else { this.buffer = null; } } public long getContentLength() { if (this.buffer != null) { return this.buffer.length; } else { return wrappedEntity.getContentLength(); } } public InputStream getContent() throws IOException { if (this.buffer != null) { return new ByteArrayInputStream(this.buffer); } else { return wrappedEntity.getContent(); } } /** * Tells that this entity does not have to be chunked. * * @return <code>false</code> */ public boolean isChunked() { return (buffer == null) && wrappedEntity.isChunked(); } /** * Tells that this entity is repeatable. * * @return <code>true</code> */ public boolean isRepeatable() { return true; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } if (this.buffer != null) { outstream.write(this.buffer); } else { wrappedEntity.writeTo(outstream); } } // non-javadoc, see interface HttpEntity public boolean isStreaming() { return (buffer == null) && wrappedEntity.isStreaming(); } } // class BufferedHttpEntity
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.entity; import java.io.IOException; import java.io.OutputStream; /** * An abstract entity content producer. *<p>Content producers are expected to be able to produce their * content multiple times</p> * * @since 4.0 */ public interface ContentProducer { void writeTo(OutputStream outstream) throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** * A streamed entity that obtains its content from a {@link Serializable}. * The content obtained from the {@link Serializable} instance can * optionally be buffered in a byte array in order to make the * entity self-contained and repeatable. * * @since 4.0 */ public class SerializableEntity extends AbstractHttpEntity { private byte[] objSer; private Serializable objRef; /** * Creates new instance of this class. * * @param ser input * @param bufferize tells whether the content should be * stored in an internal buffer * @throws IOException in case of an I/O error */ public SerializableEntity(Serializable ser, boolean bufferize) throws IOException { super(); if (ser == null) { throw new IllegalArgumentException("Source object may not be null"); } if (bufferize) { createBytes(ser); } else { this.objRef = ser; } } private void createBytes(Serializable ser) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(ser); out.flush(); this.objSer = baos.toByteArray(); } public InputStream getContent() throws IOException, IllegalStateException { if (this.objSer == null) { createBytes(this.objRef); } return new ByteArrayInputStream(this.objSer); } public long getContentLength() { if (this.objSer == null) { return -1; } else { return this.objSer.length; } } public boolean isRepeatable() { return true; } public boolean isStreaming() { return this.objSer == null; } public void writeTo(OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } if (this.objSer == null) { ObjectOutputStream out = new ObjectOutputStream(outstream); out.writeObject(this.objRef); out.flush(); } else { outstream.write(this.objSer); 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.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Entity that delegates the process of content generation * to a {@link ContentProducer}. * * @since 4.0 */ public class EntityTemplate extends AbstractHttpEntity { private final ContentProducer contentproducer; public EntityTemplate(final ContentProducer contentproducer) { super(); if (contentproducer == null) { throw new IllegalArgumentException("Content producer may not be null"); } this.contentproducer = contentproducer; } public long getContentLength() { return -1; } public InputStream getContent() { throw new UnsupportedOperationException("Entity template does not implement getContent()"); } public boolean isRepeatable() { return true; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } this.contentproducer.writeTo(outstream); } public boolean isStreaming() { 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.ogt.http.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.message.BasicHeader; import org.apache.ogt.http.protocol.HTTP; /** * Abstract base class for entities. * Provides the commonly used attributes for streamed and self-contained * implementations of {@link HttpEntity HttpEntity}. * * @since 4.0 */ public abstract class AbstractHttpEntity implements HttpEntity { protected Header contentType; protected Header contentEncoding; protected boolean chunked; /** * Protected default constructor. * The contentType, contentEncoding and chunked attributes of the created object are set to * <code>null</code>, <code>null</code> and <code>false</code>, respectively. */ protected AbstractHttpEntity() { super(); } /** * Obtains the Content-Type header. * The default implementation returns the value of the * {@link #contentType contentType} attribute. * * @return the Content-Type header, or <code>null</code> */ public Header getContentType() { return this.contentType; } /** * Obtains the Content-Encoding header. * The default implementation returns the value of the * {@link #contentEncoding contentEncoding} attribute. * * @return the Content-Encoding header, or <code>null</code> */ public Header getContentEncoding() { return this.contentEncoding; } /** * Obtains the 'chunked' flag. * The default implementation returns the value of the * {@link #chunked chunked} attribute. * * @return the 'chunked' flag */ public boolean isChunked() { return this.chunked; } /** * Specifies the Content-Type header. * The default implementation sets the value of the * {@link #contentType contentType} attribute. * * @param contentType the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentType(final Header contentType) { this.contentType = contentType; } /** * Specifies the Content-Type header, as a string. * The default implementation calls * {@link #setContentType(Header) setContentType(Header)}. * * @param ctString the new Content-Type header, or * <code>null</code> to unset */ public void setContentType(final String ctString) { Header h = null; if (ctString != null) { h = new BasicHeader(HTTP.CONTENT_TYPE, ctString); } setContentType(h); } /** * Specifies the Content-Encoding header. * The default implementation sets the value of the * {@link #contentEncoding contentEncoding} attribute. * * @param contentEncoding the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentEncoding(final Header contentEncoding) { this.contentEncoding = contentEncoding; } /** * Specifies the Content-Encoding header, as a string. * The default implementation calls * {@link #setContentEncoding(Header) setContentEncoding(Header)}. * * @param ceString the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentEncoding(final String ceString) { Header h = null; if (ceString != null) { h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString); } setContentEncoding(h); } /** * Specifies the 'chunked' flag. * <p> * Note that the chunked setting is a hint only. * If using HTTP/1.0, chunking is never performed. * Otherwise, even if chunked is false, HttpClient must * use chunk coding if the entity content length is * unknown (-1). * <p> * The default implementation sets the value of the * {@link #chunked chunked} attribute. * * @param b the new 'chunked' flag */ public void setChunked(boolean b) { this.chunked = b; } /** * The default implementation does not consume anything. * * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A self contained, repeatable entity that obtains its content from a file. * * @since 4.0 */ public class FileEntity extends AbstractHttpEntity implements Cloneable { protected final File file; public FileEntity(final File file, final String contentType) { super(); if (file == null) { throw new IllegalArgumentException("File may not be null"); } this.file = file; setContentType(contentType); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.file.length(); } public InputStream getContent() throws IOException { return new FileInputStream(this.file); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = new FileInputStream(this.file); try { byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } outstream.flush(); } finally { instream.close(); } } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { // File instance is considered immutable // No need to make a copy of it return super.clone(); } } // class FileEntity
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.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.ogt.http.protocol.HTTP; /** * A self contained, repeatable entity that obtains its content from * a {@link String}. * * @since 4.0 */ public class StringEntity extends AbstractHttpEntity implements Cloneable { protected final byte[] content; /** * Creates a StringEntity with the specified content, mimetype and charset * * @param string content to be used. Not {@code null}. * @param mimeType mime type to be used. May be {@code null}, in which case the default is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" * @param charset character set to be used. May be {@code null}, in which case the default is {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1" * * @since 4.1 * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string, String mimeType, String charset) throws UnsupportedEncodingException { super(); if (string == null) { throw new IllegalArgumentException("Source string may not be null"); } if (mimeType == null) { mimeType = HTTP.PLAIN_TEXT_TYPE; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } this.content = string.getBytes(charset); setContentType(mimeType + HTTP.CHARSET_PARAM + charset); } /** * Creates a StringEntity with the specified content and charset. * <br/> * The mime type defaults to {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain". * * @param string content to be used. Not {@code null}. * @param charset character set to be used. May be {@code null}, in which case the default is {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1" * * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string, String charset) throws UnsupportedEncodingException { this(string, null, charset); } /** * Creates a StringEntity with the specified content and charset. * <br/> * The charset defaults to {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1". * <br/> * The mime type defaults to {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain". * * @param string content to be used. Not {@code null}. * * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string) throws UnsupportedEncodingException { this(string, null); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() throws IOException { return new ByteArrayInputStream(this.content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(this.content); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class StringEntity
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.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A streamed, non-repeatable entity that obtains its content from * an {@link InputStream}. * * @since 4.0 */ public class InputStreamEntity extends AbstractHttpEntity { private final static int BUFFER_SIZE = 2048; private final InputStream content; private final long length; public InputStreamEntity(final InputStream instream, long length) { super(); if (instream == null) { throw new IllegalArgumentException("Source input stream may not be null"); } this.content = instream; this.length = length; } public boolean isRepeatable() { return false; } public long getContentLength() { return this.length; } public InputStream getContent() throws IOException { return this.content; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = this.content; try { byte[] buffer = new byte[BUFFER_SIZE]; int l; if (this.length < 0) { // consume until EOF while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); } } else { // consume no more than length long remaining = this.length; while (remaining > 0) { l = instream.read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); if (l == -1) { break; } outstream.write(buffer, 0, l); remaining -= l; } } } finally { instream.close(); } } public boolean isStreaming() { return true; } /** * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { // If the input stream is from a connection, closing it will read to // the end of the content. Otherwise, we don't care what it does. this.content.close(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A self contained, repeatable entity that obtains its content from a byte array. * * @since 4.0 */ public class ByteArrayEntity extends AbstractHttpEntity implements Cloneable { protected final byte[] content; public ByteArrayEntity(final byte[] b) { super(); if (b == null) { throw new IllegalArgumentException("Source byte array may not be null"); } this.content = b; } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() { return new ByteArrayInputStream(this.content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(this.content); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class ByteArrayEntity
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.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; /** * Base class for wrapping entities. * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all * calls to it. Implementations of wrapping entities can derive * from this class and need to override only those methods that * should not be delegated to the wrapped entity. * * @since 4.0 */ public class HttpEntityWrapper implements HttpEntity { /** The wrapped entity. */ protected HttpEntity wrappedEntity; /** * Creates a new entity wrapper. * * @param wrapped the entity to wrap, not null * @throws IllegalArgumentException if wrapped is null */ public HttpEntityWrapper(HttpEntity wrapped) { super(); if (wrapped == null) { throw new IllegalArgumentException ("wrapped entity must not be null"); } wrappedEntity = wrapped; } // constructor public boolean isRepeatable() { return wrappedEntity.isRepeatable(); } public boolean isChunked() { return wrappedEntity.isChunked(); } public long getContentLength() { return wrappedEntity.getContentLength(); } public Header getContentType() { return wrappedEntity.getContentType(); } public Header getContentEncoding() { return wrappedEntity.getContentEncoding(); } public InputStream getContent() throws IOException { return wrappedEntity.getContent(); } public void writeTo(OutputStream outstream) throws IOException { wrappedEntity.writeTo(outstream); } public boolean isStreaming() { return wrappedEntity.isStreaming(); } /** * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { wrappedEntity.consumeContent(); } }
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.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * An entity that can be sent or received with an HTTP message. * Entities can be found in some * {@link HttpEntityEnclosingRequest requests} and in * {@link HttpResponse responses}, where they are optional. * <p> * There are three distinct types of entities in HttpCore, * depending on where their {@link #getContent content} originates: * <ul> * <li><b>streamed</b>: The content is received from a stream, or * generated on the fly. In particular, this category includes * entities being received from a {@link HttpConnection connection}. * {@link #isStreaming Streamed} entities are generally not * {@link #isRepeatable repeatable}. * </li> * <li><b>self-contained</b>: The content is in memory or obtained by * means that are independent from a connection or other entity. * Self-contained entities are generally {@link #isRepeatable repeatable}. * </li> * <li><b>wrapping</b>: The content is obtained from another entity. * </li> * </ul> * This distinction is important for connection management with incoming * entities. For entities that are created by an application and only sent * using the HTTP components framework, the difference between streamed * and self-contained is of little importance. In that case, it is suggested * to consider non-repeatable entities as streamed, and those that are * repeatable (without a huge effort) as self-contained. * * @since 4.0 */ public interface HttpEntity { /** * Tells if the entity is capable of producing its data more than once. * A repeatable entity's getContent() and writeTo(OutputStream) methods * can be called more than once whereas a non-repeatable entity's can not. * @return true if the entity is repeatable, false otherwise. */ boolean isRepeatable(); /** * Tells about chunked encoding for this entity. * The primary purpose of this method is to indicate whether * chunked encoding should be used when the entity is sent. * For entities that are received, it can also indicate whether * the entity was received with chunked encoding. * <br/> * The behavior of wrapping entities is implementation dependent, * but should respect the primary purpose. * * @return <code>true</code> if chunked encoding is preferred for this * entity, or <code>false</code> if it is not */ boolean isChunked(); /** * Tells the length of the content, if known. * * @return the number of bytes of the content, or * a negative number if unknown. If the content length is known * but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE}, * a negative number is returned. */ long getContentLength(); /** * Obtains the Content-Type header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. It can include a * charset attribute. * * @return the Content-Type header for this entity, or * <code>null</code> if the content type is unknown */ Header getContentType(); /** * Obtains the Content-Encoding header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. * Wrapping entities that modify the content encoding should * adjust this header accordingly. * * @return the Content-Encoding header for this entity, or * <code>null</code> if the content encoding is unknown */ Header getContentEncoding(); /** * Returns a content stream of the entity. * {@link #isRepeatable Repeatable} entities are expected * to create a new instance of {@link InputStream} for each invocation * of this method and therefore can be consumed multiple times. * Entities that are not {@link #isRepeatable repeatable} are expected * to return the same {@link InputStream} instance and therefore * may not be consumed more than once. * <p> * IMPORTANT: Please note all entity implementations must ensure that * all allocated resources are properly deallocated after * the {@link InputStream#close()} method is invoked. * * @return content stream of the entity. * * @throws IOException if the stream could not be created * @throws IllegalStateException * if content stream cannot be created. * * @see #isRepeatable() */ InputStream getContent() throws IOException, IllegalStateException; /** * Writes the entity content out to the output stream. * <p> * <p> * IMPORTANT: Please note all entity implementations must ensure that * all allocated resources are properly deallocated when this method * returns. * * @param outstream the output stream to write entity content to * * @throws IOException if an I/O error occurs */ void writeTo(OutputStream outstream) throws IOException; /** * Tells whether this entity depends on an underlying stream. * Streamed entities that read data directly from the socket should * return <code>true</code>. Self-contained entities should return * <code>false</code>. Wrapping entities should delegate this call * to the wrapped entity. * * @return <code>true</code> if the entity content is streamed, * <code>false</code> otherwise */ boolean isStreaming(); // don't expect an exception here /** * This method is deprecated since version 4.1. Please use standard * java convention to ensure resource deallocation by calling * {@link InputStream#close()} on the input stream returned by * {@link #getContent()} * <p> * This method is called to indicate that the content of this entity * is no longer required. All entity implementations are expected to * release all allocated resources as a result of this method * invocation. Content streaming entities are also expected to * dispose of the remaining content, if any. Wrapping entities should * delegate this call to the wrapped entity. * <p> * This method is of particular importance for entities being * received from a {@link HttpConnection connection}. The entity * needs to be consumed completely in order to re-use the connection * with keep-alive. * * @throws IOException if an I/O error occurs. * * @deprecated Use {@link org.apache.ogt.http.util.EntityUtils#consume(HttpEntity)} * * @see #getContent() and #writeTo(OutputStream) */ void consumeContent() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.protocol.HttpContext; /** * A factory for {@link HttpResponse HttpResponse} objects. * * @since 4.0 */ public interface HttpResponseFactory { /** * Creates a new response from status line elements. * * @param ver the protocol version * @param status the status code * @param context the context from which to determine the locale * for looking up a reason phrase to the status code, or * <code>null</code> to use the default locale * * @return the new response with an initialized status line */ HttpResponse newHttpResponse(ProtocolVersion ver, int status, HttpContext context); /** * Creates a new response from a status line. * * @param statusline the status line * @param context the context from which to determine the locale * for looking up a reason phrase if the status code * is updated, or * <code>null</code> to use the default locale * * @return the new response with the argument status line */ HttpResponse newHttpResponse(StatusLine statusline, HttpContext context); }
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.util.Locale; /** * After receiving and interpreting a request message, a server responds * with an HTTP response message. * <pre> * Response = Status-Line * *(( general-header * | response-header * | entity-header ) CRLF) * CRLF * [ message-body ] * </pre> * * @since 4.0 */ public interface HttpResponse extends HttpMessage { /** * Obtains the status line of this response. * The status line can be set using one of the * {@link #setStatusLine setStatusLine} methods, * or it can be initialized in a constructor. * * @return the status line, or <code>null</code> if not yet set */ StatusLine getStatusLine(); /** * Sets the status line of this response. * * @param statusline the status line of this response */ void setStatusLine(StatusLine statusline); /** * Sets the status line of this response. * The reason phrase will be determined based on the current * {@link #getLocale locale}. * * @param ver the HTTP version * @param code the status code */ void setStatusLine(ProtocolVersion ver, int code); /** * Sets the status line of this response with a reason phrase. * * @param ver the HTTP version * @param code the status code * @param reason the reason phrase, or <code>null</code> to omit */ void setStatusLine(ProtocolVersion ver, int code, String reason); /** * Updates the status line of this response with a new status code. * The status line can only be updated if it is available. It must * have been set either explicitly or in a constructor. * <br/> * The reason phrase will be updated according to the new status code, * based on the current {@link #getLocale locale}. It can be set * explicitly using {@link #setReasonPhrase setReasonPhrase}. * * @param code the HTTP status code. * * @throws IllegalStateException * if the status line has not be set * * @see HttpStatus * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setStatusCode(int code) throws IllegalStateException; /** * Updates the status line of this response with a new reason phrase. * The status line can only be updated if it is available. It must * have been set either explicitly or in a constructor. * * @param reason the new reason phrase as a single-line string, or * <code>null</code> to unset the reason phrase * * @throws IllegalStateException * if the status line has not be set * * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setReasonPhrase(String reason) throws IllegalStateException; /** * Obtains the message entity of this response, if any. * The entity is provided by calling {@link #setEntity setEntity}. * * @return the response entity, or * <code>null</code> if there is none */ HttpEntity getEntity(); /** * Associates a response entity with this response. * * @param entity the entity to associate with this response, or * <code>null</code> to unset */ void setEntity(HttpEntity entity); /** * Obtains the locale of this response. * The locale is used to determine the reason phrase * for the {@link #setStatusCode status code}. * It can be changed using {@link #setLocale setLocale}. * * @return the locale of this response, never <code>null</code> */ Locale getLocale(); /** * Changes the locale of this response. * If there is a status line, it's reason phrase will be updated * according to the status code and new locale. * * @param loc the new locale * * @see #getLocale getLocale * @see #setStatusCode setStatusCode */ void setLocale(Locale loc); }
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 request message from a client to a server includes, within the * first line of that message, the method to be applied to the resource, * the identifier of the resource, and the protocol version in use. * <pre> * Request = Request-Line * *(( general-header * | request-header * | entity-header ) CRLF) * CRLF * [ message-body ] * </pre> * * @since 4.0 */ public interface HttpRequest extends HttpMessage { /** * Returns the request line of this request. * @return the request line. */ RequestLine getRequestLine(); }
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.util.Iterator; /** * A type-safe iterator for {@link Header} objects. * * @since 4.0 */ public interface HeaderIterator extends Iterator { /** * Indicates whether there is another header in this iteration. * * @return <code>true</code> if there is another header, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next header from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header in this iteration */ Header nextHeader(); }
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 org.apache.ogt.http.ProtocolException; /** * Signals an unsupported version of the HTTP protocol. * * @since 4.0 */ public class UnsupportedHttpVersionException extends ProtocolException { private static final long serialVersionUID = -1348448090193107031L; /** * Creates an exception without a detail message. */ public UnsupportedHttpVersionException() { super(); } /** * Creates an exception with the specified detail message. * * @param message The exception detail message */ public UnsupportedHttpVersionException(final String message) { super(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; 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; 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.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.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 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.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 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.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.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 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.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.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.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.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.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; 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.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.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.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.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.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.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.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.impl.nio.ssl; import java.io.IOException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.impl.DefaultHttpRequestFactory; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLMode; import org.apache.http.impl.nio.reactor.SSLSetupHandler; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; /** * Default implementation of {@link IOEventDispatch} interface for SSL * (encrypted) server-side HTTP connections. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.1 */ public class SSLServerIOEventDispatch implements IOEventDispatch { private static final String SSL_SESSION = "http.nio.ssl-session"; private final NHttpServiceHandler handler; private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; private final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP service handler may not be null"); } if (sslcontext == null) { throw new IllegalArgumentException("SSL context may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.handler = handler; this.params = params; this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the server protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLServerIOEventDispatch( final NHttpServiceHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return new HeapByteBufferAllocator(); } /** * Creates an instance of {@link DefaultHttpRequestFactory} to be used * by HTTP connections for creating {@link HttpRequest} objects. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link HttpRequestFactory} interface. * * @return HTTP request factory. */ protected HttpRequestFactory createHttpRequestFactory() { return new DefaultHttpRequestFactory(); } /** * Creates an instance of {@link DefaultNHttpServerConnection} based on the * given {@link IOSession}. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpServerIOTarget} interface. * * @param session the underlying SSL I/O session. * * @return newly created HTTP connection. */ protected NHttpServerIOTarget createConnection(final IOSession session) { return new DefaultNHttpServerConnection( session, createHttpRequestFactory(), createByteBufferAllocator(), this.params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. * <p> * This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } public void connected(final IOSession session) { SSLIOSession sslSession = createSSLIOSession( session, this.sslcontext, this.sslHandler); NHttpServerIOTarget conn = createConnection( sslSession); session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); session.setAttribute(SSL_SESSION, sslSession); this.handler.connected(conn); try { sslSession.bind(SSLMode.SERVER, this.params); } catch (SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void disconnected(final IOSession session) { NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn != null) { this.handler.closed(conn); } } private void ensureNotNull(final NHttpServerIOTarget conn) { if (conn == null) { throw new IllegalStateException("HTTP connection is null"); } } private void ensureNotNull(final SSLIOSession ssliosession) { if (ssliosession == null) { throw new IllegalStateException("SSL I/O session is null"); } } public void inputReady(final IOSession session) { NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); try { if (sslSession.isAppInputReady()) { conn.consumeInput(this.handler); } sslSession.inboundTransport(); } catch (IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void outputReady(final IOSession session) { NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); try { if (sslSession.isAppOutputReady()) { conn.produceOutput(this.handler); } sslSession.outboundTransport(); } catch (IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void timeout(final IOSession session) { NHttpServerIOTarget conn = (NHttpServerIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); this.handler.timeout(conn); synchronized (sslSession) { if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) { // The session failed to cleanly terminate sslSession.shutdown(); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.nio.ssl; import java.io.IOException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultNHttpClientConnection; import org.apache.http.impl.nio.reactor.SSLIOSession; import org.apache.http.impl.nio.reactor.SSLMode; import org.apache.http.impl.nio.reactor.SSLSetupHandler; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.params.HttpParams; import org.apache.http.protocol.ExecutionContext; /** * Default implementation of {@link IOEventDispatch} interface for SSL * (encrypted) client-side HTTP connections. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.1 */ public class SSLClientIOEventDispatch implements IOEventDispatch { private static final String SSL_SESSION = "http.nio.ssl-session"; private final NHttpClientHandler handler; private final SSLContext sslcontext; private final SSLSetupHandler sslHandler; private final HttpParams params; /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final SSLSetupHandler sslHandler, final HttpParams params) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP client handler may not be null"); } if (sslcontext == null) { throw new IllegalArgumentException("SSL context may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.handler = handler; this.params = params; this.sslcontext = sslcontext; this.sslHandler = sslHandler; } /** * Creates a new instance of this class to be used for dispatching I/O event * notifications to the given protocol handler using the given * {@link SSLContext}. This I/O dispatcher will transparently handle SSL * protocol aspects for HTTP connections. * * @param handler the client protocol handler. * @param sslcontext the SSL context. * @param params HTTP parameters. */ public SSLClientIOEventDispatch( final NHttpClientHandler handler, final SSLContext sslcontext, final HttpParams params) { this(handler, sslcontext, null, params); } /** * Creates an instance of {@link HeapByteBufferAllocator} to be used * by HTTP connections for allocating {@link java.nio.ByteBuffer} objects. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link ByteBufferAllocator} interface. * * @return byte buffer allocator. */ protected ByteBufferAllocator createByteBufferAllocator() { return new HeapByteBufferAllocator(); } /** * Creates an instance of {@link DefaultHttpResponseFactory} to be used * by HTTP connections for creating {@link HttpResponse} objects. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link HttpResponseFactory} interface. * * @return HTTP response factory. */ protected HttpResponseFactory createHttpResponseFactory() { return new DefaultHttpResponseFactory(); } /** * Creates an instance of {@link DefaultNHttpClientConnection} based on the * given SSL {@link IOSession}. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpClientIOTarget} interface. * * @param session the underlying SSL I/O session. * * @return newly created HTTP connection. */ protected NHttpClientIOTarget createConnection(final IOSession session) { return new DefaultNHttpClientConnection( session, createHttpResponseFactory(), createByteBufferAllocator(), this.params); } /** * Creates an instance of {@link SSLIOSession} decorating the given * {@link IOSession}. * <p> * This method can be overridden in a super class in order to provide * a different implementation of SSL I/O session. * * @param session the underlying I/O session. * @param sslcontext the SSL context. * @param sslHandler the SSL setup handler. * @return newly created SSL I/O session. */ protected SSLIOSession createSSLIOSession( final IOSession session, final SSLContext sslcontext, final SSLSetupHandler sslHandler) { return new SSLIOSession(session, sslcontext, sslHandler); } public void connected(final IOSession session) { SSLIOSession sslSession = createSSLIOSession( session, this.sslcontext, this.sslHandler); NHttpClientIOTarget conn = createConnection( sslSession); session.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); session.setAttribute(SSL_SESSION, sslSession); Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY); this.handler.connected(conn, attachment); try { sslSession.bind(SSLMode.CLIENT, this.params); } catch (SSLException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void disconnected(final IOSession session) { NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn != null) { this.handler.closed(conn); } } private void ensureNotNull(final NHttpClientIOTarget conn) { if (conn == null) { throw new IllegalStateException("HTTP connection is null"); } } private void ensureNotNull(final SSLIOSession ssliosession) { if (ssliosession == null) { throw new IllegalStateException("SSL I/O session is null"); } } public void inputReady(final IOSession session) { NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); try { if (sslSession.isAppInputReady()) { conn.consumeInput(this.handler); } sslSession.inboundTransport(); } catch (IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void outputReady(final IOSession session) { NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); try { if (sslSession.isAppOutputReady()) { conn.produceOutput(this.handler); } sslSession.outboundTransport(); } catch (IOException ex) { this.handler.exception(conn, ex); sslSession.shutdown(); } } public void timeout(final IOSession session) { NHttpClientIOTarget conn = (NHttpClientIOTarget) session.getAttribute(ExecutionContext.HTTP_CONNECTION); ensureNotNull(conn); SSLIOSession sslSession = (SSLIOSession) session.getAttribute(SSL_SESSION); ensureNotNull(sslSession); this.handler.timeout(conn); synchronized (sslSession) { if (sslSession.isOutboundDone() && !sslSession.isInboundDone()) { // The session failed to terminate cleanly sslSession.shutdown(); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.nio; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.codecs.DefaultHttpRequestParser; import org.apache.http.impl.nio.codecs.DefaultHttpResponseWriter; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParams; /** * Default implementation of the {@link NHttpServerConnection} interface. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class DefaultNHttpServerConnection extends NHttpConnectionBase implements NHttpServerIOTarget { protected final NHttpMessageParser<HttpRequest> requestParser; protected final NHttpMessageWriter<HttpResponse> responseWriter; /** * Creates a new instance of this class given the underlying I/O session. * * @param session the underlying I/O session. * @param requestFactory HTTP request factory. * @param allocator byte buffer allocator. * @param params HTTP parameters. */ public DefaultNHttpServerConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, allocator, params); if (requestFactory == null) { throw new IllegalArgumentException("Request factory may not be null"); } this.requestParser = createRequestParser(this.inbuf, requestFactory, params); this.responseWriter = createResponseWriter(this.outbuf, params); } /** * Creates an instance of {@link NHttpMessageParser} to be used * by this connection for parsing incoming {@link HttpRequest} messages. * <p> * This method can be overridden in a super class in order to provide * a different implementation of the {@link NHttpMessageParser} interface. * * @return HTTP response parser. */ protected NHttpMessageParser<HttpRequest> createRequestParser( final SessionInputBuffer buffer, final HttpRequestFactory requestFactory, final HttpParams params) { // override in derived class to specify a line parser return new DefaultHttpRequestParser(buffer, null, requestFactory, params); } /** * Creates an instance of {@link NHttpMessageWriter} to be used * by this connection for writing out outgoing {@link HttpResponse} * messages. * <p> * This method can be overridden by a super class in order to provide * a different implementation of the {@link NHttpMessageWriter} interface. * * @return HTTP response parser. */ protected NHttpMessageWriter<HttpResponse> createResponseWriter( final SessionOutputBuffer buffer, final HttpParams params) { // override in derived class to specify a line formatter return new DefaultHttpResponseWriter(buffer, null, params); } public void resetInput() { this.request = null; this.contentDecoder = null; this.requestParser.reset(); } public void resetOutput() { this.response = null; this.contentEncoder = null; this.responseWriter.reset(); } public void consumeInput(final NHttpServiceHandler handler) { if (this.status != ACTIVE) { this.session.clearEvent(EventMask.READ); return; } try { if (this.request == null) { int bytesRead; do { bytesRead = this.requestParser.fillBuffer(this.session.channel()); if (bytesRead > 0) { this.inTransportMetrics.incrementBytesTransferred(bytesRead); } this.request = this.requestParser.parse(); } while (bytesRead > 0 && this.request == null); if (this.request != null) { if (this.request instanceof HttpEntityEnclosingRequest) { // Receive incoming entity HttpEntity entity = prepareDecoder(this.request); ((HttpEntityEnclosingRequest)this.request).setEntity(entity); } this.connMetrics.incrementRequestCount(); handler.requestReceived(this); if (this.contentDecoder == null) { // No request entity is expected // Ready to receive a new request resetInput(); } } if (bytesRead == -1) { close(); } } if (this.contentDecoder != null) { handler.inputReady(this, this.contentDecoder); if (this.contentDecoder.isCompleted()) { // Request entity received // Ready to receive a new request resetInput(); } } } catch (IOException ex) { handler.exception(this, ex); } catch (HttpException ex) { resetInput(); handler.exception(this, ex); } finally { // Finally set buffered input flag this.hasBufferedInput = this.inbuf.hasData(); } } public void produceOutput(final NHttpServiceHandler handler) { try { if (this.outbuf.hasData()) { int bytesWritten = this.outbuf.flush(this.session.channel()); if (bytesWritten > 0) { this.outTransportMetrics.incrementBytesTransferred(bytesWritten); } } if (!this.outbuf.hasData()) { if (this.status == CLOSING) { this.session.close(); this.status = CLOSED; resetOutput(); return; } else { if (this.contentEncoder != null) { handler.outputReady(this, this.contentEncoder); if (this.contentEncoder.isCompleted()) { resetOutput(); } } } if (this.contentEncoder == null && !this.outbuf.hasData()) { if (this.status == CLOSING) { this.session.close(); this.status = CLOSED; } if (this.status != CLOSED) { this.session.clearEvent(EventMask.WRITE); handler.responseReady(this); } } } } catch (IOException ex) { handler.exception(this, ex); } finally { // Finally set the buffered output flag this.hasBufferedOutput = this.outbuf.hasData(); } } public void submitResponse(final HttpResponse response) throws IOException, HttpException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } assertNotClosed(); if (this.response != null) { throw new HttpException("Response already submitted"); } this.responseWriter.write(response); this.hasBufferedOutput = this.outbuf.hasData(); if (response.getStatusLine().getStatusCode() >= 200) { this.connMetrics.incrementResponseCount(); if (response.getEntity() != null) { this.response = response; prepareEncoder(response); } } this.session.setEvent(EventMask.WRITE); } public boolean isResponseSubmitted() { return this.response != null; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.nio; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import org.apache.http.ConnectionClosedException; import org.apache.http.Header; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpInetConnection; import org.apache.http.HttpMessage; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ContentLengthStrategy; import org.apache.http.impl.HttpConnectionMetricsImpl; import org.apache.http.impl.entity.LaxContentLengthStrategy; import org.apache.http.impl.entity.StrictContentLengthStrategy; import org.apache.http.impl.io.HttpTransportMetricsImpl; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpConnection; import org.apache.http.impl.nio.codecs.ChunkDecoder; import org.apache.http.impl.nio.codecs.ChunkEncoder; import org.apache.http.impl.nio.codecs.IdentityDecoder; import org.apache.http.impl.nio.codecs.IdentityEncoder; import org.apache.http.impl.nio.codecs.LengthDelimitedDecoder; import org.apache.http.impl.nio.codecs.LengthDelimitedEncoder; import org.apache.http.impl.nio.reactor.SessionInputBufferImpl; import org.apache.http.impl.nio.reactor.SessionOutputBufferImpl; import org.apache.http.io.HttpTransportMetrics; import org.apache.http.nio.reactor.EventMask; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; /** * This class serves as a base for all {@link NHttpConnection} implementations * and implements functionality common to both client and server * HTTP connections. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * </ul> * * @since 4.0 */ public class NHttpConnectionBase implements NHttpConnection, HttpInetConnection, SessionBufferStatus { protected final ContentLengthStrategy incomingContentStrategy; protected final ContentLengthStrategy outgoingContentStrategy; protected final SessionInputBufferImpl inbuf; protected final SessionOutputBufferImpl outbuf; protected final HttpTransportMetricsImpl inTransportMetrics; protected final HttpTransportMetricsImpl outTransportMetrics; protected final HttpConnectionMetricsImpl connMetrics; protected HttpContext context; protected IOSession session; protected SocketAddress remote; protected volatile ContentDecoder contentDecoder; protected volatile boolean hasBufferedInput; protected volatile ContentEncoder contentEncoder; protected volatile boolean hasBufferedOutput; protected volatile HttpRequest request; protected volatile HttpResponse response; protected volatile int status; /** * Creates a new instance of this class given the underlying I/O session. * * @param session the underlying I/O session. * @param allocator byte buffer allocator. * @param params HTTP parameters. */ public NHttpConnectionBase( final IOSession session, final ByteBufferAllocator allocator, final HttpParams params) { super(); if (session == null) { throw new IllegalArgumentException("I/O session may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP params may not be null"); } int buffersize = HttpConnectionParams.getSocketBufferSize(params); int linebuffersize = buffersize; if (linebuffersize > 512) { linebuffersize = 512; } this.inbuf = new SessionInputBufferImpl(buffersize, linebuffersize, allocator, params); this.outbuf = new SessionOutputBufferImpl(buffersize, linebuffersize, allocator, params); this.incomingContentStrategy = new LaxContentLengthStrategy(); this.outgoingContentStrategy = new StrictContentLengthStrategy(); this.inTransportMetrics = createTransportMetrics(); this.outTransportMetrics = createTransportMetrics(); this.connMetrics = createConnectionMetrics( this.inTransportMetrics, this.outTransportMetrics); setSession(session); this.status = ACTIVE; } private void setSession(final IOSession session) { this.session = session; this.context = new SessionHttpContext(this.session); this.session.setBufferStatus(this); this.remote = this.session.getRemoteAddress(); } /** * @since 4.1 */ protected HttpTransportMetricsImpl createTransportMetrics() { return new HttpTransportMetricsImpl(); } /** * @since 4.1 */ protected HttpConnectionMetricsImpl createConnectionMetrics( final HttpTransportMetrics inTransportMetric, final HttpTransportMetrics outTransportMetric) { return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric); } public int getStatus() { return this.status; } public HttpContext getContext() { return this.context; } public HttpRequest getHttpRequest() { return this.request; } public HttpResponse getHttpResponse() { return this.response; } public void requestInput() { this.session.setEvent(EventMask.READ); } public void requestOutput() { this.session.setEvent(EventMask.WRITE); } public void suspendInput() { this.session.clearEvent(EventMask.READ); } public void suspendOutput() { this.session.clearEvent(EventMask.WRITE); } /** * Initializes a specific {@link ContentDecoder} implementation based on the * properties of the given {@link HttpMessage} and generates an instance of * {@link HttpEntity} matching the properties of the content decoder. * * @param message the HTTP message. * @return HTTP entity. * @throws HttpException in case of an HTTP protocol violation. */ protected HttpEntity prepareDecoder(final HttpMessage message) throws HttpException { BasicHttpEntity entity = new BasicHttpEntity(); long len = this.incomingContentStrategy.determineLength(message); this.contentDecoder = createContentDecoder( len, this.session.channel(), this.inbuf, this.inTransportMetrics); if (len == ContentLengthStrategy.CHUNKED) { entity.setChunked(true); entity.setContentLength(-1); } else if (len == ContentLengthStrategy.IDENTITY) { entity.setChunked(false); entity.setContentLength(-1); } else { entity.setChunked(false); entity.setContentLength(len); } Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } return entity; } /** * Factory method for {@link ContentDecoder} instances. * * @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or * {@link ContentLengthStrategy#IDENTITY}, if unknown. * @param channel the session channel. * @param buffer the session buffer. * @param metrics transport metrics. * * @return content decoder. * * @since 4.1 */ protected ContentDecoder createContentDecoder( final long len, final ReadableByteChannel channel, final SessionInputBuffer buffer, final HttpTransportMetricsImpl metrics) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkDecoder(channel, buffer, metrics); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityDecoder(channel, buffer, metrics); } else { return new LengthDelimitedDecoder(channel, buffer, metrics, len); } } /** * Initializes a specific {@link ContentEncoder} implementation based on the * properties of the given {@link HttpMessage}. * * @param message the HTTP message. * @throws HttpException in case of an HTTP protocol violation. */ protected void prepareEncoder(final HttpMessage message) throws HttpException { long len = this.outgoingContentStrategy.determineLength(message); this.contentEncoder = createContentEncoder( len, this.session.channel(), this.outbuf, this.outTransportMetrics); } /** * Factory method for {@link ContentEncoder} instances. * * @param len content length, if known, {@link ContentLengthStrategy#CHUNKED} or * {@link ContentLengthStrategy#IDENTITY}, if unknown. * @param channel the session channel. * @param buffer the session buffer. * @param metrics transport metrics. * * @return content encoder. * * @since 4.1 */ protected ContentEncoder createContentEncoder( final long len, final WritableByteChannel channel, final SessionOutputBuffer buffer, final HttpTransportMetricsImpl metrics) { if (len == ContentLengthStrategy.CHUNKED) { return new ChunkEncoder(channel, buffer, metrics); } else if (len == ContentLengthStrategy.IDENTITY) { return new IdentityEncoder(channel, buffer, metrics); } else { return new LengthDelimitedEncoder(channel, buffer, metrics, len); } } public boolean hasBufferedInput() { return this.hasBufferedInput; } public boolean hasBufferedOutput() { return this.hasBufferedOutput; } /** * Assets if the connection is still open. * * @throws ConnectionClosedException in case the connection has already * been closed. */ protected void assertNotClosed() throws ConnectionClosedException { if (this.status != ACTIVE) { throw new ConnectionClosedException("Connection is closed"); } } public void close() throws IOException { if (this.status != ACTIVE) { return; } this.status = CLOSING; if (this.outbuf.hasData()) { this.session.setEvent(EventMask.WRITE); } else { this.session.close(); this.status = CLOSED; } } public boolean isOpen() { return this.status == ACTIVE && !this.session.isClosed(); } public boolean isStale() { return this.session.isClosed(); } public InetAddress getLocalAddress() { SocketAddress address = this.session.getLocalAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getAddress(); } else { return null; } } public int getLocalPort() { SocketAddress address = this.session.getLocalAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getPort(); } else { return -1; } } public InetAddress getRemoteAddress() { SocketAddress address = this.session.getRemoteAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getAddress(); } else { return null; } } public int getRemotePort() { SocketAddress address = this.session.getRemoteAddress(); if (address instanceof InetSocketAddress) { return ((InetSocketAddress) address).getPort(); } else { return -1; } } public void setSocketTimeout(int timeout) { this.session.setSocketTimeout(timeout); } public int getSocketTimeout() { return this.session.getSocketTimeout(); } public void shutdown() throws IOException { this.status = CLOSED; this.session.shutdown(); } public HttpConnectionMetrics getMetrics() { return this.connMetrics; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("["); buffer.append(this.remote); if (this.status == CLOSED) { buffer.append("(closed)"); } buffer.append("]"); return buffer.toString(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.nio; import org.apache.http.nio.reactor.IOSession; import org.apache.http.protocol.HttpContext; class SessionHttpContext implements HttpContext { private final IOSession iosession; public SessionHttpContext(final IOSession iosession) { super(); this.iosession = iosession; } public Object getAttribute(final String id) { return this.iosession.getAttribute(id); } public Object removeAttribute(final String id) { return this.iosession.removeAttribute(id); } public void setAttribute(final String id, final Object obj) { this.iosession.setAttribute(id, obj); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.nio; import 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 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.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.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 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.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.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 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.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 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.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.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