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; import java.util.Iterator; /** * A type-safe iterator for {@link HeaderElement} objects. * * @since 4.0 */ public interface HeaderElementIterator extends Iterator { /** * Indicates whether there is another header element in this * iteration. * * @return <code>true</code> if there is another header element, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next header element from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header element in this iteration */ HeaderElement nextElement(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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 java.io.IOException; /** * A generic HTTP connection, useful on client and server side. * * @since 4.0 */ public interface HttpConnection { /** * Closes this connection gracefully. * This method will attempt to flush the internal output * buffer prior to closing the underlying socket. * This method MUST NOT be called from a different thread to force * shutdown of the connection. Use {@link #shutdown shutdown} instead. */ public void close() throws IOException; /** * Checks if this connection is open. * @return true if it is open, false if it is closed. */ public boolean isOpen(); /** * Checks whether this connection has gone down. * Network connections may get closed during some time of inactivity * for several reasons. The next time a read is attempted on such a * connection it will throw an IOException. * This method tries to alleviate this inconvenience by trying to * find out if a connection is still usable. Implementations may do * that by attempting a read with a very small timeout. Thus this * method may block for a small amount of time before returning a result. * It is therefore an <i>expensive</i> operation. * * @return <code>true</code> if attempts to use this connection are * likely to succeed, or <code>false</code> if they are likely * to fail and this connection should be closed */ public boolean isStale(); /** * Sets the socket timeout value. * * @param timeout timeout value in milliseconds */ void setSocketTimeout(int timeout); /** * Returns the socket timeout value. * * @return positive value in milliseconds if a timeout is set, * <code>0</code> if timeout is disabled or <code>-1</code> if * timeout is undefined. */ int getSocketTimeout(); /** * Force-closes this connection. * This is the only method of a connection which may be called * from a different thread to terminate the connection. * This method will not attempt to flush the transmitter's * internal buffer prior to closing the underlying socket. */ public void shutdown() throws IOException; /** * Returns a collection of connection metrics. * * @return HttpConnectionMetrics */ HttpConnectionMetrics getMetrics(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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 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.util.Iterator; /** * An iterator for {@link String} tokens. * This interface is designed as a complement to * {@link HeaderElementIterator}, in cases where the items * are plain strings rather than full header elements. * * @since 4.0 */ public interface TokenIterator extends Iterator { /** * Indicates whether there is another token in this iteration. * * @return <code>true</code> if there is another token, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next token from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next token in this iteration */ String nextToken(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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. Protocol * <p> * 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 HttpResponseInterceptor { /** * Processes a response. * On the server side, this step is performed before the response is * sent to the client. On the client side, this step is performed * on incoming messages before the message body is evaluated. * * @param response the response to postprocess * @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(HttpResponse response, HttpContext context) throws HttpException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; 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.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.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; /** * 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.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; /** * 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 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.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.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.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 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; /** * 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.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 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; /** * 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; 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; /** * 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; 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 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
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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; /** * Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518 * (WebDAV) are listed. * * @since 4.1 */ public final class HttpHeaders { private HttpHeaders() { } /** RFC 2616 (HTTP/1.1) Section 14.1 */ public static final String ACCEPT = "Accept"; /** RFC 2616 (HTTP/1.1) Section 14.2 */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** RFC 2616 (HTTP/1.1) Section 14.3 */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.4 */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** RFC 2616 (HTTP/1.1) Section 14.5 */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** RFC 2616 (HTTP/1.1) Section 14.6 */ public static final String AGE = "Age"; /** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */ public static final String ALLOW = "Allow"; /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */ public static final String AUTHORIZATION = "Authorization"; /** RFC 2616 (HTTP/1.1) Section 14.9 */ public static final String CACHE_CONTROL = "Cache-Control"; /** RFC 2616 (HTTP/1.1) Section 14.10 */ public static final String CONNECTION = "Connection"; /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.12 */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */ public static final String CONTENT_LENGTH = "Content-Length"; /** RFC 2616 (HTTP/1.1) Section 14.14 */ public static final String CONTENT_LOCATION = "Content-Location"; /** RFC 2616 (HTTP/1.1) Section 14.15 */ public static final String CONTENT_MD5 = "Content-MD5"; /** RFC 2616 (HTTP/1.1) Section 14.16 */ public static final String CONTENT_RANGE = "Content-Range"; /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */ public static final String CONTENT_TYPE = "Content-Type"; /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */ public static final String DATE = "Date"; /** RFC 2518 (WevDAV) Section 9.1 */ public static final String DAV = "Dav"; /** RFC 2518 (WevDAV) Section 9.2 */ public static final String DEPTH = "Depth"; /** RFC 2518 (WevDAV) Section 9.3 */ public static final String DESTINATION = "Destination"; /** RFC 2616 (HTTP/1.1) Section 14.19 */ public static final String ETAG = "ETag"; /** RFC 2616 (HTTP/1.1) Section 14.20 */ public static final String EXPECT = "Expect"; /** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */ public static final String EXPIRES = "Expires"; /** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */ public static final String FROM = "From"; /** RFC 2616 (HTTP/1.1) Section 14.23 */ public static final String HOST = "Host"; /** RFC 2518 (WevDAV) Section 9.4 */ public static final String IF = "If"; /** RFC 2616 (HTTP/1.1) Section 14.24 */ public static final String IF_MATCH = "If-Match"; /** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** RFC 2616 (HTTP/1.1) Section 14.26 */ public static final String IF_NONE_MATCH = "If-None-Match"; /** RFC 2616 (HTTP/1.1) Section 14.27 */ public static final String IF_RANGE = "If-Range"; /** RFC 2616 (HTTP/1.1) Section 14.28 */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */ public static final String LAST_MODIFIED = "Last-Modified"; /** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */ public static final String LOCATION = "Location"; /** RFC 2518 (WevDAV) Section 9.5 */ public static final String LOCK_TOKEN = "Lock-Token"; /** RFC 2616 (HTTP/1.1) Section 14.31 */ public static final String MAX_FORWARDS = "Max-Forwards"; /** RFC 2518 (WevDAV) Section 9.6 */ public static final String OVERWRITE = "Overwrite"; /** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */ public static final String PRAGMA = "Pragma"; /** RFC 2616 (HTTP/1.1) Section 14.33 */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** RFC 2616 (HTTP/1.1) Section 14.34 */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** RFC 2616 (HTTP/1.1) Section 14.35 */ public static final String RANGE = "Range"; /** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */ public static final String REFERER = "Referer"; /** RFC 2616 (HTTP/1.1) Section 14.37 */ public static final String RETRY_AFTER = "Retry-After"; /** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */ public static final String SERVER = "Server"; /** RFC 2518 (WevDAV) Section 9.7 */ public static final String STATUS_URI = "Status-URI"; /** RFC 2616 (HTTP/1.1) Section 14.39 */ public static final String TE = "TE"; /** RFC 2518 (WevDAV) Section 9.8 */ public static final String TIMEOUT = "Timeout"; /** RFC 2616 (HTTP/1.1) Section 14.40 */ public static final String TRAILER = "Trailer"; /** RFC 2616 (HTTP/1.1) Section 14.41 */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.42 */ public static final String UPGRADE = "Upgrade"; /** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */ public static final String USER_AGENT = "User-Agent"; /** RFC 2616 (HTTP/1.1) Section 14.44 */ public static final String VARY = "Vary"; /** RFC 2616 (HTTP/1.1) Section 14.45 */ public static final String VIA = "Via"; /** RFC 2616 (HTTP/1.1) Section 14.46 */ public static final String WARNING = "Warning"; /** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for formatting elements of the HEAD section of an HTTP message. * This is the complement to {@link LineParser}. * There are individual methods for formatting a request line, a * status line, or a header line. The formatting does <i>not</i> include the * trailing line break sequence CR-LF. * Instances of this interface are expected to be stateless and thread-safe. * * <p> * The formatted lines are returned in memory, the formatter does not depend * on any specific IO mechanism. * In order to avoid unnecessary creation of temporary objects, * a buffer can be passed as argument to all formatting methods. * The implementation may or may not actually use that buffer for formatting. * If it is used, the buffer will first be cleared by the * <code>formatXXX</code> methods. * The argument buffer can always be re-used after the call. The buffer * returned as the result, if it is different from the argument buffer, * MUST NOT be modified. * </p> * * @since 4.0 */ public interface LineFormatter { /** * Formats a protocol version. * This method does <i>not</i> follow the general contract for * <code>buffer</code> arguments. * It does <i>not</i> clear the argument buffer, but appends instead. * The returned buffer can always be modified by the caller. * Because of these differing conventions, it is not named * <code>formatProtocolVersion</code>. * * @param buffer a buffer to which to append, or <code>null</code> * @param version the protocol version to format * * @return a buffer with the formatted protocol version appended. * The caller is allowed to modify the result buffer. * If the <code>buffer</code> argument is not <code>null</code>, * the returned buffer is the argument buffer. */ CharArrayBuffer appendProtocolVersion(CharArrayBuffer buffer, ProtocolVersion version); /** * Formats a request line. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param reqline the request line to format * * @return the formatted request line */ CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, RequestLine reqline); /** * Formats a status line. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param statline the status line to format * * @return the formatted status line * * @throws org.apache.ogt.http.ParseException in case of a parse error */ CharArrayBuffer formatStatusLine(CharArrayBuffer buffer, StatusLine statline); /** * Formats a header. * Due to header continuation, the result may be multiple lines. * In order to generate well-formed HTTP, the lines in the result * must be separated by the HTTP line break sequence CR-LF. * There is <i>no</i> trailing CR-LF in the result. * <br/> * See the class comment for details about the buffer argument. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param header the header to format * * @return a buffer holding the formatted header, never <code>null</code>. * The returned buffer may be different from the argument buffer. * * @throws org.apache.ogt.http.ParseException in case of a parse error */ CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.util.NoSuchElementException; import org.apache.ogt.http.FormattedHeader; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HeaderElementIterator; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic implementation of a {@link HeaderElementIterator}. * * @since 4.0 */ public class BasicHeaderElementIterator implements HeaderElementIterator { private final HeaderIterator headerIt; private final HeaderValueParser parser; private HeaderElement currentElement = null; private CharArrayBuffer buffer = null; private ParserCursor cursor = null; /** * Creates a new instance of BasicHeaderElementIterator */ public BasicHeaderElementIterator( final HeaderIterator headerIterator, final HeaderValueParser parser) { if (headerIterator == null) { throw new IllegalArgumentException("Header iterator may not be null"); } if (parser == null) { throw new IllegalArgumentException("Parser may not be null"); } this.headerIt = headerIterator; this.parser = parser; } public BasicHeaderElementIterator(final HeaderIterator headerIterator) { this(headerIterator, BasicHeaderValueParser.DEFAULT); } private void bufferHeaderValue() { this.cursor = null; this.buffer = null; while (this.headerIt.hasNext()) { Header h = this.headerIt.nextHeader(); if (h instanceof FormattedHeader) { this.buffer = ((FormattedHeader) h).getBuffer(); this.cursor = new ParserCursor(0, this.buffer.length()); this.cursor.updatePos(((FormattedHeader) h).getValuePos()); break; } else { String value = h.getValue(); if (value != null) { this.buffer = new CharArrayBuffer(value.length()); this.buffer.append(value); this.cursor = new ParserCursor(0, this.buffer.length()); break; } } } } private void parseNextElement() { // loop while there are headers left to parse while (this.headerIt.hasNext() || this.cursor != null) { if (this.cursor == null || this.cursor.atEnd()) { // get next header value bufferHeaderValue(); } // Anything buffered? if (this.cursor != null) { // loop while there is data in the buffer while (!this.cursor.atEnd()) { HeaderElement e = this.parser.parseHeaderElement(this.buffer, this.cursor); if (!(e.getName().length() == 0 && e.getValue() == null)) { // Found something this.currentElement = e; return; } } // if at the end of the buffer if (this.cursor.atEnd()) { // discard it this.cursor = null; this.buffer = null; } } } } public boolean hasNext() { if (this.currentElement == null) { parseNextElement(); } return this.currentElement != null; } public HeaderElement nextElement() throws NoSuchElementException { if (this.currentElement == null) { parseNextElement(); } if (this.currentElement == null) { throw new NoSuchElementException("No more header elements available"); } HeaderElement element = this.currentElement; this.currentElement = null; return element; } public final Object next() throws NoSuchElementException { return nextElement(); } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Remove 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.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic parser for lines in the head section of an HTTP message. * There are individual methods for parsing a request line, a * status line, or a header line. * The lines to parse are passed in memory, the parser does not depend * on any specific IO mechanism. * Instances of this class are stateless and thread-safe. * Derived classes MUST maintain these properties. * * <p> * Note: This class was created by refactoring parsing code located in * various other classes. The author tags from those other classes have * been replicated here, although the association with the parsing code * taken from there has not been traced. * </p> * * @since 4.0 */ public class BasicLineParser implements LineParser { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicLineParser} is not a singleton, there can * be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicLineParser DEFAULT = new BasicLineParser(); /** * A version of the protocol to parse. * The version is typically not relevant, but the protocol name. */ protected final ProtocolVersion protocol; /** * Creates a new line parser for the given HTTP-like protocol. * * @param proto a version of the protocol to parse, or * <code>null</code> for HTTP. The actual version * is not relevant, only the protocol name. */ public BasicLineParser(ProtocolVersion proto) { if (proto == null) { proto = HttpVersion.HTTP_1_1; } this.protocol = proto; } /** * Creates a new line parser for HTTP. */ public BasicLineParser() { this(null); } public final static ProtocolVersion parseProtocolVersion(String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseProtocolVersion(buffer, cursor); } // non-javadoc, see interface LineParser public ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } final String protoname = this.protocol.getProtocol(); final int protolength = protoname.length(); int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); skipWhitespace(buffer, cursor); int i = cursor.getPos(); // long enough for "HTTP/1.1"? if (i + protolength + 4 > indexTo) { throw new ParseException ("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo)); } // check the protocol name and slash boolean ok = true; for (int j=0; ok && (j<protolength); j++) { ok = (buffer.charAt(i+j) == protoname.charAt(j)); } if (ok) { ok = (buffer.charAt(i+protolength) == '/'); } if (!ok) { throw new ParseException ("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo)); } i += protolength+1; int period = buffer.indexOf('.', i, indexTo); if (period == -1) { throw new ParseException ("Invalid protocol version number: " + buffer.substring(indexFrom, indexTo)); } int major; try { major = Integer.parseInt(buffer.substringTrimmed(i, period)); } catch (NumberFormatException e) { throw new ParseException ("Invalid protocol major version number: " + buffer.substring(indexFrom, indexTo)); } i = period + 1; int blank = buffer.indexOf(' ', i, indexTo); if (blank == -1) { blank = indexTo; } int minor; try { minor = Integer.parseInt(buffer.substringTrimmed(i, blank)); } catch (NumberFormatException e) { throw new ParseException( "Invalid protocol minor version number: " + buffer.substring(indexFrom, indexTo)); } cursor.updatePos(blank); return createProtocolVersion(major, minor); } // parseProtocolVersion /** * Creates a protocol version. * Called from {@link #parseProtocolVersion}. * * @param major the major version number, for example 1 in HTTP/1.0 * @param minor the minor version number, for example 0 in HTTP/1.0 * * @return the protocol version */ protected ProtocolVersion createProtocolVersion(int major, int minor) { return protocol.forVersion(major, minor); } // non-javadoc, see interface LineParser public boolean hasProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int index = cursor.getPos(); final String protoname = this.protocol.getProtocol(); final int protolength = protoname.length(); if (buffer.length() < protolength+4) return false; // not long enough for "HTTP/1.1" if (index < 0) { // end of line, no tolerance for trailing whitespace // this works only for single-digit major and minor version index = buffer.length() -4 -protolength; } else if (index == 0) { // beginning of line, tolerate leading whitespace while ((index < buffer.length()) && HTTP.isWhitespace(buffer.charAt(index))) { index++; } } // else within line, don't tolerate whitespace if (index + protolength + 4 > buffer.length()) return false; // just check protocol name and slash, no need to analyse the version boolean ok = true; for (int j=0; ok && (j<protolength); j++) { ok = (buffer.charAt(index+j) == protoname.charAt(j)); } if (ok) { ok = (buffer.charAt(index+protolength) == '/'); } return ok; } public final static RequestLine parseRequestLine(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseRequestLine(buffer, cursor); } /** * Parses a request line. * * @param buffer a buffer holding the line to parse * * @return the parsed request line * * @throws ParseException in case of a parse error */ public RequestLine parseRequestLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); try { skipWhitespace(buffer, cursor); int i = cursor.getPos(); int blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } String method = buffer.substringTrimmed(i, blank); cursor.updatePos(blank); skipWhitespace(buffer, cursor); i = cursor.getPos(); blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } String uri = buffer.substringTrimmed(i, blank); cursor.updatePos(blank); ProtocolVersion ver = parseProtocolVersion(buffer, cursor); skipWhitespace(buffer, cursor); if (!cursor.atEnd()) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } return createRequestLine(method, uri, ver); } catch (IndexOutOfBoundsException e) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } } // parseRequestLine /** * Instantiates a new request line. * Called from {@link #parseRequestLine}. * * @param method the request method * @param uri the requested URI * @param ver the protocol version * * @return a new status line with the given data */ protected RequestLine createRequestLine(final String method, final String uri, final ProtocolVersion ver) { return new BasicRequestLine(method, uri, ver); } public final static StatusLine parseStatusLine(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseStatusLine(buffer, cursor); } // non-javadoc, see interface LineParser public StatusLine parseStatusLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); try { // handle the HTTP-Version ProtocolVersion ver = parseProtocolVersion(buffer, cursor); // handle the Status-Code skipWhitespace(buffer, cursor); int i = cursor.getPos(); int blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { blank = indexTo; } int statusCode = 0; String s = buffer.substringTrimmed(i, blank); for (int j = 0; j < s.length(); j++) { if (!Character.isDigit(s.charAt(j))) { throw new ParseException( "Status line contains invalid status code: " + buffer.substring(indexFrom, indexTo)); } } try { statusCode = Integer.parseInt(s); } catch (NumberFormatException e) { throw new ParseException( "Status line contains invalid status code: " + buffer.substring(indexFrom, indexTo)); } //handle the Reason-Phrase i = blank; String reasonPhrase = null; if (i < indexTo) { reasonPhrase = buffer.substringTrimmed(i, indexTo); } else { reasonPhrase = ""; } return createStatusLine(ver, statusCode, reasonPhrase); } catch (IndexOutOfBoundsException e) { throw new ParseException("Invalid status line: " + buffer.substring(indexFrom, indexTo)); } } // parseStatusLine /** * Instantiates a new status line. * Called from {@link #parseStatusLine}. * * @param ver the protocol version * @param status the status code * @param reason the reason phrase * * @return a new status line with the given data */ protected StatusLine createStatusLine(final ProtocolVersion ver, final int status, final String reason) { return new BasicStatusLine(ver, status, reason); } public final static Header parseHeader(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); return parser.parseHeader(buffer); } // non-javadoc, see interface LineParser public Header parseHeader(CharArrayBuffer buffer) throws ParseException { // the actual parser code is in the constructor of BufferedHeader return new BufferedHeader(buffer); } /** * Helper to skip whitespace. */ protected void skipWhitespace(final CharArrayBuffer buffer, final ParserCursor cursor) { int pos = cursor.getPos(); int indexTo = cursor.getUpperBound(); while ((pos < indexTo) && HTTP.isWhitespace(buffer.charAt(pos))) { pos++; } cursor.updatePos(pos); } } // class BasicLineParser
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import org.apache.ogt.http.FormattedHeader; import org.apache.ogt.http.Header; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for formatting elements of the HEAD section of an HTTP message. * This is the complement to {@link LineParser}. * There are individual methods for formatting a request line, a * status line, or a header line. The formatting does <i>not</i> include the * trailing line break sequence CR-LF. * The formatted lines are returned in memory, the formatter does not depend * on any specific IO mechanism. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public class BasicLineFormatter implements LineFormatter { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicLineFormatter} is not a singleton, there can * be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicLineFormatter DEFAULT = new BasicLineFormatter(); // public default constructor /** * Obtains a buffer for formatting. * * @param buffer a buffer already available, or <code>null</code> * * @return the cleared argument buffer if there is one, or * a new empty buffer that can be used for formatting */ protected CharArrayBuffer initBuffer(CharArrayBuffer buffer) { if (buffer != null) { buffer.clear(); } else { buffer = new CharArrayBuffer(64); } return buffer; } /** * Formats a protocol version. * * @param version the protocol version to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted protocol version */ public final static String formatProtocolVersion(final ProtocolVersion version, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.appendProtocolVersion(null, version).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer, final ProtocolVersion version) { if (version == null) { throw new IllegalArgumentException ("Protocol version may not be null"); } // can't use initBuffer, that would clear the argument! CharArrayBuffer result = buffer; final int len = estimateProtocolVersionLen(version); if (result == null) { result = new CharArrayBuffer(len); } else { result.ensureCapacity(len); } result.append(version.getProtocol()); result.append('/'); result.append(Integer.toString(version.getMajor())); result.append('.'); result.append(Integer.toString(version.getMinor())); return result; } /** * Guesses the length of a formatted protocol version. * Needed to guess the length of a formatted request or status line. * * @param version the protocol version to format, or <code>null</code> * * @return the estimated length of the formatted protocol version, * in characters */ protected int estimateProtocolVersionLen(final ProtocolVersion version) { return version.getProtocol().length() + 4; // room for "HTTP/1.1" } /** * Formats a request line. * * @param reqline the request line to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted request line */ public final static String formatRequestLine(final RequestLine reqline, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatRequestLine(null, reqline).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, RequestLine reqline) { if (reqline == null) { throw new IllegalArgumentException ("Request line may not be null"); } CharArrayBuffer result = initBuffer(buffer); doFormatRequestLine(result, reqline); return result; } /** * Actually formats a request line. * Called from {@link #formatRequestLine}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param reqline the request line to format, never <code>null</code> */ protected void doFormatRequestLine(final CharArrayBuffer buffer, final RequestLine reqline) { final String method = reqline.getMethod(); final String uri = reqline.getUri(); // room for "GET /index.html HTTP/1.1" int len = method.length() + 1 + uri.length() + 1 + estimateProtocolVersionLen(reqline.getProtocolVersion()); buffer.ensureCapacity(len); buffer.append(method); buffer.append(' '); buffer.append(uri); buffer.append(' '); appendProtocolVersion(buffer, reqline.getProtocolVersion()); } /** * Formats a status line. * * @param statline the status line to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted status line */ public final static String formatStatusLine(final StatusLine statline, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatStatusLine(null, statline).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { if (statline == null) { throw new IllegalArgumentException ("Status line may not be null"); } CharArrayBuffer result = initBuffer(buffer); doFormatStatusLine(result, statline); return result; } /** * Actually formats a status line. * Called from {@link #formatStatusLine}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param statline the status line to format, never <code>null</code> */ protected void doFormatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { int len = estimateProtocolVersionLen(statline.getProtocolVersion()) + 1 + 3 + 1; // room for "HTTP/1.1 200 " final String reason = statline.getReasonPhrase(); if (reason != null) { len += reason.length(); } buffer.ensureCapacity(len); appendProtocolVersion(buffer, statline.getProtocolVersion()); buffer.append(' '); buffer.append(Integer.toString(statline.getStatusCode())); buffer.append(' '); // keep whitespace even if reason phrase is empty if (reason != null) { buffer.append(reason); } } /** * Formats a header. * * @param header the header to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted header */ public final static String formatHeader(final Header header, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatHeader(null, header).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header) { if (header == null) { throw new IllegalArgumentException ("Header may not be null"); } CharArrayBuffer result = null; if (header instanceof FormattedHeader) { // If the header is backed by a buffer, re-use the buffer result = ((FormattedHeader)header).getBuffer(); } else { result = initBuffer(buffer); doFormatHeader(result, header); } return result; } // formatHeader /** * Actually formats a header. * Called from {@link #formatHeader}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param header the header to format, never <code>null</code> */ protected void doFormatHeader(final CharArrayBuffer buffer, final Header header) { final String name = header.getName(); final String value = header.getValue(); int len = name.length() + 2; if (value != null) { len += value.length(); } buffer.ensureCapacity(len); buffer.append(name); buffer.append(": "); if (value != null) { buffer.append(value); } } } // class BasicLineFormatter
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for parsing header values into elements. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public interface HeaderValueParser { /** * Parses a header value into elements. * Parse errors are indicated as <code>RuntimeException</code>. * <p> * Some HTTP headers (such as the set-cookie header) have values that * can be decomposed into multiple elements. In order to be processed * by this parser, 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. * </p> * * @param buffer buffer holding the header value to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all elements of the header value * * @throws ParseException in case of a parse error */ HeaderElement[] parseElements( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a single header element. * A header element consist of a semicolon-separate list * of name=value definitions. * * @param buffer buffer holding the element to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed element * * @throws ParseException in case of a parse error */ HeaderElement parseHeaderElement( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a list of name-value pairs. * These lists are used to specify parameters to a header element. * Parse errors are indicated as <code>ParseException</code>. * * @param buffer buffer holding the name-value list to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all items of the name-value list * * @throws ParseException in case of a parse error */ NameValuePair[] parseParameters( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a name=value specification, where the = and value are optional. * * @param buffer the buffer holding the name-value pair to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the name-value pair, where the value is <code>null</code> * if no value is specified */ NameValuePair parseNameValuePair( CharArrayBuffer buffer, ParserCursor cursor) 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.message; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; /** * Basic implementation of {@link HttpRequest}. * <p> * The following parameters can be used to customize the behavior of this class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li> * </ul> * * @since 4.0 */ public class BasicHttpRequest extends AbstractHttpMessage implements HttpRequest { private final String method; private final String uri; private RequestLine requestline; /** * Creates an instance of this class using the given request method * and URI. The HTTP protocol version will be obtained from the * {@link HttpParams} instance associated with the object. * The initialization will be deferred * until {@link #getRequestLine()} is accessed for the first time. * * @param method request method. * @param uri request URI. */ public BasicHttpRequest(final String method, final String uri) { super(); if (method == null) { throw new IllegalArgumentException("Method name may not be null"); } if (uri == null) { throw new IllegalArgumentException("Request URI may not be null"); } this.method = method; this.uri = uri; this.requestline = null; } /** * Creates an instance of this class using the given request method, URI * and the HTTP protocol version. * * @param method request method. * @param uri request URI. * @param ver HTTP protocol version. */ public BasicHttpRequest(final String method, final String uri, final ProtocolVersion ver) { this(new BasicRequestLine(method, uri, ver)); } /** * Creates an instance of this class using the given request line. * * @param requestline request line. */ public BasicHttpRequest(final RequestLine requestline) { super(); if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } this.requestline = requestline; this.method = requestline.getMethod(); this.uri = requestline.getUri(); } /** * Returns the HTTP protocol version to be used for this request. If an * HTTP protocol version was not explicitly set at the construction time, * this method will obtain it from the {@link HttpParams} instance * associated with the object. * * @see #BasicHttpRequest(String, String) */ public ProtocolVersion getProtocolVersion() { return getRequestLine().getProtocolVersion(); } /** * Returns the request line of this request. If an HTTP protocol version * was not explicitly set at the construction time, this method will obtain * it from the {@link HttpParams} instance associated with the object. * * @see #BasicHttpRequest(String, String) */ public RequestLine getRequestLine() { if (this.requestline == null) { ProtocolVersion ver = HttpProtocolParams.getVersion(getParams()); this.requestline = new BasicRequestLine(this.method, this.uri, ver); } return this.requestline; } public String toString() { return this.method + " " + this.uri + " " + this.headergroup; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.io.Serializable; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.StatusLine; /** * Basic implementation of {@link StatusLine} * * @version $Id: BasicStatusLine.java 986952 2010-08-18 21:24:55Z olegk $ * * @since 4.0 */ public class BasicStatusLine implements StatusLine, Cloneable, Serializable { private static final long serialVersionUID = -2443303766890459269L; // ----------------------------------------------------- Instance Variables /** The protocol version. */ private final ProtocolVersion protoVersion; /** The status code. */ private final int statusCode; /** The reason phrase. */ private final String reasonPhrase; // ----------------------------------------------------------- Constructors /** * Creates a new status line with the given version, status, and reason. * * @param version the protocol version of the response * @param statusCode the status code of the response * @param reasonPhrase the reason phrase to the status code, or * <code>null</code> */ public BasicStatusLine(final ProtocolVersion version, int statusCode, final String reasonPhrase) { super(); if (version == null) { throw new IllegalArgumentException ("Protocol version may not be null."); } if (statusCode < 0) { throw new IllegalArgumentException ("Status code may not be negative."); } this.protoVersion = version; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; } // --------------------------------------------------------- Public Methods public int getStatusCode() { return this.statusCode; } public ProtocolVersion getProtocolVersion() { return this.protoVersion; } public String getReasonPhrase() { return this.reasonPhrase; } public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.DEFAULT .formatStatusLine(null, this).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.message; import java.util.NoSuchElementException; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.TokenIterator; /** * Basic implementation of a {@link TokenIterator}. * This implementation parses <tt>#token<tt> sequences as * defined by RFC 2616, section 2. * It extends that definition somewhat beyond US-ASCII. * * @since 4.0 */ public class BasicTokenIterator implements TokenIterator { /** The HTTP separator characters. Defined in RFC 2616, section 2.2. */ // the order of the characters here is adjusted to put the // most likely candidates at the beginning of the collection public final static String HTTP_SEPARATORS = " ,;=()<>@:\\\"/[]?{}\t"; /** The iterator from which to obtain the next header. */ protected final HeaderIterator headerIt; /** * The value of the current header. * This is the header value that includes {@link #currentToken}. * Undefined if the iteration is over. */ protected String currentHeader; /** * The token to be returned by the next call to {@link #currentToken}. * <code>null</code> if the iteration is over. */ protected String currentToken; /** * The position after {@link #currentToken} in {@link #currentHeader}. * Undefined if the iteration is over. */ protected int searchPos; /** * Creates a new instance of {@link BasicTokenIterator}. * * @param headerIterator the iterator for the headers to tokenize */ public BasicTokenIterator(final HeaderIterator headerIterator) { if (headerIterator == null) { throw new IllegalArgumentException ("Header iterator must not be null."); } this.headerIt = headerIterator; this.searchPos = findNext(-1); } // non-javadoc, see interface TokenIterator public boolean hasNext() { return (this.currentToken != null); } /** * Obtains the next token from this iteration. * * @return the next token in this iteration * * @throws NoSuchElementException if the iteration is already over * @throws ParseException if an invalid header value is encountered */ public String nextToken() throws NoSuchElementException, ParseException { if (this.currentToken == null) { throw new NoSuchElementException("Iteration already finished."); } final String result = this.currentToken; // updates currentToken, may trigger ParseException: this.searchPos = findNext(this.searchPos); return result; } /** * Returns the next token. * Same as {@link #nextToken}, but with generic return type. * * @return the next token in this iteration * * @throws NoSuchElementException if there are no more tokens * @throws ParseException if an invalid header value is encountered */ public final Object next() throws NoSuchElementException, ParseException { return nextToken(); } /** * Removing tokens is not supported. * * @throws UnsupportedOperationException always */ public final void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing tokens is not supported."); } /** * Determines the next token. * If found, the token is stored in {@link #currentToken}. * The return value indicates the position after the token * in {@link #currentHeader}. If necessary, the next header * will be obtained from {@link #headerIt}. * If not found, {@link #currentToken} is set to <code>null</code>. * * @param from the position in the current header at which to * start the search, -1 to search in the first header * * @return the position after the found token in the current header, or * negative if there was no next token * * @throws ParseException if an invalid header value is encountered */ protected int findNext(int from) throws ParseException { if (from < 0) { // called from the constructor, initialize the first header if (!this.headerIt.hasNext()) { return -1; } this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { // called after a token, make sure there is a separator from = findTokenSeparator(from); } int start = findTokenStart(from); if (start < 0) { this.currentToken = null; return -1; // nothing found } int end = findTokenEnd(start); this.currentToken = createToken(this.currentHeader, start, end); return end; } /** * Creates a new token to be returned. * Called from {@link #findNext findNext} after the token is identified. * The default implementation simply calls * {@link java.lang.String#substring String.substring}. * <br/> * If header values are significantly longer than tokens, and some * tokens are permanently referenced by the application, there can * be problems with garbage collection. A substring will hold a * reference to the full characters of the original string and * therefore occupies more memory than might be expected. * To avoid this, override this method and create a new string * instead of a substring. * * @param value the full header value from which to create a token * @param start the index of the first token character * @param end the index after the last token character * * @return a string representing the token identified by the arguments */ protected String createToken(String value, int start, int end) { return value.substring(start, end); } /** * Determines the starting position of the next token. * This method will iterate over headers if necessary. * * @param from the position in the current header at which to * start the search * * @return the position of the token start in the current header, * negative if no token start could be found */ protected int findTokenStart(int from) { if (from < 0) { throw new IllegalArgumentException ("Search position must not be negative: " + from); } boolean found = false; while (!found && (this.currentHeader != null)) { final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch) || isWhitespace(ch)) { // whitspace and token separators are skipped from++; } else if (isTokenChar(this.currentHeader.charAt(from))) { // found the start of a token found = true; } else { throw new ParseException ("Invalid character before token (pos " + from + "): " + this.currentHeader); } } if (!found) { if (this.headerIt.hasNext()) { this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { this.currentHeader = null; } } } // while headers return found ? from : -1; } /** * Determines the position of the next token separator. * Because of multi-header joining rules, the end of a * header value is a token separator. This method does * therefore not need to iterate over headers. * * @param from the position in the current header at which to * start the search * * @return the position of a token separator in the current header, * or at the end * * @throws ParseException * if a new token is found before a token separator. * RFC 2616, section 2.1 explicitly requires a comma between * tokens for <tt>#</tt>. */ protected int findTokenSeparator(int from) { if (from < 0) { throw new IllegalArgumentException ("Search position must not be negative: " + from); } boolean found = false; final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch)) { found = true; } else if (isWhitespace(ch)) { from++; } else if (isTokenChar(ch)) { throw new ParseException ("Tokens without separator (pos " + from + "): " + this.currentHeader); } else { throw new ParseException ("Invalid character after token (pos " + from + "): " + this.currentHeader); } } return from; } /** * Determines the ending position of the current token. * This method will not leave the current header value, * since the end of the header value is a token boundary. * * @param from the position of the first character of the token * * @return the position after the last character of the token. * The behavior is undefined if <code>from</code> does not * point to a token character in the current header value. */ protected int findTokenEnd(int from) { if (from < 0) { throw new IllegalArgumentException ("Token start position must not be negative: " + from); } final int to = this.currentHeader.length(); int end = from+1; while ((end < to) && isTokenChar(this.currentHeader.charAt(end))) { end++; } return end; } /** * Checks whether a character is a token separator. * RFC 2616, section 2.1 defines comma as the separator for * <tt>#token</tt> sequences. The end of a header value will * also separate tokens, but that is not a character check. * * @param ch the character to check * * @return <code>true</code> if the character is a token separator, * <code>false</code> otherwise */ protected boolean isTokenSeparator(char ch) { return (ch == ','); } /** * Checks whether a character is a whitespace character. * RFC 2616, section 2.2 defines space and horizontal tab as whitespace. * The optional preceeding line break is irrelevant, since header * continuation is handled transparently when parsing messages. * * @param ch the character to check * * @return <code>true</code> if the character is whitespace, * <code>false</code> otherwise */ protected boolean isWhitespace(char ch) { // we do not use Character.isWhitspace(ch) here, since that allows // many control characters which are not whitespace as per RFC 2616 return ((ch == '\t') || Character.isSpaceChar(ch)); } /** * Checks whether a character is a valid token character. * Whitespace, control characters, and HTTP separators are not * valid token characters. The HTTP specification (RFC 2616, section 2.2) * defines tokens only for the US-ASCII character set, this * method extends the definition to other character sets. * * @param ch the character to check * * @return <code>true</code> if the character is a valid token start, * <code>false</code> otherwise */ protected boolean isTokenChar(char ch) { // common sense extension of ALPHA + DIGIT if (Character.isLetterOrDigit(ch)) return true; // common sense extension of CTL if (Character.isISOControl(ch)) return false; // no common sense extension for this if (isHttpSeparator(ch)) return false; // RFC 2616, section 2.2 defines a token character as // "any CHAR except CTLs or separators". The controls // and separators are included in the checks above. // This will yield unexpected results for Unicode format characters. // If that is a problem, overwrite isHttpSeparator(char) to filter // out the false positives. return true; } /** * Checks whether a character is an HTTP separator. * The implementation in this class checks only for the HTTP separators * defined in RFC 2616, section 2.2. If you need to detect other * separators beyond the US-ASCII character set, override this method. * * @param ch the character to check * * @return <code>true</code> if the character is an HTTP separator */ protected boolean isHttpSeparator(char ch) { return (HTTP_SEPARATORS.indexOf(ch) >= 0); } } // class BasicTokenIterator
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.util.NoSuchElementException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; /** * Basic implementation of a {@link HeaderIterator}. * * @since 4.0 */ public class BasicHeaderIterator implements HeaderIterator { /** * An array of headers to iterate over. * Not all elements of this array are necessarily part of the iteration. * This array will never be modified by the iterator. * Derived implementations are expected to adhere to this restriction. */ protected final Header[] allHeaders; /** * The position of the next header in {@link #allHeaders allHeaders}. * Negative if the iteration is over. */ protected int currentIndex; /** * The header name to filter by. * <code>null</code> to iterate over all headers in the array. */ protected String headerName; /** * Creates a new header iterator. * * @param headers an array of headers over which to iterate * @param name the name of the headers over which to iterate, or * <code>null</code> for any */ public BasicHeaderIterator(Header[] headers, String name) { if (headers == null) { throw new IllegalArgumentException ("Header array must not be null."); } this.allHeaders = headers; this.headerName = name; this.currentIndex = findNext(-1); } /** * Determines the index of the next header. * * @param from one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ protected int findNext(int from) { if (from < -1) return -1; final int to = this.allHeaders.length-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return <code>true</code> if the header should be part of the * iteration, <code>false</code> to skip */ protected boolean filterHeader(int index) { return (this.headerName == null) || this.headerName.equalsIgnoreCase(this.allHeaders[index].getName()); } // non-javadoc, see interface HeaderIterator public boolean hasNext() { return (this.currentIndex >= 0); } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public Header nextHeader() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.currentIndex = findNext(current); return this.allHeaders[current]; } /** * Returns the next header. * Same as {@link #nextHeader nextHeader}, but not type-safe. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removing headers is not supported. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing headers is 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.message; import java.io.Serializable; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; /** * Basic implementation of {@link RequestLine}. * * @since 4.0 */ public class BasicRequestLine implements RequestLine, Cloneable, Serializable { private static final long serialVersionUID = 2810581718468737193L; private final ProtocolVersion protoversion; private final String method; private final String uri; public BasicRequestLine(final String method, final String uri, final ProtocolVersion version) { super(); if (method == null) { throw new IllegalArgumentException ("Method must not be null."); } if (uri == null) { throw new IllegalArgumentException ("URI must not be null."); } if (version == null) { throw new IllegalArgumentException ("Protocol version must not be null."); } this.method = method; this.uri = uri; this.protoversion = version; } public String getMethod() { return this.method; } public ProtocolVersion getProtocolVersion() { return this.protoversion; } public String getUri() { return this.uri; } public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.DEFAULT .formatRequestLine(null, this).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.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.protocol.HTTP; /** * Basic implementation of {@link HttpEntityEnclosingRequest}. * * @since 4.0 */ public class BasicHttpEntityEnclosingRequest extends BasicHttpRequest implements HttpEntityEnclosingRequest { private HttpEntity entity; public BasicHttpEntityEnclosingRequest(final String method, final String uri) { super(method, uri); } public BasicHttpEntityEnclosingRequest(final String method, final String uri, final ProtocolVersion ver) { super(method, uri, ver); } public BasicHttpEntityEnclosingRequest(final RequestLine requestline) { super(requestline); } public HttpEntity getEntity() { return this.entity; } public void setEntity(final HttpEntity entity) { this.entity = entity; } public boolean expectContinue() { Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for parsing lines in the HEAD section of an HTTP message. * There are individual methods for parsing a request line, a * status line, or a header line. * The lines to parse are passed in memory, the parser does not depend * on any specific IO mechanism. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public interface LineParser { /** * Parses the textual representation of a protocol version. * This is needed for parsing request lines (last element) * as well as status lines (first element). * * @param buffer a buffer holding the protocol version to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed protocol version * * @throws ParseException in case of a parse error */ ProtocolVersion parseProtocolVersion( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Checks whether there likely is a protocol version in a line. * This method implements a <i>heuristic</i> to check for a * likely protocol version specification. It does <i>not</i> * guarantee that {@link #parseProtocolVersion} would not * detect a parse error. * This can be used to detect garbage lines before a request * or status line. * * @param buffer a buffer holding the line to inspect * @param cursor the cursor at which to check for a protocol version, or * negative for "end of line". Whether the check tolerates * whitespace before or after the protocol version is * implementation dependent. * * @return <code>true</code> if there is a protocol version at the * argument index (possibly ignoring whitespace), * <code>false</code> otherwise */ boolean hasProtocolVersion( CharArrayBuffer buffer, ParserCursor cursor); /** * Parses a request line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed request line * * @throws ParseException in case of a parse error */ RequestLine parseRequestLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a status line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed status line * * @throws ParseException in case of a parse error */ StatusLine parseStatusLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Creates a header from a line. * The full header line is expected here. Header continuation lines * must be joined by the caller before invoking this method. * * @param buffer a buffer holding the full header line. * This buffer MUST NOT be re-used afterwards, since * the returned object may reference the contents later. * * @return the header in the argument buffer. * The returned object MAY be a wrapper for the argument buffer. * The argument buffer MUST NOT be re-used or changed afterwards. * * @throws ParseException in case of a parse error */ Header parseHeader(CharArrayBuffer buffer) 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.message; import java.util.List; import java.util.ArrayList; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic implementation for parsing header values into elements. * Instances of this class are stateless and thread-safe. * Derived classes are expected to maintain these properties. * * @since 4.0 */ public class BasicHeaderValueParser implements HeaderValueParser { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicHeaderValueParser} is not a singleton, there * can be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicHeaderValueParser DEFAULT = new BasicHeaderValueParser(); private final static char PARAM_DELIMITER = ';'; private final static char ELEM_DELIMITER = ','; private final static char[] ALL_DELIMITERS = new char[] { PARAM_DELIMITER, ELEM_DELIMITER }; // public default constructor /** * Parses elements with the given parser. * * @param value the header value to parse * @param parser the parser to use, or <code>null</code> for default * * @return array holding the header elements, never <code>null</code> */ public final static HeaderElement[] parseElements(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseElements(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public HeaderElement[] parseElements(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } List elements = new ArrayList(); while (!cursor.atEnd()) { HeaderElement element = parseHeaderElement(buffer, cursor); if (!(element.getName().length() == 0 && element.getValue() == null)) { elements.add(element); } } return (HeaderElement[]) elements.toArray(new HeaderElement[elements.size()]); } /** * Parses an element with the given parser. * * @param value the header element to parse * @param parser the parser to use, or <code>null</code> for default * * @return the parsed header element */ public final static HeaderElement parseHeaderElement(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseHeaderElement(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } NameValuePair nvp = parseNameValuePair(buffer, cursor); NameValuePair[] params = null; if (!cursor.atEnd()) { char ch = buffer.charAt(cursor.getPos() - 1); if (ch != ELEM_DELIMITER) { params = parseParameters(buffer, cursor); } } return createHeaderElement(nvp.getName(), nvp.getValue(), params); } /** * Creates a header element. * Called from {@link #parseHeaderElement}. * * @return a header element representing the argument */ protected HeaderElement createHeaderElement( final String name, final String value, final NameValuePair[] params) { return new BasicHeaderElement(name, value, params); } /** * Parses parameters with the given parser. * * @param value the parameter list to parse * @param parser the parser to use, or <code>null</code> for default * * @return array holding the parameters, never <code>null</code> */ public final static NameValuePair[] parseParameters(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseParameters(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public NameValuePair[] parseParameters(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int pos = cursor.getPos(); int indexTo = cursor.getUpperBound(); while (pos < indexTo) { char ch = buffer.charAt(pos); if (HTTP.isWhitespace(ch)) { pos++; } else { break; } } cursor.updatePos(pos); if (cursor.atEnd()) { return new NameValuePair[] {}; } List params = new ArrayList(); while (!cursor.atEnd()) { NameValuePair param = parseNameValuePair(buffer, cursor); params.add(param); char ch = buffer.charAt(cursor.getPos() - 1); if (ch == ELEM_DELIMITER) { break; } } return (NameValuePair[]) params.toArray(new NameValuePair[params.size()]); } /** * Parses a name-value-pair with the given parser. * * @param value the NVP to parse * @param parser the parser to use, or <code>null</code> for default * * @return the parsed name-value pair */ public final static NameValuePair parseNameValuePair(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseNameValuePair(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor) { return parseNameValuePair(buffer, cursor, ALL_DELIMITERS); } private static boolean isOneOf(final char ch, final char[] chs) { if (chs != null) { for (int i = 0; i < chs.length; i++) { if (ch == chs[i]) { return true; } } } return false; } public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } boolean terminated = false; int pos = cursor.getPos(); int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); // Find name String name = null; while (pos < indexTo) { char ch = buffer.charAt(pos); if (ch == '=') { break; } if (isOneOf(ch, delimiters)) { terminated = true; break; } pos++; } if (pos == indexTo) { terminated = true; name = buffer.substringTrimmed(indexFrom, indexTo); } else { name = buffer.substringTrimmed(indexFrom, pos); pos++; } if (terminated) { cursor.updatePos(pos); return createNameValuePair(name, null); } // Find value String value = null; int i1 = pos; boolean qouted = false; boolean escaped = false; while (pos < indexTo) { char ch = buffer.charAt(pos); if (ch == '"' && !escaped) { qouted = !qouted; } if (!qouted && !escaped && isOneOf(ch, delimiters)) { terminated = true; break; } if (escaped) { escaped = false; } else { escaped = qouted && ch == '\\'; } pos++; } int i2 = pos; // Trim leading white spaces while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) { i1++; } // Trim trailing white spaces while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) { i2--; } // Strip away quotes if necessary if (((i2 - i1) >= 2) && (buffer.charAt(i1) == '"') && (buffer.charAt(i2 - 1) == '"')) { i1++; i2--; } value = buffer.substring(i1, i2); if (terminated) { pos++; } cursor.updatePos(pos); return createNameValuePair(name, value); } /** * Creates a name-value pair. * Called from {@link #parseNameValuePair}. * * @param name the name * @param value the value, or <code>null</code> * * @return a name-value pair representing the arguments */ protected NameValuePair createNameValuePair(final String name, final String value) { return new BasicNameValuePair(name, value); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.io.Serializable; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.ParseException; /** * Basic implementation of {@link Header}. * * @since 4.0 */ public class BasicHeader implements Header, Cloneable, Serializable { private static final long serialVersionUID = -5427236326487562174L; private final String name; private final String value; /** * Constructor with name and value * * @param name the header name * @param value the header value */ public BasicHeader(final String name, final String value) { super(); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } this.name = name; this.value = value; } public String getName() { return this.name; } public String getValue() { return this.value; } public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.DEFAULT.formatHeader(null, this).toString(); } public HeaderElement[] getElements() throws ParseException { if (this.value != null) { // result intentionally not cached, it's probably not used again return BasicHeaderValueParser.parseElements(this.value, null); } else { return new HeaderElement[] {}; } } 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.message; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for formatting elements of a header value. * This is the complement to {@link HeaderValueParser}. * Instances of this interface are expected to be stateless and thread-safe. * * <p> * All formatting methods accept an optional buffer argument. * If a buffer is passed in, the formatted element will be appended * and the modified buffer is returned. If no buffer is passed in, * a new buffer will be created and filled with the formatted element. * In both cases, the caller is allowed to modify the returned buffer. * </p> * * @since 4.0 */ public interface HeaderValueFormatter { /** * Formats an array of header elements. * * @param buffer the buffer to append to, or * <code>null</code> to create a new buffer * @param elems the header elements to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * * @return a buffer with the formatted header elements. * If the <code>buffer</code> argument was not <code>null</code>, * that buffer will be used and returned. */ CharArrayBuffer formatElements(CharArrayBuffer buffer, HeaderElement[] elems, boolean quote); /** * Formats one header element. * * @param buffer the buffer to append to, or * <code>null</code> to create a new buffer * @param elem the header element to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * * @return a buffer with the formatted header element. * If the <code>buffer</code> argument was not <code>null</code>, * that buffer will be used and returned. */ CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer, HeaderElement elem, boolean quote); /** * Formats the parameters of a header element. * That's a list of name-value pairs, to be separated by semicolons. * This method will <i>not</i> generate a leading semicolon. * * @param buffer the buffer to append to, or * <code>null</code> to create a new buffer * @param nvps the parameters (name-value pairs) to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * * @return a buffer with the formatted parameters. * If the <code>buffer</code> argument was not <code>null</code>, * that buffer will be used and returned. */ CharArrayBuffer formatParameters(CharArrayBuffer buffer, NameValuePair[] nvps, boolean quote); /** * Formats one name-value pair, where the value is optional. * * @param buffer the buffer to append to, or * <code>null</code> to create a new buffer * @param nvp the name-value pair to format * @param quote <code>true</code> to always format with a quoted value, * <code>false</code> to use quotes only when necessary * * @return a buffer with the formatted name-value pair. * If the <code>buffer</code> argument was not <code>null</code>, * that buffer will be used and returned. */ CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer, NameValuePair nvp, boolean quote); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.io.Serializable; import org.apache.ogt.http.FormattedHeader; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.util.CharArrayBuffer; /** * This class represents a raw HTTP header whose content is parsed 'on demand' * only when the header value needs to be consumed. * * @since 4.0 */ public class BufferedHeader implements FormattedHeader, Cloneable, Serializable { private static final long serialVersionUID = -2768352615787625448L; /** * Header name. */ private final String name; /** * The buffer containing the entire header line. */ private final CharArrayBuffer buffer; /** * The beginning of the header value in the buffer */ private final int valuePos; /** * Creates a new header from a buffer. * The name of the header will be parsed immediately, * the value only if it is accessed. * * @param buffer the buffer containing the header to represent * * @throws ParseException in case of a parse error */ public BufferedHeader(final CharArrayBuffer buffer) throws ParseException { super(); if (buffer == null) { throw new IllegalArgumentException ("Char array buffer may not be null"); } int colon = buffer.indexOf(':'); if (colon == -1) { throw new ParseException ("Invalid header: " + buffer.toString()); } String s = buffer.substringTrimmed(0, colon); if (s.length() == 0) { throw new ParseException ("Invalid header: " + buffer.toString()); } this.buffer = buffer; this.name = s; this.valuePos = colon + 1; } public String getName() { return this.name; } public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } public HeaderElement[] getElements() throws ParseException { ParserCursor cursor = new ParserCursor(0, this.buffer.length()); cursor.updatePos(this.valuePos); return BasicHeaderValueParser.DEFAULT .parseElements(this.buffer, cursor); } public int getValuePos() { return this.valuePos; } public CharArrayBuffer getBuffer() { return this.buffer; } public String toString() { return this.buffer.toString(); } public Object clone() throws CloneNotSupportedException { // buffer is considered immutable // no need to make a copy of it return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic implementation for formatting header value elements. * Instances of this class are stateless and thread-safe. * Derived classes are expected to maintain these properties. * * @since 4.0 */ public class BasicHeaderValueFormatter implements HeaderValueFormatter { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicHeaderValueFormatter} is not a singleton, there * can be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicHeaderValueFormatter DEFAULT = new BasicHeaderValueFormatter(); /** * Special characters that can be used as separators in HTTP parameters. * These special characters MUST be in a quoted string to be used within * a parameter value . */ public final static String SEPARATORS = " ;,:@()<>\\\"/[]?={}\t"; /** * Unsafe special characters that must be escaped using the backslash * character */ public final static String UNSAFE_CHARS = "\"\\"; // public default constructor /** * Formats an array of header elements. * * @param elems the header elements to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * @param formatter the formatter to use, or <code>null</code> * for the {@link #DEFAULT default} * * @return the formatted header elements */ public final static String formatElements(final HeaderElement[] elems, final boolean quote, HeaderValueFormatter formatter) { if (formatter == null) formatter = BasicHeaderValueFormatter.DEFAULT; return formatter.formatElements(null, elems, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter public CharArrayBuffer formatElements(CharArrayBuffer buffer, final HeaderElement[] elems, final boolean quote) { if (elems == null) { throw new IllegalArgumentException ("Header element array must not be null."); } int len = estimateElementsLen(elems); if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } for (int i=0; i<elems.length; i++) { if (i > 0) { buffer.append(", "); } formatHeaderElement(buffer, elems[i], quote); } return buffer; } /** * Estimates the length of formatted header elements. * * @param elems the header elements to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateElementsLen(final HeaderElement[] elems) { if ((elems == null) || (elems.length < 1)) return 0; int result = (elems.length-1) * 2; // elements separated by ", " for (int i=0; i<elems.length; i++) { result += estimateHeaderElementLen(elems[i]); } return result; } /** * Formats a header element. * * @param elem the header element to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * @param formatter the formatter to use, or <code>null</code> * for the {@link #DEFAULT default} * * @return the formatted header element */ public final static String formatHeaderElement(final HeaderElement elem, boolean quote, HeaderValueFormatter formatter) { if (formatter == null) formatter = BasicHeaderValueFormatter.DEFAULT; return formatter.formatHeaderElement(null, elem, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter public CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer, final HeaderElement elem, final boolean quote) { if (elem == null) { throw new IllegalArgumentException ("Header element must not be null."); } int len = estimateHeaderElementLen(elem); if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } buffer.append(elem.getName()); final String value = elem.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i=0; i<parcnt; i++) { buffer.append("; "); formatNameValuePair(buffer, elem.getParameter(i), quote); } } return buffer; } /** * Estimates the length of a formatted header element. * * @param elem the header element to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateHeaderElementLen(final HeaderElement elem) { if (elem == null) return 0; int result = elem.getName().length(); // name final String value = elem.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } final int parcnt = elem.getParameterCount(); if (parcnt > 0) { for (int i=0; i<parcnt; i++) { result += 2 + // ; <param> estimateNameValuePairLen(elem.getParameter(i)); } } return result; } /** * Formats a set of parameters. * * @param nvps the parameters to format * @param quote <code>true</code> to always format with quoted values, * <code>false</code> to use quotes only when necessary * @param formatter the formatter to use, or <code>null</code> * for the {@link #DEFAULT default} * * @return the formatted parameters */ public final static String formatParameters(final NameValuePair[] nvps, final boolean quote, HeaderValueFormatter formatter) { if (formatter == null) formatter = BasicHeaderValueFormatter.DEFAULT; return formatter.formatParameters(null, nvps, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter public CharArrayBuffer formatParameters(CharArrayBuffer buffer, NameValuePair[] nvps, boolean quote) { if (nvps == null) { throw new IllegalArgumentException ("Parameters must not be null."); } int len = estimateParametersLen(nvps); if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } for (int i = 0; i < nvps.length; i++) { if (i > 0) { buffer.append("; "); } formatNameValuePair(buffer, nvps[i], quote); } return buffer; } /** * Estimates the length of formatted parameters. * * @param nvps the parameters to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateParametersLen(final NameValuePair[] nvps) { if ((nvps == null) || (nvps.length < 1)) return 0; int result = (nvps.length-1) * 2; // "; " between the parameters for (int i=0; i<nvps.length; i++) { result += estimateNameValuePairLen(nvps[i]); } return result; } /** * Formats a name-value pair. * * @param nvp the name-value pair to format * @param quote <code>true</code> to always format with a quoted value, * <code>false</code> to use quotes only when necessary * @param formatter the formatter to use, or <code>null</code> * for the {@link #DEFAULT default} * * @return the formatted name-value pair */ public final static String formatNameValuePair(final NameValuePair nvp, final boolean quote, HeaderValueFormatter formatter) { if (formatter == null) formatter = BasicHeaderValueFormatter.DEFAULT; return formatter.formatNameValuePair(null, nvp, quote).toString(); } // non-javadoc, see interface HeaderValueFormatter public CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer, final NameValuePair nvp, final boolean quote) { if (nvp == null) { throw new IllegalArgumentException ("NameValuePair must not be null."); } int len = estimateNameValuePairLen(nvp); if (buffer == null) { buffer = new CharArrayBuffer(len); } else { buffer.ensureCapacity(len); } buffer.append(nvp.getName()); final String value = nvp.getValue(); if (value != null) { buffer.append('='); doFormatValue(buffer, value, quote); } return buffer; } /** * Estimates the length of a formatted name-value pair. * * @param nvp the name-value pair to format, or <code>null</code> * * @return a length estimate, in number of characters */ protected int estimateNameValuePairLen(final NameValuePair nvp) { if (nvp == null) return 0; int result = nvp.getName().length(); // name final String value = nvp.getValue(); if (value != null) { // assume quotes, but no escaped characters result += 3 + value.length(); // ="value" } return result; } /** * Actually formats the value of a name-value pair. * This does not include a leading = character. * Called from {@link #formatNameValuePair formatNameValuePair}. * * @param buffer the buffer to append to, never <code>null</code> * @param value the value to append, never <code>null</code> * @param quote <code>true</code> to always format with quotes, * <code>false</code> to use quotes only when necessary */ protected void doFormatValue(final CharArrayBuffer buffer, final String value, boolean quote) { if (!quote) { for (int i = 0; (i < value.length()) && !quote; i++) { quote = isSeparator(value.charAt(i)); } } if (quote) { buffer.append('"'); } for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (isUnsafe(ch)) { buffer.append('\\'); } buffer.append(ch); } if (quote) { buffer.append('"'); } } /** * Checks whether a character is a {@link #SEPARATORS separator}. * * @param ch the character to check * * @return <code>true</code> if the character is a separator, * <code>false</code> otherwise */ protected boolean isSeparator(char ch) { return SEPARATORS.indexOf(ch) >= 0; } /** * Checks whether a character is {@link #UNSAFE_CHARS unsafe}. * * @param ch the character to check * * @return <code>true</code> if the character is unsafe, * <code>false</code> otherwise */ protected boolean isUnsafe(char ch) { return UNSAFE_CHARS.indexOf(ch) >= 0; } } // class BasicHeaderValueFormatter
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.util.CharArrayBuffer; import org.apache.ogt.http.util.LangUtils; /** * Basic implementation of {@link HeaderElement} * * @since 4.0 */ public class BasicHeaderElement implements HeaderElement, Cloneable { private final String name; private final String value; private final NameValuePair[] parameters; /** * Constructor with name, value and parameters. * * @param name header element name * @param value header element value. May be <tt>null</tt> * @param parameters header element parameters. May be <tt>null</tt>. * Parameters are copied by reference, not by value */ public BasicHeaderElement( final String name, final String value, final NameValuePair[] parameters) { super(); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } this.name = name; this.value = value; if (parameters != null) { this.parameters = parameters; } else { this.parameters = new NameValuePair[] {}; } } /** * Constructor with name and value. * * @param name header element name * @param value header element value. May be <tt>null</tt> */ public BasicHeaderElement(final String name, final String value) { this(name, value, null); } public String getName() { return this.name; } public String getValue() { return this.value; } public NameValuePair[] getParameters() { return (NameValuePair[])this.parameters.clone(); } public int getParameterCount() { return this.parameters.length; } public NameValuePair getParameter(int index) { // ArrayIndexOutOfBoundsException is appropriate return this.parameters[index]; } public NameValuePair getParameterByName(final String name) { if (name == null) { throw new IllegalArgumentException("Name may not be null"); } NameValuePair found = null; for (int i = 0; i < this.parameters.length; i++) { NameValuePair current = this.parameters[ i ]; if (current.getName().equalsIgnoreCase(name)) { found = current; break; } } return found; } public boolean equals(final Object object) { if (this == object) return true; if (object instanceof HeaderElement) { BasicHeaderElement that = (BasicHeaderElement) object; return this.name.equals(that.name) && LangUtils.equals(this.value, that.value) && LangUtils.equals(this.parameters, that.parameters); } else { return false; } } public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.name); hash = LangUtils.hashCode(hash, this.value); for (int i = 0; i < this.parameters.length; i++) { hash = LangUtils.hashCode(hash, this.parameters[i]); } return hash; } public String toString() { CharArrayBuffer buffer = new CharArrayBuffer(64); buffer.append(this.name); if (this.value != null) { buffer.append("="); buffer.append(this.value); } for (int i = 0; i < this.parameters.length; i++) { buffer.append("; "); buffer.append(this.parameters[i]); } return buffer.toString(); } public Object clone() throws CloneNotSupportedException { // parameters array is considered immutable // no need to make a copy of it return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.io.Serializable; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.util.CharArrayBuffer; import org.apache.ogt.http.util.LangUtils; /** * Basic implementation of {@link NameValuePair}. * * @since 4.0 */ public class BasicNameValuePair implements NameValuePair, Cloneable, Serializable { private static final long serialVersionUID = -6437800749411518984L; private final String name; private final String value; /** * Default Constructor taking a name and a value. The value may be null. * * @param name The name. * @param value The value. */ public BasicNameValuePair(final String name, final String value) { super(); if (name == null) { throw new IllegalArgumentException("Name may not be null"); } this.name = name; this.value = value; } public String getName() { return this.name; } public String getValue() { return this.value; } public String toString() { // don't call complex default formatting for a simple toString if (this.value == null) { return name; } else { int len = this.name.length() + 1 + this.value.length(); CharArrayBuffer buffer = new CharArrayBuffer(len); buffer.append(this.name); buffer.append("="); buffer.append(this.value); return buffer.toString(); } } public boolean equals(final Object object) { if (this == object) return true; if (object instanceof NameValuePair) { BasicNameValuePair that = (BasicNameValuePair) object; return this.name.equals(that.name) && LangUtils.equals(this.value, that.value); } else { return false; } } public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.name); hash = LangUtils.hashCode(hash, this.value); 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.message; import java.util.Iterator; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.params.BasicHttpParams; import org.apache.ogt.http.params.HttpParams; /** * Basic implementation of {@link HttpMessage}. * * @since 4.0 */ public abstract class AbstractHttpMessage implements HttpMessage { protected HeaderGroup headergroup; protected HttpParams params; protected AbstractHttpMessage(final HttpParams params) { super(); this.headergroup = new HeaderGroup(); this.params = params; } protected AbstractHttpMessage() { this(null); } // non-javadoc, see interface HttpMessage public boolean containsHeader(String name) { return this.headergroup.containsHeader(name); } // non-javadoc, see interface HttpMessage public Header[] getHeaders(final String name) { return this.headergroup.getHeaders(name); } // non-javadoc, see interface HttpMessage public Header getFirstHeader(final String name) { return this.headergroup.getFirstHeader(name); } // non-javadoc, see interface HttpMessage public Header getLastHeader(final String name) { return this.headergroup.getLastHeader(name); } // non-javadoc, see interface HttpMessage public Header[] getAllHeaders() { return this.headergroup.getAllHeaders(); } // non-javadoc, see interface HttpMessage public void addHeader(final Header header) { this.headergroup.addHeader(header); } // non-javadoc, see interface HttpMessage public void addHeader(final String name, final String value) { if (name == null) { throw new IllegalArgumentException("Header name may not be null"); } this.headergroup.addHeader(new BasicHeader(name, value)); } // non-javadoc, see interface HttpMessage public void setHeader(final Header header) { this.headergroup.updateHeader(header); } // non-javadoc, see interface HttpMessage public void setHeader(final String name, final String value) { if (name == null) { throw new IllegalArgumentException("Header name may not be null"); } this.headergroup.updateHeader(new BasicHeader(name, value)); } // non-javadoc, see interface HttpMessage public void setHeaders(final Header[] headers) { this.headergroup.setHeaders(headers); } // non-javadoc, see interface HttpMessage public void removeHeader(final Header header) { this.headergroup.removeHeader(header); } // non-javadoc, see interface HttpMessage public void removeHeaders(final String name) { if (name == null) { return; } for (Iterator i = this.headergroup.iterator(); i.hasNext(); ) { Header header = (Header) i.next(); if (name.equalsIgnoreCase(header.getName())) { i.remove(); } } } // non-javadoc, see interface HttpMessage public HeaderIterator headerIterator() { return this.headergroup.iterator(); } // non-javadoc, see interface HttpMessage public HeaderIterator headerIterator(String name) { return this.headergroup.iterator(name); } // non-javadoc, see interface HttpMessage public HttpParams getParams() { if (this.params == null) { this.params = new BasicHttpParams(); } return this.params; } // non-javadoc, see interface HttpMessage public void setParams(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.params = 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.message; import org.apache.ogt.http.util.CharArrayBuffer; /** * This class represents a context of a parsing operation: * <ul> * <li>the current position the parsing operation is expected to start at</li> * <li>the bounds limiting the scope of the parsing operation</li> * </ul> * * @since 4.0 */ public class ParserCursor { private final int lowerBound; private final int upperBound; private int pos; public ParserCursor(int lowerBound, int upperBound) { super(); if (lowerBound < 0) { throw new IndexOutOfBoundsException("Lower bound cannot be negative"); } if (lowerBound > upperBound) { throw new IndexOutOfBoundsException("Lower bound cannot be greater then upper bound"); } this.lowerBound = lowerBound; this.upperBound = upperBound; this.pos = lowerBound; } public int getLowerBound() { return this.lowerBound; } public int getUpperBound() { return this.upperBound; } public int getPos() { return this.pos; } public void updatePos(int pos) { if (pos < this.lowerBound) { throw new IndexOutOfBoundsException("pos: "+pos+" < lowerBound: "+this.lowerBound); } if (pos > this.upperBound) { throw new IndexOutOfBoundsException("pos: "+pos+" > upperBound: "+this.upperBound); } this.pos = pos; } public boolean atEnd() { return this.pos >= this.upperBound; } public String toString() { CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append('['); buffer.append(Integer.toString(this.lowerBound)); buffer.append('>'); buffer.append(Integer.toString(this.pos)); buffer.append('>'); buffer.append(Integer.toString(this.upperBound)); 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.ogt.http.message; import java.util.List; import java.util.NoSuchElementException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; /** * Implementation of a {@link HeaderIterator} based on a {@link List}. * For use by {@link HeaderGroup}. * * @since 4.0 */ public class BasicListHeaderIterator implements HeaderIterator { /** * A list of headers to iterate over. * Not all elements of this array are necessarily part of the iteration. */ protected final List allHeaders; /** * The position of the next header in {@link #allHeaders allHeaders}. * Negative if the iteration is over. */ protected int currentIndex; /** * The position of the last returned header. * Negative if none has been returned so far. */ protected int lastIndex; /** * The header name to filter by. * <code>null</code> to iterate over all headers in the array. */ protected String headerName; /** * Creates a new header iterator. * * @param headers a list of headers over which to iterate * @param name the name of the headers over which to iterate, or * <code>null</code> for any */ public BasicListHeaderIterator(List headers, String name) { if (headers == null) { throw new IllegalArgumentException ("Header list must not be null."); } this.allHeaders = headers; this.headerName = name; this.currentIndex = findNext(-1); this.lastIndex = -1; } /** * Determines the index of the next header. * * @param from one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ protected int findNext(int from) { if (from < -1) return -1; final int to = this.allHeaders.size()-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return <code>true</code> if the header should be part of the * iteration, <code>false</code> to skip */ protected boolean filterHeader(int index) { if (this.headerName == null) return true; // non-header elements, including null, will trigger exceptions final String name = ((Header)this.allHeaders.get(index)).getName(); return this.headerName.equalsIgnoreCase(name); } // non-javadoc, see interface HeaderIterator public boolean hasNext() { return (this.currentIndex >= 0); } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public Header nextHeader() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.lastIndex = current; this.currentIndex = findNext(current); return (Header) this.allHeaders.get(current); } /** * Returns the next header. * Same as {@link #nextHeader nextHeader}, but not type-safe. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removes the header that was returned last. */ public void remove() throws UnsupportedOperationException { if (this.lastIndex < 0) { throw new IllegalStateException("No header to remove."); } this.allHeaders.remove(this.lastIndex); this.lastIndex = -1; this.currentIndex--; // adjust for the removed element } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.util.Locale; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.ReasonPhraseCatalog; import org.apache.ogt.http.StatusLine; /** * Basic implementation of {@link HttpResponse}. * * @since 4.0 */ public class BasicHttpResponse extends AbstractHttpMessage implements HttpResponse { private StatusLine statusline; private HttpEntity entity; private ReasonPhraseCatalog reasonCatalog; private Locale locale; /** * Creates a new response. * This is the constructor to which all others map. * * @param statusline the status line * @param catalog the reason phrase catalog, or * <code>null</code> to disable automatic * reason phrase lookup * @param locale the locale for looking up reason phrases, or * <code>null</code> for the system locale */ public BasicHttpResponse(final StatusLine statusline, final ReasonPhraseCatalog catalog, final Locale locale) { super(); if (statusline == null) { throw new IllegalArgumentException("Status line may not be null."); } this.statusline = statusline; this.reasonCatalog = catalog; this.locale = (locale != null) ? locale : Locale.getDefault(); } /** * Creates a response from a status line. * The response will not have a reason phrase catalog and * use the system default locale. * * @param statusline the status line */ public BasicHttpResponse(final StatusLine statusline) { this(statusline, null, null); } /** * Creates a response from elements of a status line. * The response will not have a reason phrase catalog and * use the system default locale. * * @param ver the protocol version of the response * @param code the status code of the response * @param reason the reason phrase to the status code, or * <code>null</code> */ public BasicHttpResponse(final ProtocolVersion ver, final int code, final String reason) { this(new BasicStatusLine(ver, code, reason), null, null); } // non-javadoc, see interface HttpMessage public ProtocolVersion getProtocolVersion() { return this.statusline.getProtocolVersion(); } // non-javadoc, see interface HttpResponse public StatusLine getStatusLine() { return this.statusline; } // non-javadoc, see interface HttpResponse public HttpEntity getEntity() { return this.entity; } // non-javadoc, see interface HttpResponse public Locale getLocale() { return this.locale; } // non-javadoc, see interface HttpResponse public void setStatusLine(final StatusLine statusline) { if (statusline == null) { throw new IllegalArgumentException("Status line may not be null"); } this.statusline = statusline; } // non-javadoc, see interface HttpResponse public void setStatusLine(final ProtocolVersion ver, final int code) { // arguments checked in BasicStatusLine constructor this.statusline = new BasicStatusLine(ver, code, getReason(code)); } // non-javadoc, see interface HttpResponse public void setStatusLine(final ProtocolVersion ver, final int code, final String reason) { // arguments checked in BasicStatusLine constructor this.statusline = new BasicStatusLine(ver, code, reason); } // non-javadoc, see interface HttpResponse public void setStatusCode(int code) { // argument checked in BasicStatusLine constructor ProtocolVersion ver = this.statusline.getProtocolVersion(); this.statusline = new BasicStatusLine(ver, code, getReason(code)); } // non-javadoc, see interface HttpResponse public void setReasonPhrase(String reason) { if ((reason != null) && ((reason.indexOf('\n') >= 0) || (reason.indexOf('\r') >= 0)) ) { throw new IllegalArgumentException("Line break in reason phrase."); } this.statusline = new BasicStatusLine(this.statusline.getProtocolVersion(), this.statusline.getStatusCode(), reason); } // non-javadoc, see interface HttpResponse public void setEntity(final HttpEntity entity) { this.entity = entity; } // non-javadoc, see interface HttpResponse public void setLocale(Locale loc) { if (loc == null) { throw new IllegalArgumentException("Locale may not be null."); } this.locale = loc; final int code = this.statusline.getStatusCode(); this.statusline = new BasicStatusLine (this.statusline.getProtocolVersion(), code, getReason(code)); } /** * Looks up a reason phrase. * This method evaluates the currently set catalog and locale. * It also handles a missing catalog. * * @param code the status code for which to look up the reason * * @return the reason phrase, or <code>null</code> if there is none */ protected String getReason(int code) { return (this.reasonCatalog == null) ? null : this.reasonCatalog.getReason(code, this.locale); } public String toString() { return this.statusline + " " + this.headergroup; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.message; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.util.CharArrayBuffer; /** * A class for combining a set of headers. * This class allows for multiple headers with the same name and * keeps track of the order in which headers were added. * * * @since 4.0 */ public class HeaderGroup implements Cloneable, Serializable { private static final long serialVersionUID = 2608834160639271617L; /** The list of headers for this group, in the order in which they were added */ private final List headers; /** * Constructor for HeaderGroup. */ public HeaderGroup() { this.headers = new ArrayList(16); } /** * Removes any contained headers. */ public void clear() { headers.clear(); } /** * Adds the given header to the group. The order in which this header was * added is preserved. * * @param header the header to add */ public void addHeader(Header header) { if (header == null) { return; } headers.add(header); } /** * Removes the given header. * * @param header the header to remove */ public void removeHeader(Header header) { if (header == null) { return; } headers.remove(header); } /** * Replaces the first occurence of the header with the same name. If no header with * the same name is found the given header is added to the end of the list. * * @param header the new header that should replace the first header with the same * name if present in the list. */ public void updateHeader(Header header) { if (header == null) { return; } for (int i = 0; i < this.headers.size(); i++) { Header current = (Header) this.headers.get(i); if (current.getName().equalsIgnoreCase(header.getName())) { this.headers.set(i, header); return; } } this.headers.add(header); } /** * Sets all of the headers contained within this group overriding any * existing headers. The headers are added in the order in which they appear * in the array. * * @param headers the headers to set */ public void setHeaders(Header[] headers) { clear(); if (headers == null) { return; } for (int i = 0; i < headers.length; i++) { this.headers.add(headers[i]); } } /** * Gets a header representing all of the header values with the given name. * If more that one header with the given name exists the values will be * combined with a "," as per RFC 2616. * * <p>Header name comparison is case insensitive. * * @param name the name of the header(s) to get * @return a header with a condensed value or <code>null</code> if no * headers by the given name are present */ public Header getCondensedHeader(String name) { Header[] headers = getHeaders(name); if (headers.length == 0) { return null; } else if (headers.length == 1) { return headers[0]; } else { CharArrayBuffer valueBuffer = new CharArrayBuffer(128); valueBuffer.append(headers[0].getValue()); for (int i = 1; i < headers.length; i++) { valueBuffer.append(", "); valueBuffer.append(headers[i].getValue()); } return new BasicHeader(name.toLowerCase(Locale.ENGLISH), valueBuffer.toString()); } } /** * Gets all of the headers with the given name. The returned array * maintains the relative order in which the headers were added. * * <p>Header name comparison is case insensitive. * * @param name the name of the header(s) to get * * @return an array of length >= 0 */ public Header[] getHeaders(String name) { ArrayList headersFound = new ArrayList(); for (int i = 0; i < headers.size(); i++) { Header header = (Header) headers.get(i); if (header.getName().equalsIgnoreCase(name)) { headersFound.add(header); } } return (Header[]) headersFound.toArray(new Header[headersFound.size()]); } /** * Gets the first header with the given name. * * <p>Header name comparison is case insensitive. * * @param name the name of the header to get * @return the first header or <code>null</code> */ public Header getFirstHeader(String name) { for (int i = 0; i < headers.size(); i++) { Header header = (Header) headers.get(i); if (header.getName().equalsIgnoreCase(name)) { return header; } } return null; } /** * Gets the last header with the given name. * * <p>Header name comparison is case insensitive. * * @param name the name of the header to get * @return the last header or <code>null</code> */ public Header getLastHeader(String name) { // start at the end of the list and work backwards for (int i = headers.size() - 1; i >= 0; i--) { Header header = (Header) headers.get(i); if (header.getName().equalsIgnoreCase(name)) { return header; } } return null; } /** * Gets all of the headers contained within this group. * * @return an array of length >= 0 */ public Header[] getAllHeaders() { return (Header[]) headers.toArray(new Header[headers.size()]); } /** * Tests if headers with the given name are contained within this group. * * <p>Header name comparison is case insensitive. * * @param name the header name to test for * @return <code>true</code> if at least one header with the name is * contained, <code>false</code> otherwise */ public boolean containsHeader(String name) { for (int i = 0; i < headers.size(); i++) { Header header = (Header) headers.get(i); if (header.getName().equalsIgnoreCase(name)) { return true; } } return false; } /** * Returns an iterator over this group of headers. * * @return iterator over this group of headers. * * @since 4.0 */ public HeaderIterator iterator() { return new BasicListHeaderIterator(this.headers, null); } /** * Returns an iterator over the headers with a given name in this group. * * @param name the name of the headers over which to iterate, or * <code>null</code> for all headers * * @return iterator over some headers in this group. * * @since 4.0 */ public HeaderIterator iterator(final String name) { return new BasicListHeaderIterator(this.headers, name); } /** * Returns a copy of this object * * @return copy of this object * * @since 4.0 */ public HeaderGroup copy() { HeaderGroup clone = new HeaderGroup(); clone.headers.addAll(this.headers); return clone; } public Object clone() throws CloneNotSupportedException { HeaderGroup clone = (HeaderGroup) super.clone(); clone.headers.clear(); clone.headers.addAll(this.headers); return clone; } public String toString() { return this.headers.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.ogt.http.params; /** * Thread-safe extension of the {@link BasicHttpParams}. * * @since 4.1 */ public class SyncBasicHttpParams extends BasicHttpParams { private static final long serialVersionUID = 5387834869062660642L; public SyncBasicHttpParams() { super(); } public synchronized boolean removeParameter(final String name) { return super.removeParameter(name); } public synchronized HttpParams setParameter(final String name, final Object value) { return super.setParameter(name, value); } public synchronized Object getParameter(final String name) { return super.getParameter(name); } public synchronized boolean isParameterSet(final String name) { return super.isParameterSet(name); } public synchronized boolean isParameterSetLocally(final String name) { return super.isParameterSetLocally(name); } public synchronized void setParameters(final String[] names, final Object value) { super.setParameters(names, value); } public synchronized void clear() { super.clear(); } public synchronized 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.params; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.protocol.HTTP; /** * Utility class for accessing protocol parameters in {@link HttpParams}. * * @since 4.0 * * @see CoreProtocolPNames */ public final class HttpProtocolParams implements CoreProtocolPNames { private HttpProtocolParams() { super(); } /** * Obtains value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter. * If not set, defaults to <code>US-ASCII</code>. * * @param params HTTP parameters. * @return HTTP element charset. */ public static String getHttpElementCharset(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String charset = (String) params.getParameter (CoreProtocolPNames.HTTP_ELEMENT_CHARSET); if (charset == null) { charset = HTTP.DEFAULT_PROTOCOL_CHARSET; } return charset; } /** * Sets value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter. * * @param params HTTP parameters. * @param charset HTTP element charset. */ public static void setHttpElementCharset(final HttpParams params, final String charset) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, charset); } /** * Obtains value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. * If not set, defaults to <code>ISO-8859-1</code>. * * @param params HTTP parameters. * @return HTTP content charset. */ public static String getContentCharset(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String charset = (String) params.getParameter (CoreProtocolPNames.HTTP_CONTENT_CHARSET); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } return charset; } /** * Sets value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter. * * @param params HTTP parameters. * @param charset HTTP content charset. */ public static void setContentCharset(final HttpParams params, final String charset) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); } /** * Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. * If not set, defaults to {@link HttpVersion#HTTP_1_1}. * * @param params HTTP parameters. * @return HTTP protocol version. */ public static ProtocolVersion getVersion(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Object param = params.getParameter (CoreProtocolPNames.PROTOCOL_VERSION); if (param == null) { return HttpVersion.HTTP_1_1; } return (ProtocolVersion)param; } /** * Sets value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter. * * @param params HTTP parameters. * @param version HTTP protocol version. */ public static void setVersion(final HttpParams params, final ProtocolVersion version) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, version); } /** * Obtains value of the {@link CoreProtocolPNames#USER_AGENT} parameter. * If not set, returns <code>null</code>. * * @param params HTTP parameters. * @return User agent string. */ public static String getUserAgent(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return (String) params.getParameter(CoreProtocolPNames.USER_AGENT); } /** * Sets value of the {@link CoreProtocolPNames#USER_AGENT} parameter. * * @param params HTTP parameters. * @param useragent User agent string. */ public static void setUserAgent(final HttpParams params, final String useragent) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setParameter(CoreProtocolPNames.USER_AGENT, useragent); } /** * Obtains value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. * If not set, returns <code>false</code>. * * @param params HTTP parameters. * @return User agent string. */ public static boolean useExpectContinue(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter (CoreProtocolPNames.USE_EXPECT_CONTINUE, false); } /** * Sets value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter. * * @param params HTTP parameters. * @param b expect-continue flag. */ public static void setUseExpectContinue(final HttpParams params, boolean b) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, b); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.params; /** * HttpParams interface represents a collection of immutable values that define * a runtime behavior of a component. HTTP parameters should be simple objects: * integers, doubles, strings, collections and objects that remain immutable * at runtime. HttpParams is expected to be used in 'write once - read many' mode. * Once initialized, HTTP parameters are not expected to mutate in * the course of HTTP message processing. * <p> * The purpose of this interface is to define a behavior of other components. * Usually each complex component has its own HTTP parameter collection. * <p> * Instances of this interface can be linked together to form a hierarchy. * In the simplest form one set of parameters can use content of another one * to obtain default values of parameters not present in the local set. * * @see DefaultedHttpParams * * @since 4.0 */ public interface HttpParams { /** * Obtains the value of the given parameter. * * @param name the parent name. * * @return an object that represents the value of the parameter, * <code>null</code> if the parameter is not set or if it * is explicitly set to <code>null</code> * * @see #setParameter(String, Object) */ Object getParameter(String name); /** * Assigns the value to the parameter with the given name. * * @param name parameter name * @param value parameter value */ HttpParams setParameter(String name, Object value); /** * Creates a copy of these parameters. * * @return a new set of parameters holding the same values as this one * * @deprecated */ HttpParams copy(); /** * Removes the parameter with the specified name. * * @param name parameter name * * @return true if the parameter existed and has been removed, false else. */ boolean removeParameter(String name); /** * Returns a {@link Long} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Long} that represents the value of the parameter. * * @see #setLongParameter(String, long) */ long getLongParameter(String name, long defaultValue); /** * Assigns a {@link Long} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setLongParameter(String name, long value); /** * Returns an {@link Integer} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Integer} that represents the value of the parameter. * * @see #setIntParameter(String, int) */ int getIntParameter(String name, int defaultValue); /** * Assigns an {@link Integer} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setIntParameter(String name, int value); /** * Returns a {@link Double} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Double} that represents the value of the parameter. * * @see #setDoubleParameter(String, double) */ double getDoubleParameter(String name, double defaultValue); /** * Assigns a {@link Double} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setDoubleParameter(String name, double value); /** * Returns a {@link Boolean} parameter value with the given name. * If the parameter is not explicitly set, the default value is returned. * * @param name the parent name. * @param defaultValue the default value. * * @return a {@link Boolean} that represents the value of the parameter. * * @see #setBooleanParameter(String, boolean) */ boolean getBooleanParameter(String name, boolean defaultValue); /** * Assigns a {@link Boolean} to the parameter with the given name * * @param name parameter name * @param value parameter value */ HttpParams setBooleanParameter(String name, boolean value); /** * Checks if a boolean parameter is set to <code>true</code>. * * @param name parameter name * * @return <tt>true</tt> if the parameter is set to value <tt>true</tt>, * <tt>false</tt> if it is not set or set to <code>false</code> */ boolean isParameterTrue(String name); /** * Checks if a boolean parameter is not set or <code>false</code>. * * @param name parameter name * * @return <tt>true</tt> if the parameter is either not set or * set to value <tt>false</tt>, * <tt>false</tt> if it is set to <code>true</code> */ boolean isParameterFalse(String name); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.params; /** * {@link HttpParams} implementation that delegates resolution of a parameter * to the given default {@link HttpParams} instance if the parameter is not * present in the local one. The state of the local collection can be mutated, * whereas the default collection is treated as read-only. * * @since 4.0 */ public final class DefaultedHttpParams extends AbstractHttpParams { private final HttpParams local; private final HttpParams defaults; /** * Create the defaulted set of HttpParams. * * @param local the mutable set of HttpParams * @param defaults the default set of HttpParams, not mutated by this class */ public DefaultedHttpParams(final HttpParams local, final HttpParams defaults) { super(); if (local == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.local = local; this.defaults = defaults; } /** * Creates a copy of the local collection with the same default * * @deprecated */ public HttpParams copy() { HttpParams clone = this.local.copy(); return new DefaultedHttpParams(clone, this.defaults); } /** * Retrieves the value of the parameter from the local collection and, if the * parameter is not set locally, delegates its resolution to the default * collection. */ public Object getParameter(final String name) { Object obj = this.local.getParameter(name); if (obj == null && this.defaults != null) { obj = this.defaults.getParameter(name); } return obj; } /** * Attempts to remove the parameter from the local collection. This method * <i>does not</i> modify the default collection. */ public boolean removeParameter(final String name) { return this.local.removeParameter(name); } /** * Sets the parameter in the local collection. This method <i>does not</i> * modify the default collection. */ public HttpParams setParameter(final String name, final Object value) { return this.local.setParameter(name, value); } /** * * @return the default HttpParams collection */ public HttpParams getDefaults() { return this.defaults; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; import org.apache.ogt.http.HttpVersion; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate HTTP protocol parameters using Java Beans * conventions. * * @since 4.0 */ public class HttpProtocolParamBean extends HttpAbstractParamBean { public HttpProtocolParamBean (final HttpParams params) { super(params); } public void setHttpElementCharset (final String httpElementCharset) { HttpProtocolParams.setHttpElementCharset(params, httpElementCharset); } public void setContentCharset (final String contentCharset) { HttpProtocolParams.setContentCharset(params, contentCharset); } public void setVersion (final HttpVersion version) { HttpProtocolParams.setVersion(params, version); } public void setUserAgent (final String userAgent) { HttpProtocolParams.setUserAgent(params, userAgent); } public void setUseExpectContinue (boolean useExpectContinue) { HttpProtocolParams.setUseExpectContinue(params, useExpectContinue); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; /** * @since 4.0 */ public abstract class HttpAbstractParamBean { protected final HttpParams params; public HttpAbstractParamBean (final HttpParams params) { if (params == null) throw new IllegalArgumentException("HTTP parameters may not be null"); this.params = 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.params; /** * This is a Java Bean class that can be used to wrap an instance of * {@link HttpParams} and manipulate HTTP connection parameters using Java Beans * conventions. * * @since 4.0 */ public class HttpConnectionParamBean extends HttpAbstractParamBean { public HttpConnectionParamBean (final HttpParams params) { super(params); } public void setSoTimeout (int soTimeout) { HttpConnectionParams.setSoTimeout(params, soTimeout); } public void setTcpNoDelay (boolean tcpNoDelay) { HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay); } public void setSocketBufferSize (int socketBufferSize) { HttpConnectionParams.setSocketBufferSize(params, socketBufferSize); } public void setLinger (int linger) { HttpConnectionParams.setLinger(params, linger); } public void setConnectionTimeout (int connectionTimeout) { HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); } public void setStaleCheckingEnabled (boolean staleCheckingEnabled) { HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; /** * Defines parameter names for connections in HttpCore. * * @since 4.0 */ public interface CoreConnectionPNames { /** * Defines the socket timeout (<code>SO_TIMEOUT</code>) in milliseconds, * which is the timeout for waiting for data or, put differently, * a maximum period inactivity between two consecutive data packets). * A timeout value of zero is interpreted as an infinite timeout. * <p> * This parameter expects a value of type {@link Integer}. * </p> * @see java.net.SocketOptions#SO_TIMEOUT */ public static final String SO_TIMEOUT = "http.socket.timeout"; /** * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm * tries to conserve bandwidth by minimizing the number of segments that are * sent. When applications wish to decrease network latency and increase * performance, they can disable Nagle's algorithm (that is enable * TCP_NODELAY). Data will be sent earlier, at the cost of an increase * in bandwidth consumption. * <p> * This parameter expects a value of type {@link Boolean}. * </p> * @see java.net.SocketOptions#TCP_NODELAY */ public static final String TCP_NODELAY = "http.tcp.nodelay"; /** * Determines the size of the internal socket buffer used to buffer data * while receiving / transmitting HTTP messages. * <p> * This parameter expects a value of type {@link Integer}. * </p> */ public static final String SOCKET_BUFFER_SIZE = "http.socket.buffer-size"; /** * Sets SO_LINGER with the specified linger time in seconds. The maximum * timeout value is platform specific. Value <code>0</code> implies that * the option is disabled. Value <code>-1</code> implies that the JRE * default is used. The setting only affects the socket close operation. * <p> * This parameter expects a value of type {@link Integer}. * </p> * @see java.net.SocketOptions#SO_LINGER */ public static final String SO_LINGER = "http.socket.linger"; /** * Defines whether the socket can be bound even though a previous connection is * still in a timeout state. * <p> * This parameter expects a value of type {@link Boolean}. * </p> * @see java.net.Socket#setReuseAddress(boolean) * * @since 4.1 */ public static final String SO_REUSEADDR = "http.socket.reuseaddr"; /** * Determines the timeout in milliseconds until a connection is established. * A timeout value of zero is interpreted as an infinite timeout. * <p> * Please note this parameter can only be applied to connections that * are bound to a particular local address. * <p> * This parameter expects a value of type {@link Integer}. * </p> */ public static final String CONNECTION_TIMEOUT = "http.connection.timeout"; /** * Determines whether stale connection check is to be used. The stale * connection check can cause up to 30 millisecond overhead per request and * should be used only when appropriate. For performance critical * operations this check should be disabled. * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck"; /** * Determines the maximum line length limit. If set to a positive value, * any HTTP line exceeding this limit will cause an IOException. A negative * or zero value will effectively disable the check. * <p> * This parameter expects a value of type {@link Integer}. * </p> */ public static final String MAX_LINE_LENGTH = "http.connection.max-line-length"; /** * Determines the maximum HTTP header count allowed. If set to a positive * value, the number of HTTP headers received from the data stream exceeding * this limit will cause an IOException. A negative or zero value will * effectively disable the check. * <p> * This parameter expects a value of type {@link Integer}. * </p> */ public static final String MAX_HEADER_COUNT = "http.connection.max-header-count"; /** * Defines the size limit below which data chunks should be buffered in a session I/O buffer * in order to minimize native method invocations on the underlying network socket. * The optimal value of this parameter can be platform specific and defines a trade-off * between performance of memory copy operations and that of native method invocation. * <p> * This parameter expects a value of type {@link Integer}. * </p> * * @since 4.1 */ public static final String MIN_CHUNK_LIMIT = "http.connection.min-chunk-limit"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; /** * Utility class for accessing connection parameters in {@link HttpParams}. * * @since 4.0 */ public final class HttpConnectionParams implements CoreConnectionPNames { private HttpConnectionParams() { super(); } /** * Obtains value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter. * If not set, defaults to <code>0</code>. * * @param params HTTP parameters. * @return SO_TIMEOUT. */ public static int getSoTimeout(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0); } /** * Sets value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter. * * @param params HTTP parameters. * @param timeout SO_TIMEOUT. */ public static void setSoTimeout(final HttpParams params, int timeout) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } /** * Obtains value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. * If not set, defaults to <code>false</code>. * * @param params HTTP parameters. * @return SO_REUSEADDR. * * @since 4.1 */ public static boolean getSoReuseaddr(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, false); } /** * Sets value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter. * * @param params HTTP parameters. * @param reuseaddr SO_REUSEADDR. * * @since 4.1 */ public static void setSoReuseaddr(final HttpParams params, boolean reuseaddr) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, reuseaddr); } /** * Obtains value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. * If not set, defaults to <code>true</code>. * * @param params HTTP parameters. * @return Nagle's algorithm flag */ public static boolean getTcpNoDelay(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter (CoreConnectionPNames.TCP_NODELAY, true); } /** * Sets value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter. * * @param params HTTP parameters. * @param value Nagle's algorithm flag */ public static void setTcpNoDelay(final HttpParams params, boolean value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, value); } /** * Obtains value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} * parameter. If not set, defaults to <code>-1</code>. * * @param params HTTP parameters. * @return socket buffer size */ public static int getSocketBufferSize(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getIntParameter (CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1); } /** * Sets value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE} * parameter. * * @param params HTTP parameters. * @param size socket buffer size */ public static void setSocketBufferSize(final HttpParams params, int size) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, size); } /** * Obtains value of the {@link CoreConnectionPNames#SO_LINGER} parameter. * If not set, defaults to <code>-1</code>. * * @param params HTTP parameters. * @return SO_LINGER. */ public static int getLinger(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1); } /** * Sets value of the {@link CoreConnectionPNames#SO_LINGER} parameter. * * @param params HTTP parameters. * @param value SO_LINGER. */ public static void setLinger(final HttpParams params, int value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setIntParameter(CoreConnectionPNames.SO_LINGER, value); } /** * Obtains value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} * parameter. If not set, defaults to <code>0</code>. * * @param params HTTP parameters. * @return connect timeout. */ public static int getConnectionTimeout(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getIntParameter (CoreConnectionPNames.CONNECTION_TIMEOUT, 0); } /** * Sets value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT} * parameter. * * @param params HTTP parameters. * @param timeout connect timeout. */ public static void setConnectionTimeout(final HttpParams params, int timeout) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setIntParameter (CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); } /** * Obtains value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} * parameter. If not set, defaults to <code>true</code>. * * @param params HTTP parameters. * @return stale connection check flag. */ public static boolean isStaleCheckingEnabled(final HttpParams params) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } return params.getBooleanParameter (CoreConnectionPNames.STALE_CONNECTION_CHECK, true); } /** * Sets value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK} * parameter. * * @param params HTTP parameters. * @param value stale connection check flag. */ public static void setStaleCheckingEnabled(final HttpParams params, boolean value) { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } params.setBooleanParameter (CoreConnectionPNames.STALE_CONNECTION_CHECK, value); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.params; import org.apache.ogt.http.params.HttpParams; /** * Abstract base class for parameter collections. * Type specific setters and getters are mapped to the abstract, * generic getters and setters. * * @since 4.0 */ public abstract class AbstractHttpParams implements HttpParams { /** * Instantiates parameters. */ protected AbstractHttpParams() { super(); } public long getLongParameter(final String name, long defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Long)param).longValue(); } public HttpParams setLongParameter(final String name, long value) { setParameter(name, new Long(value)); return this; } public int getIntParameter(final String name, int defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Integer)param).intValue(); } public HttpParams setIntParameter(final String name, int value) { setParameter(name, new Integer(value)); return this; } public double getDoubleParameter(final String name, double defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Double)param).doubleValue(); } public HttpParams setDoubleParameter(final String name, double value) { setParameter(name, new Double(value)); return this; } public boolean getBooleanParameter(final String name, boolean defaultValue) { Object param = getParameter(name); if (param == null) { return defaultValue; } return ((Boolean)param).booleanValue(); } public HttpParams setBooleanParameter(final String name, boolean value) { setParameter(name, value ? Boolean.TRUE : Boolean.FALSE); return this; } public boolean isParameterTrue(final String name) { return getBooleanParameter(name, false); } public boolean isParameterFalse(final String name) { return !getBooleanParameter(name, false); } } // class AbstractHttpParams
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; import org.apache.ogt.http.ProtocolVersion; /** * Defines parameter names for protocol execution in HttpCore. * * @since 4.0 */ public interface CoreProtocolPNames { /** * Defines the {@link ProtocolVersion} used per default. * <p> * This parameter expects a value of type {@link ProtocolVersion}. * </p> */ public static final String PROTOCOL_VERSION = "http.protocol.version"; /** * Defines the charset to be used for encoding HTTP protocol elements. * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; /** * Defines the charset to be used per default for encoding content body. * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; /** * Defines the content of the <code>User-Agent</code> header. * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String USER_AGENT = "http.useragent"; /** * Defines the content of the <code>Server</code> header. * <p> * This parameter expects a value of type {@link String}. * </p> */ public static final String ORIGIN_SERVER = "http.origin-server"; /** * Defines whether responses with an invalid <code>Transfer-Encoding</code> * header should be rejected. * <p> * This parameter expects a value of type {@link Boolean}. * </p> */ public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; /** * <p> * Activates 'Expect: 100-Continue' handshake for the * entity enclosing methods. The purpose of the 'Expect: 100-Continue' * handshake is to allow a client that is sending a request message with * a request body to determine if the origin server is willing to * accept the request (based on the request headers) before the client * sends the request body. * </p> * * <p> * The use of the 'Expect: 100-continue' handshake can result in * a noticeable performance improvement for entity enclosing requests * (such as POST and PUT) that require the target server's * authentication. * </p> * * <p> * 'Expect: 100-continue' handshake should be used with * caution, as it may cause problems with HTTP servers and * proxies that do not support HTTP/1.1 protocol. * </p> * * This parameter expects a value of type {@link Boolean}. */ public static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; /** * <p> * Defines the maximum period of time in milliseconds the client should spend * waiting for a 100-continue response. * </p> * * This parameter expects a value of type {@link Integer}. */ public static final String WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.params; import java.io.Serializable; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import org.apache.ogt.http.params.HttpParams; /** * Default implementation of {@link HttpParams} interface. * <p> * Please note access to the internal structures of this class is not * synchronized and therefore this class may be thread-unsafe. * * @since 4.0 */ public class BasicHttpParams extends AbstractHttpParams implements Serializable, Cloneable { private static final long serialVersionUID = -7086398485908701455L; /** Map of HTTP parameters that this collection contains. */ private final HashMap parameters = new HashMap(); public BasicHttpParams() { super(); } public Object getParameter(final String name) { return this.parameters.get(name); } public HttpParams setParameter(final String name, final Object value) { this.parameters.put(name, value); return this; } public boolean removeParameter(String name) { //this is to avoid the case in which the key has a null value if (this.parameters.containsKey(name)) { this.parameters.remove(name); return true; } else { return false; } } /** * Assigns the value to all the parameter with the given names * * @param names array of parameter names * @param value parameter value */ public void setParameters(final String[] names, final Object value) { for (int i = 0; i < names.length; i++) { setParameter(names[i], value); } } /** * Is the parameter set? * <p> * Uses {@link #getParameter(String)} (which is overrideable) to * fetch the parameter value, if any. * <p> * Also @see {@link #isParameterSetLocally(String)} * * @param name parameter name * @return true if parameter is defined and non-null */ public boolean isParameterSet(final String name) { return getParameter(name) != null; } /** * Is the parameter set in this object? * <p> * The parameter value is fetched directly. * <p> * Also @see {@link #isParameterSet(String)} * * @param name parameter name * @return true if parameter is defined and non-null */ public boolean isParameterSetLocally(final String name) { return this.parameters.get(name) != null; } /** * Removes all parameters from this collection. */ public void clear() { this.parameters.clear(); } /** * Creates a copy of these parameters. * This implementation calls {@link #clone()}. * * @return a new set of params holding a copy of the * <i>local</i> parameters in this object. * * @deprecated * @throws UnsupportedOperationException if the clone() fails */ public HttpParams copy() { try { return (HttpParams) clone(); } catch (CloneNotSupportedException ex) { throw new UnsupportedOperationException("Cloning not supported"); } } /** * Clones the instance. * Uses {@link #copyParams(HttpParams)} to copy the parameters. */ public Object clone() throws CloneNotSupportedException { BasicHttpParams clone = (BasicHttpParams) super.clone(); copyParams(clone); return clone; } protected void copyParams(HttpParams target) { Iterator iter = parameters.entrySet().iterator(); while (iter.hasNext()) { Map.Entry me = (Map.Entry) iter.next(); if (me.getKey() instanceof String) target.setParameter((String)me.getKey(), me.getValue()); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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 name / value pair parameter used as an element of HTTP messages. * <pre> * parameter = attribute "=" value * attribute = token * value = token | quoted-string * </pre> * * * @since 4.0 */ public interface NameValuePair { String getName(); String getValue(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.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.HttpRequestFactory; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpServerConnection; 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.HttpRequestParser; import org.apache.ogt.http.impl.io.HttpResponseWriter; 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 server-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 AbstractHttpServerConnection implements HttpServerConnection { private final EntitySerializer entityserializer; private final EntityDeserializer entitydeserializer; private SessionInputBuffer inbuffer = null; private SessionOutputBuffer outbuffer = null; private EofSensor eofSensor = null; private HttpMessageParser requestParser = null; private HttpMessageWriter responseWriter = 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 AbstractHttpServerConnection() { 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 DefaultHttpRequestFactory} to be used * for creating {@link HttpRequest} 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 HttpRequestFactory} interface. * * @return HTTP request factory. */ protected HttpRequestFactory createHttpRequestFactory() { return new DefaultHttpRequestFactory(); } /** * Creates an instance of {@link HttpMessageParser} to be used for parsing * HTTP requests 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 HttpRequestParser}. * * @param buffer the session input buffer. * @param requestFactory the HTTP request factory. * @param params HTTP parameters. * @return HTTP message parser. */ protected HttpMessageParser createRequestParser( final SessionInputBuffer buffer, final HttpRequestFactory requestFactory, final HttpParams params) { return new HttpRequestParser(buffer, null, requestFactory, params); } /** * Creates an instance of {@link HttpMessageWriter} to be used for * writing out HTTP responses 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 HttpResponseWriter}. * * @param buffer the session output buffer * @param params HTTP parameters * @return HTTP message writer */ protected HttpMessageWriter createResponseWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new HttpResponseWriter(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 #createHttpRequestFactory}, * {@link #createRequestParser(SessionInputBuffer, HttpRequestFactory, HttpParams)} * and {@link #createResponseWriter(SessionOutputBuffer, HttpParams)} * methods to initialize HTTP request parser and response writer 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.requestParser = createRequestParser( inbuffer, createHttpRequestFactory(), params); this.responseWriter = createResponseWriter( outbuffer, params); this.metrics = createConnectionMetrics( inbuffer.getMetrics(), outbuffer.getMetrics()); } public HttpRequest receiveRequestHeader() throws HttpException, IOException { assertOpen(); HttpRequest request = (HttpRequest) this.requestParser.parse(); this.metrics.incrementRequestCount(); return request; } public void receiveRequestEntity(final HttpEntityEnclosingRequest request) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } assertOpen(); HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, request); request.setEntity(entity); } protected void doFlush() throws IOException { this.outbuffer.flush(); } public void flush() throws IOException { assertOpen(); doFlush(); } public void sendResponseHeader(final HttpResponse response) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } assertOpen(); this.responseWriter.write(response); if (response.getStatusLine().getStatusCode() >= 200) { this.metrics.incrementResponseCount(); } } public void sendResponseEntity(final HttpResponse response) throws HttpException, IOException { if (response.getEntity() == null) { return; } this.entityserializer.serialize( this.outbuffer, response, response.getEntity()); } 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 java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import org.apache.ogt.http.HttpInetConnection; import org.apache.ogt.http.impl.io.SocketInputBuffer; import org.apache.ogt.http.impl.io.SocketOutputBuffer; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * Implementation of a server-side HTTP connection that can be bound to a * network Socket in order to receive and transmit data. * <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.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * </ul> * * @since 4.0 */ public class SocketHttpServerConnection extends AbstractHttpServerConnection implements HttpInetConnection { private volatile boolean open; private volatile Socket socket = null; public SocketHttpServerConnection() { super(); } protected void assertNotOpen() { if (this.open) { throw new IllegalStateException("Connection is already open"); } } protected void assertOpen() { if (!this.open) { throw new IllegalStateException("Connection is not open"); } } /** * @deprecated Use {@link #createSessionInputBuffer(Socket, int, HttpParams)} */ protected SessionInputBuffer createHttpDataReceiver( final Socket socket, int buffersize, final HttpParams params) throws IOException { return createSessionInputBuffer(socket, buffersize, params); } /** * @deprecated Use {@link #createSessionOutputBuffer(Socket, int, HttpParams)} */ protected SessionOutputBuffer createHttpDataTransmitter( final Socket socket, int buffersize, final HttpParams params) throws IOException { return createSessionOutputBuffer(socket, buffersize, params); } /** * Creates an instance of {@link SocketInputBuffer} to be used for * receiving data from the given {@link Socket}. * <p> * This method can be overridden in a super class in order to provide * a custom implementation of {@link SessionInputBuffer} interface. * * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams) * * @param socket the socket. * @param buffersize the buffer size. * @param params HTTP parameters. * @return session input buffer. * @throws IOException in case of an I/O error. */ protected SessionInputBuffer createSessionInputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { return new SocketInputBuffer(socket, buffersize, params); } /** * Creates an instance of {@link SessionOutputBuffer} to be used for * sending data to the given {@link Socket}. * <p> * This method can be overridden in a super class in order to provide * a custom implementation of {@link SocketOutputBuffer} interface. * * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams) * * @param socket the socket. * @param buffersize the buffer size. * @param params HTTP parameters. * @return session output buffer. * @throws IOException in case of an I/O error. */ protected SessionOutputBuffer createSessionOutputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { return new SocketOutputBuffer(socket, buffersize, params); } /** * Binds this connection to the given {@link Socket}. This socket will be * used by the connection to send and receive data. * <p> * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)} * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods * to create session input / output buffers bound to this socket and then * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)} * method to pass references to those buffers to the underlying HTTP message * parser and formatter. * <p> * After this method's execution the connection status will be reported * as open and the {@link #isOpen()} will return <code>true</code>. * * @param socket the socket. * @param params HTTP parameters. * @throws IOException in case of an I/O error. */ protected void bind(final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.socket = socket; int buffersize = HttpConnectionParams.getSocketBufferSize(params); init( createHttpDataReceiver(socket, buffersize, params), createHttpDataTransmitter(socket, buffersize, params), params); this.open = true; } protected Socket getSocket() { return this.socket; } public boolean isOpen() { return this.open; } public InetAddress getLocalAddress() { if (this.socket != null) { return this.socket.getLocalAddress(); } else { return null; } } public int getLocalPort() { if (this.socket != null) { return this.socket.getLocalPort(); } else { return -1; } } public InetAddress getRemoteAddress() { if (this.socket != null) { return this.socket.getInetAddress(); } else { return null; } } public int getRemotePort() { if (this.socket != null) { return this.socket.getPort(); } else { return -1; } } public void setSocketTimeout(int timeout) { assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch (SocketException ignore) { // It is not quite clear from the Sun's documentation if there are any // other legitimate cases for a socket exception to be thrown when setting // SO_TIMEOUT besides the socket being already closed } } } public int getSocketTimeout() { if (this.socket != null) { try { return this.socket.getSoTimeout(); } catch (SocketException ignore) { return -1; } } else { return -1; } } public void shutdown() throws IOException { this.open = false; Socket tmpsocket = this.socket; if (tmpsocket != null) { tmpsocket.close(); } } public void close() throws IOException { if (!this.open) { return; } this.open = false; this.open = false; Socket sock = this.socket; try { doFlush(); try { try { sock.shutdownOutput(); } catch (IOException ignore) { } try { sock.shutdownInput(); } catch (IOException ignore) { } } catch (UnsupportedOperationException ignore) { // if one isn't supported, the other one isn't either } } finally { sock.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; import java.io.IOException; import java.net.Socket; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * Default implementation of a server-side HTTP connection. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class DefaultHttpServerConnection extends SocketHttpServerConnection { public DefaultHttpServerConnection() { super(); } public void bind(final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } assertNotOpen(); socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } super.bind(socket, params); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("["); if (isOpen()) { buffer.append(getRemotePort()); } else { 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.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.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.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 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; import java.util.Locale; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.ReasonPhraseCatalog; /** * English reason phrases for HTTP status codes. * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and * RFC2518 (WebDAV) are supported. * * @since 4.0 */ public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog { // static array with english reason phrases defined below /** * The default instance of this catalog. * This catalog is thread safe, so there typically * is no need to create other instances. */ public final static EnglishReasonPhraseCatalog INSTANCE = new EnglishReasonPhraseCatalog(); /** * Restricted default constructor, for derived classes. * If you need an instance of this class, use {@link #INSTANCE INSTANCE}. */ protected EnglishReasonPhraseCatalog() { // no body } /** * Obtains the reason phrase for a status code. * * @param status the status code, in the range 100-599 * @param loc ignored * * @return the reason phrase, or <code>null</code> */ public String getReason(int status, Locale loc) { if ((status < 100) || (status >= 600)) { throw new IllegalArgumentException ("Unknown category for status code " + status + "."); } final int category = status / 100; final int subcode = status - 100*category; String reason = null; if (REASON_PHRASES[category].length > subcode) reason = REASON_PHRASES[category][subcode]; return reason; } /** Reason phrases lookup table. */ private static final String[][] REASON_PHRASES = new String[][]{ null, new String[3], // 1xx new String[8], // 2xx new String[8], // 3xx new String[25], // 4xx new String[8] // 5xx }; /** * Stores the given reason phrase, by status code. * Helper method to initialize the static lookup table. * * @param status the status code for which to define the phrase * @param reason the reason phrase for this status code */ private static void setReason(int status, String reason) { final int category = status / 100; final int subcode = status - 100*category; REASON_PHRASES[category][subcode] = reason; } // ----------------------------------------------------- Static Initializer /** Set up status code to "reason phrase" map. */ static { // HTTP 1.0 Server status codes -- see RFC 1945 setReason(HttpStatus.SC_OK, "OK"); setReason(HttpStatus.SC_CREATED, "Created"); setReason(HttpStatus.SC_ACCEPTED, "Accepted"); setReason(HttpStatus.SC_NO_CONTENT, "No Content"); setReason(HttpStatus.SC_MOVED_PERMANENTLY, "Moved Permanently"); setReason(HttpStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily"); setReason(HttpStatus.SC_NOT_MODIFIED, "Not Modified"); setReason(HttpStatus.SC_BAD_REQUEST, "Bad Request"); setReason(HttpStatus.SC_UNAUTHORIZED, "Unauthorized"); setReason(HttpStatus.SC_FORBIDDEN, "Forbidden"); setReason(HttpStatus.SC_NOT_FOUND, "Not Found"); setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); setReason(HttpStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); setReason(HttpStatus.SC_BAD_GATEWAY, "Bad Gateway"); setReason(HttpStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); // HTTP 1.1 Server status codes -- see RFC 2048 setReason(HttpStatus.SC_CONTINUE, "Continue"); setReason(HttpStatus.SC_TEMPORARY_REDIRECT, "Temporary Redirect"); setReason(HttpStatus.SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); setReason(HttpStatus.SC_CONFLICT, "Conflict"); setReason(HttpStatus.SC_PRECONDITION_FAILED, "Precondition Failed"); setReason(HttpStatus.SC_REQUEST_TOO_LONG, "Request Too Long"); setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long"); setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); setReason(HttpStatus.SC_MULTIPLE_CHOICES, "Multiple Choices"); setReason(HttpStatus.SC_SEE_OTHER, "See Other"); setReason(HttpStatus.SC_USE_PROXY, "Use Proxy"); setReason(HttpStatus.SC_PAYMENT_REQUIRED, "Payment Required"); setReason(HttpStatus.SC_NOT_ACCEPTABLE, "Not Acceptable"); setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required"); setReason(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout"); setReason(HttpStatus.SC_SWITCHING_PROTOCOLS, "Switching Protocols"); setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION, "Non Authoritative Information"); setReason(HttpStatus.SC_RESET_CONTENT, "Reset Content"); setReason(HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); setReason(HttpStatus.SC_GATEWAY_TIMEOUT, "Gateway Timeout"); setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED, "Http Version Not Supported"); setReason(HttpStatus.SC_GONE, "Gone"); setReason(HttpStatus.SC_LENGTH_REQUIRED, "Length Required"); setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Requested Range Not Satisfiable"); setReason(HttpStatus.SC_EXPECTATION_FAILED, "Expectation Failed"); // WebDAV Server-specific status codes setReason(HttpStatus.SC_PROCESSING, "Processing"); setReason(HttpStatus.SC_MULTI_STATUS, "Multi-Status"); setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity"); setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE, "Insufficient Space On Resource"); setReason(HttpStatus.SC_METHOD_FAILURE, "Method Failure"); setReason(HttpStatus.SC_LOCKED, "Locked"); setReason(HttpStatus.SC_INSUFFICIENT_STORAGE, "Insufficient Storage"); setReason(HttpStatus.SC_FAILED_DEPENDENCY, "Failed Dependency"); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import org.apache.ogt.http.HttpInetConnection; import org.apache.ogt.http.impl.io.SocketInputBuffer; import org.apache.ogt.http.impl.io.SocketOutputBuffer; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * Implementation of a client-side HTTP connection that can be bound to an * arbitrary {@link Socket} for receiving data from and transmitting data to * a remote server. * <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.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * </ul> * * @since 4.0 */ public class SocketHttpClientConnection extends AbstractHttpClientConnection implements HttpInetConnection { private volatile boolean open; private volatile Socket socket = null; public SocketHttpClientConnection() { super(); } protected void assertNotOpen() { if (this.open) { throw new IllegalStateException("Connection is already open"); } } protected void assertOpen() { if (!this.open) { throw new IllegalStateException("Connection is not open"); } } /** * Creates an instance of {@link SocketInputBuffer} to be used for * receiving data from the given {@link Socket}. * <p> * This method can be overridden in a super class in order to provide * a custom implementation of {@link SessionInputBuffer} interface. * * @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams) * * @param socket the socket. * @param buffersize the buffer size. * @param params HTTP parameters. * @return session input buffer. * @throws IOException in case of an I/O error. */ protected SessionInputBuffer createSessionInputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { return new SocketInputBuffer(socket, buffersize, params); } /** * Creates an instance of {@link SessionOutputBuffer} to be used for * sending data to the given {@link Socket}. * <p> * This method can be overridden in a super class in order to provide * a custom implementation of {@link SocketOutputBuffer} interface. * * @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams) * * @param socket the socket. * @param buffersize the buffer size. * @param params HTTP parameters. * @return session output buffer. * @throws IOException in case of an I/O error. */ protected SessionOutputBuffer createSessionOutputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { return new SocketOutputBuffer(socket, buffersize, params); } /** * Binds this connection to the given {@link Socket}. This socket will be * used by the connection to send and receive data. * <p> * This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)} * and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods * to create session input / output buffers bound to this socket and then * will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)} * method to pass references to those buffers to the underlying HTTP message * parser and formatter. * <p> * After this method's execution the connection status will be reported * as open and the {@link #isOpen()} will return <code>true</code>. * * @param socket the socket. * @param params HTTP parameters. * @throws IOException in case of an I/O error. */ protected void bind( final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.socket = socket; int buffersize = HttpConnectionParams.getSocketBufferSize(params); init( createSessionInputBuffer(socket, buffersize, params), createSessionOutputBuffer(socket, buffersize, params), params); this.open = true; } public boolean isOpen() { return this.open; } protected Socket getSocket() { return this.socket; } public InetAddress getLocalAddress() { if (this.socket != null) { return this.socket.getLocalAddress(); } else { return null; } } public int getLocalPort() { if (this.socket != null) { return this.socket.getLocalPort(); } else { return -1; } } public InetAddress getRemoteAddress() { if (this.socket != null) { return this.socket.getInetAddress(); } else { return null; } } public int getRemotePort() { if (this.socket != null) { return this.socket.getPort(); } else { return -1; } } public void setSocketTimeout(int timeout) { assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch (SocketException ignore) { // It is not quite clear from the Sun's documentation if there are any // other legitimate cases for a socket exception to be thrown when setting // SO_TIMEOUT besides the socket being already closed } } } public int getSocketTimeout() { if (this.socket != null) { try { return this.socket.getSoTimeout(); } catch (SocketException ignore) { return -1; } } else { return -1; } } public void shutdown() throws IOException { this.open = false; Socket tmpsocket = this.socket; if (tmpsocket != null) { tmpsocket.close(); } } public void close() throws IOException { if (!this.open) { return; } this.open = false; Socket sock = this.socket; try { doFlush(); try { try { sock.shutdownOutput(); } catch (IOException ignore) { } try { sock.shutdownInput(); } catch (IOException ignore) { } } catch (UnsupportedOperationException ignore) { // if one isn't supported, the other one isn't either } } finally { sock.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; 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; 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 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.impl; import org.apache.ogt.http.ConnectionReuseStrategy; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.protocol.HttpContext; /** * A strategy that never re-uses a connection. * * @since 4.0 */ public class NoConnectionReuseStrategy implements ConnectionReuseStrategy { // default constructor // non-JavaDoc, 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"); } 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.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.io.SessionOutputBuffer; /** * Output stream 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> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, the stream will be marked as closed and no further * output will be permitted. * * @since 4.0 */ public class IdentityOutputStream extends OutputStream { /** * Wrapped session output buffer. */ private final SessionOutputBuffer out; /** True if the stream is closed. */ private boolean closed = false; public IdentityOutputStream(final SessionOutputBuffer out) { super(); if (out == null) { throw new IllegalArgumentException("Session output buffer may not be null"); } this.out = out; } /** * <p>Does not close the underlying socket output.</p> * * @throws IOException If an I/O problem occurs. */ public void close() throws IOException { if (!this.closed) { this.closed = true; this.out.flush(); } } public void flush() throws IOException { this.out.flush(); } public void write(byte[] b, int off, int len) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } this.out.write(b, off, len); } public void write(byte[] b) throws IOException { write(b, 0, b.length); } public void write(int b) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } this.out.write(b); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.io; import java.io.IOException; import java.io.InterruptedIOException; import java.net.Socket; import org.apache.ogt.http.io.EofSensor; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.params.HttpParams; /** * {@link SessionInputBuffer} implementation bound to a {@link Socket}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class SocketInputBuffer extends AbstractSessionInputBuffer implements EofSensor { static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass(); /** * Returns <code>SocketTimeoutExceptionClass<code> or <code>null</code> if the class * does not exist. * * @return <code>SocketTimeoutExceptionClass<code>, or <code>null</code> if unavailable. */ static private Class SocketTimeoutExceptionClass() { try { return Class.forName("java.net.SocketTimeoutException"); } catch (ClassNotFoundException e) { return null; } } private static boolean isSocketTimeoutException(final InterruptedIOException e) { if (SOCKET_TIMEOUT_CLASS != null) { return SOCKET_TIMEOUT_CLASS.isInstance(e); } else { return true; } } private final Socket socket; private boolean eof; /** * Creates an instance of this class. * * @param socket the socket to read data from. * @param buffersize the size of the internal buffer. If this number is less * than <code>0</code> it is set to the value of * {@link Socket#getReceiveBufferSize()}. If resultant number is less * than <code>1024</code> it is set to <code>1024</code>. * @param params HTTP parameters. */ public SocketInputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { super(); if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } this.socket = socket; this.eof = false; if (buffersize < 0) { buffersize = socket.getReceiveBufferSize(); } if (buffersize < 1024) { buffersize = 1024; } init(socket.getInputStream(), buffersize, params); } protected int fillBuffer() throws IOException { int i = super.fillBuffer(); this.eof = i == -1; return i; } public boolean isDataAvailable(int timeout) throws IOException { boolean result = hasBufferedData(); if (!result) { int oldtimeout = this.socket.getSoTimeout(); try { this.socket.setSoTimeout(timeout); fillBuffer(); result = hasBufferedData(); } catch (InterruptedIOException e) { if (!isSocketTimeoutException(e)) { throw e; } } finally { socket.setSoTimeout(oldtimeout); } } return result; } public boolean isEof() { return this.eof; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.io; import java.io.IOException; import java.util.Iterator; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.io.HttpMessageWriter; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.message.BasicLineFormatter; import org.apache.ogt.http.message.LineFormatter; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.CharArrayBuffer; /** * Abstract base class for HTTP message writers that serialize output to * an instance of {@link SessionOutputBuffer}. * * @since 4.0 */ public abstract class AbstractMessageWriter implements HttpMessageWriter { protected final SessionOutputBuffer sessionBuffer; protected final CharArrayBuffer lineBuf; protected final LineFormatter lineFormatter; /** * Creates an instance of AbstractMessageWriter. * * @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(128); this.lineFormatter = (formatter != null) ? formatter : BasicLineFormatter.DEFAULT; } /** * Subclasses must override this method to write out the first header line * based on the {@link HttpMessage} passed as a parameter. * * @param message the message whose first line is to be written out. * @throws IOException in case of an I/O error. */ protected abstract void writeHeadLine(HttpMessage message) throws IOException; public void write( final HttpMessage 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.ogt.http.impl.io; import java.io.IOException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.message.LineFormatter; import org.apache.ogt.http.params.HttpParams; /** * HTTP request writer that serializes its output to an instance * of {@link SessionOutputBuffer}. * * @since 4.0 */ public class HttpRequestWriter extends AbstractMessageWriter { public HttpRequestWriter(final SessionOutputBuffer buffer, final LineFormatter formatter, final HttpParams params) { super(buffer, formatter, params); } protected void writeHeadLine(final HttpMessage message) throws IOException { lineFormatter.formatRequestLine(this.lineBuf, ((HttpRequest) message).getRequestLine()); 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.ogt.http.impl.io; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.NoHttpResponseException; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.message.LineParser; import org.apache.ogt.http.message.ParserCursor; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.CharArrayBuffer; /** * HTTP response parser that obtain its input from an instance * of {@link SessionInputBuffer}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class HttpResponseParser extends AbstractMessageParser { private final HttpResponseFactory responseFactory; private final CharArrayBuffer lineBuf; /** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param responseFactory the factory to use to create * {@link HttpResponse}s. * @param params HTTP parameters. */ 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; this.lineBuf = new CharArrayBuffer(128); } protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new NoHttpResponseException("The target server failed to respond"); } //create the status line from the status string ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, 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.ogt.http.impl.io; import java.io.IOException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.message.LineFormatter; import org.apache.ogt.http.params.HttpParams; /** * HTTP response writer that serializes its output to an instance * of {@link SessionOutputBuffer}. * * @since 4.0 */ public class HttpResponseWriter extends AbstractMessageWriter { public HttpResponseWriter(final SessionOutputBuffer buffer, final LineFormatter formatter, final HttpParams params) { super(buffer, formatter, params); } protected void writeHeadLine(final HttpMessage message) throws IOException { lineFormatter.formatStatusLine(this.lineBuf, ((HttpResponse) message).getStatusLine()); 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.ogt.http.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.io.SessionOutputBuffer; /** * Output stream 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> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, the stream will be marked as closed and no further * output will be permitted. * * @since 4.0 */ public class ContentLengthOutputStream extends OutputStream { /** * Wrapped session output buffer. */ private final SessionOutputBuffer out; /** * The maximum number of bytes that can be written the stream. Subsequent * write operations will be ignored. */ private final long contentLength; /** Total bytes written */ private long total = 0; /** True if the stream is closed. */ private boolean closed = false; /** * Wraps a session output buffer and cuts off output after a defined number * of bytes. * * @param out The session output buffer * @param contentLength The maximum number of bytes that can be written to * the stream. Subsequent write operations will be ignored. * * @since 4.0 */ public ContentLengthOutputStream(final SessionOutputBuffer out, long contentLength) { super(); if (out == null) { throw new IllegalArgumentException("Session output buffer may not be null"); } if (contentLength < 0) { throw new IllegalArgumentException("Content length may not be negative"); } this.out = out; this.contentLength = contentLength; } /** * <p>Does not close the underlying socket output.</p> * * @throws IOException If an I/O problem occurs. */ public void close() throws IOException { if (!this.closed) { this.closed = true; this.out.flush(); } } public void flush() throws IOException { this.out.flush(); } public void write(byte[] b, int off, int len) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } if (this.total < this.contentLength) { long max = this.contentLength - this.total; if (len > max) { len = (int) max; } this.out.write(b, off, len); this.total += len; } } public void write(byte[] b) throws IOException { write(b, 0, b.length); } public void write(int b) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } if (this.total < this.contentLength) { this.out.write(b); this.total++; } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.io; import java.io.IOException; import java.net.Socket; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.params.HttpParams; /** * {@link SessionOutputBuffer} implementation bound to a {@link Socket}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * </ul> * * @since 4.0 */ public class SocketOutputBuffer extends AbstractSessionOutputBuffer { /** * Creates an instance of this class. * * @param socket the socket to write data to. * @param buffersize the size of the internal buffer. If this number is less * than <code>0</code> it is set to the value of * {@link Socket#getSendBufferSize()}. If resultant number is less * than <code>1024</code> it is set to <code>1024</code>. * @param params HTTP parameters. */ public SocketOutputBuffer( final Socket socket, int buffersize, final HttpParams params) throws IOException { super(); if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (buffersize < 0) { buffersize = socket.getSendBufferSize(); } if (buffersize < 1024) { buffersize = 1024; } init(socket.getOutputStream(), buffersize, 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.impl.io; import java.io.IOException; import java.io.InputStream; import org.apache.ogt.http.io.BufferInfo; import org.apache.ogt.http.io.SessionInputBuffer; /** * Input stream that reads data without any transformation. The end of the * content entity is demarcated by closing the underlying connection * (EOF condition). Entities transferred using this input stream can be of * unlimited length. * <p> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, it will read until the end of the stream (until * <code>-1</code> is returned). * * @since 4.0 */ public class IdentityInputStream extends InputStream { private final SessionInputBuffer in; private boolean closed = false; /** * Wraps session input stream and reads input until the the end of stream. * * @param in The session input buffer */ public IdentityInputStream(final SessionInputBuffer in) { super(); if (in == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } this.in = in; } public int available() throws IOException { if (this.in instanceof BufferInfo) { return ((BufferInfo) this.in).length(); } else { return 0; } } public void close() throws IOException { this.closed = true; } public int read() throws IOException { if (this.closed) { return -1; } else { return this.in.read(); } } public int read(final byte[] b, int off, int len) throws IOException { if (this.closed) { return -1; } else { return this.in.read(b, off, 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.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.io.BufferInfo; import org.apache.ogt.http.io.HttpTransportMetrics; import org.apache.ogt.http.io.SessionOutputBuffer; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.ByteArrayBuffer; import org.apache.ogt.http.util.CharArrayBuffer; /** * Abstract base class for session output buffers that stream data to * an arbitrary {@link OutputStream}. This class buffers small chunks of * output data in an internal byte array for optimal output performance. * <p> * {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods * of this class use CR-LF as a line delimiter. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li> * </ul> * <p> * * @since 4.0 */ public abstract class AbstractSessionOutputBuffer implements SessionOutputBuffer, BufferInfo { private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF}; private OutputStream outstream; private ByteArrayBuffer buffer; private String charset = HTTP.US_ASCII; private boolean ascii = true; private int minChunkLimit = 512; private HttpTransportMetricsImpl metrics; /** * Initializes this session output buffer. * * @param outstream the destination output stream. * @param buffersize the size of the internal buffer. * @param params HTTP parameters. */ protected void init(final OutputStream outstream, int buffersize, final HttpParams params) { if (outstream == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (buffersize <= 0) { throw new IllegalArgumentException("Buffer size may not be negative or zero"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.outstream = outstream; this.buffer = new ByteArrayBuffer(buffersize); this.charset = HttpProtocolParams.getHttpElementCharset(params); this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII) || this.charset.equalsIgnoreCase(HTTP.ASCII); this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); this.metrics = createTransportMetrics(); } /** * @since 4.1 */ protected HttpTransportMetricsImpl createTransportMetrics() { return new HttpTransportMetricsImpl(); } /** * @since 4.`1 */ public int capacity() { return this.buffer.capacity(); } /** * @since 4.1 */ public int length() { return this.buffer.length(); } /** * @since 4.1 */ public int available() { return capacity() - length(); } protected void flushBuffer() throws IOException { int len = this.buffer.length(); if (len > 0) { this.outstream.write(this.buffer.buffer(), 0, len); this.buffer.clear(); this.metrics.incrementBytesTransferred(len); } } public void flush() throws IOException { flushBuffer(); this.outstream.flush(); } public void write(final byte[] b, int off, int len) throws IOException { if (b == null) { return; } // Do not want to buffer large-ish chunks // if the byte array is larger then MIN_CHUNK_LIMIT // write it directly to the output stream if (len > this.minChunkLimit || len > this.buffer.capacity()) { // flush the buffer flushBuffer(); // write directly to the out stream this.outstream.write(b, off, len); this.metrics.incrementBytesTransferred(len); } else { // Do not let the buffer grow unnecessarily int freecapacity = this.buffer.capacity() - this.buffer.length(); if (len > freecapacity) { // flush the buffer flushBuffer(); } // buffer this.buffer.append(b, off, len); } } public void write(final byte[] b) throws IOException { if (b == null) { return; } write(b, 0, b.length); } public void write(int b) throws IOException { if (this.buffer.isFull()) { flushBuffer(); } this.buffer.append(b); } /** * Writes characters from the specified string followed by a line delimiter * to this session buffer. * <p> * This method uses CR-LF as a line delimiter. * * @param s the line. * @exception IOException if an I/O error occurs. */ public void writeLine(final String s) throws IOException { if (s == null) { return; } if (s.length() > 0) { write(s.getBytes(this.charset)); } write(CRLF); } /** * Writes characters from the specified char array followed by a line * delimiter to this session buffer. * <p> * This method uses CR-LF as a line delimiter. * * @param s the buffer containing chars of the line. * @exception IOException if an I/O error occurs. */ public void writeLine(final CharArrayBuffer s) throws IOException { if (s == null) { return; } if (this.ascii) { int off = 0; int remaining = s.length(); while (remaining > 0) { int chunk = this.buffer.capacity() - this.buffer.length(); chunk = Math.min(chunk, remaining); if (chunk > 0) { this.buffer.append(s, off, chunk); } if (this.buffer.isFull()) { flushBuffer(); } off += chunk; remaining -= chunk; } } else { // This is VERY memory inefficient, BUT since non-ASCII charsets are // NOT meant to be used anyway, there's no point optimizing it byte[] tmp = s.toString().getBytes(this.charset); write(tmp); } write(CRLF); } public HttpTransportMetrics 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.io; import java.io.IOException; import org.apache.ogt.http.ConnectionClosedException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestFactory; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.message.LineParser; import org.apache.ogt.http.message.ParserCursor; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.CharArrayBuffer; /** * HTTP request parser that obtain its input from an instance * of {@link SessionInputBuffer}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class HttpRequestParser extends AbstractMessageParser { private final HttpRequestFactory requestFactory; private final CharArrayBuffer lineBuf; /** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param requestFactory the factory to use to create * {@link HttpRequest}s. * @param params HTTP parameters. */ public HttpRequestParser( final SessionInputBuffer buffer, final LineParser parser, final HttpRequestFactory requestFactory, final HttpParams params) { super(buffer, parser, params); if (requestFactory == null) { throw new IllegalArgumentException("Request factory may not be null"); } this.requestFactory = requestFactory; this.lineBuf = new CharArrayBuffer(128); } protected HttpMessage parseHead( final SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException { this.lineBuf.clear(); int i = sessionBuffer.readLine(this.lineBuf); if (i == -1) { throw new ConnectionClosedException("Client closed connection"); } ParserCursor cursor = new ParserCursor(0, this.lineBuf.length()); RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, 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.ogt.http.impl.io; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.io.SessionOutputBuffer; /** * Implements chunked transfer coding. The content is sent in small chunks. * Entities transferred using this output stream can be of unlimited length. * Writes are buffered to an internal buffer (2048 default size). * <p> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, the stream will be marked as closed and no further * output will be permitted. * * * @since 4.0 */ public class ChunkedOutputStream extends OutputStream { // ----------------------------------------------------- Instance Variables private final SessionOutputBuffer out; private byte[] cache; private int cachePosition = 0; private boolean wroteLastChunk = false; /** True if the stream is closed. */ private boolean closed = false; // ----------------------------------------------------------- Constructors /** * Wraps a session output buffer and chunk-encodes the output. * * @param out The session output buffer * @param bufferSize The minimum chunk size (excluding last chunk) * @throws IOException in case of an I/O error */ public ChunkedOutputStream(final SessionOutputBuffer out, int bufferSize) throws IOException { super(); this.cache = new byte[bufferSize]; this.out = out; } /** * Wraps a session output buffer and chunks the output. The default buffer * size of 2048 was chosen because the chunk overhead is less than 0.5% * * @param out the output buffer to wrap * @throws IOException in case of an I/O error */ public ChunkedOutputStream(final SessionOutputBuffer out) throws IOException { this(out, 2048); } // ----------------------------------------------------------- Internal methods /** * Writes the cache out onto the underlying stream */ protected void flushCache() throws IOException { if (this.cachePosition > 0) { this.out.writeLine(Integer.toHexString(this.cachePosition)); this.out.write(this.cache, 0, this.cachePosition); this.out.writeLine(""); this.cachePosition = 0; } } /** * Writes the cache and bufferToAppend to the underlying stream * as one large chunk */ protected void flushCacheWithAppend(byte bufferToAppend[], int off, int len) throws IOException { this.out.writeLine(Integer.toHexString(this.cachePosition + len)); this.out.write(this.cache, 0, this.cachePosition); this.out.write(bufferToAppend, off, len); this.out.writeLine(""); this.cachePosition = 0; } protected void writeClosingChunk() throws IOException { // Write the final chunk. this.out.writeLine("0"); this.out.writeLine(""); } // ----------------------------------------------------------- Public Methods /** * Must be called to ensure the internal cache is flushed and the closing * chunk is written. * @throws IOException in case of an I/O error */ public void finish() throws IOException { if (!this.wroteLastChunk) { flushCache(); writeClosingChunk(); this.wroteLastChunk = true; } } // -------------------------------------------- OutputStream Methods public void write(int b) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } this.cache[this.cachePosition] = (byte) b; this.cachePosition++; if (this.cachePosition == this.cache.length) flushCache(); } /** * Writes the array. If the array does not fit within the buffer, it is * not split, but rather written out as one large chunk. */ public void write(byte b[]) throws IOException { write(b, 0, b.length); } /** * Writes the array. If the array does not fit within the buffer, it is * not split, but rather written out as one large chunk. */ public void write(byte src[], int off, int len) throws IOException { if (this.closed) { throw new IOException("Attempted write to closed stream."); } if (len >= this.cache.length - this.cachePosition) { flushCacheWithAppend(src, off, len); } else { System.arraycopy(src, off, cache, this.cachePosition, len); this.cachePosition += len; } } /** * Flushes the content buffer and the underlying stream. */ public void flush() throws IOException { flushCache(); this.out.flush(); } /** * Finishes writing to the underlying stream, but does NOT close the underlying stream. */ public void close() throws IOException { if (!this.closed) { this.closed = true; finish(); this.out.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.impl.io; import org.apache.ogt.http.io.HttpTransportMetrics; /** * Default implementation of {@link HttpTransportMetrics}. * * @since 4.0 */ public class HttpTransportMetricsImpl implements HttpTransportMetrics { private long bytesTransferred = 0; public HttpTransportMetricsImpl() { super(); } public long getBytesTransferred() { return this.bytesTransferred; } public void setBytesTransferred(long count) { this.bytesTransferred = count; } public void incrementBytesTransferred(long count) { this.bytesTransferred += count; } public void reset() { this.bytesTransferred = 0; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals 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.io; import java.io.IOException; import java.io.InputStream; import org.apache.ogt.http.io.BufferInfo; import org.apache.ogt.http.io.HttpTransportMetrics; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.ByteArrayBuffer; import org.apache.ogt.http.util.CharArrayBuffer; /** * Abstract base class for session input buffers that stream data from * an arbitrary {@link InputStream}. This class buffers input data in * an internal byte array for optimal input performance. * <p> * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this * class treat a lone LF as valid line delimiters in addition to CR-LF required * by the HTTP specification. * * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li> * </ul> * @since 4.0 */ public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo { private InputStream instream; private byte[] buffer; private int bufferpos; private int bufferlen; private ByteArrayBuffer linebuffer = null; private String charset = HTTP.US_ASCII; private boolean ascii = true; private int maxLineLen = -1; private int minChunkLimit = 512; private HttpTransportMetricsImpl metrics; /** * Initializes this session input buffer. * * @param instream the source input stream. * @param buffersize the size of the internal buffer. * @param params HTTP parameters. */ protected void init(final InputStream instream, int buffersize, final HttpParams params) { if (instream == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (buffersize <= 0) { throw new IllegalArgumentException("Buffer size may not be negative or zero"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.instream = instream; this.buffer = new byte[buffersize]; this.bufferpos = 0; this.bufferlen = 0; this.linebuffer = new ByteArrayBuffer(buffersize); this.charset = HttpProtocolParams.getHttpElementCharset(params); this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII) || this.charset.equalsIgnoreCase(HTTP.ASCII); this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); this.metrics = createTransportMetrics(); } /** * @since 4.1 */ protected HttpTransportMetricsImpl createTransportMetrics() { return new HttpTransportMetricsImpl(); } /** * @since 4.1 */ public int capacity() { return this.buffer.length; } /** * @since 4.1 */ public int length() { return this.bufferlen - this.bufferpos; } /** * @since 4.1 */ public int available() { return capacity() - length(); } protected int fillBuffer() throws IOException { // compact the buffer if necessary if (this.bufferpos > 0) { int len = this.bufferlen - this.bufferpos; if (len > 0) { System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); } this.bufferpos = 0; this.bufferlen = len; } int l; int off = this.bufferlen; int len = this.buffer.length - off; l = this.instream.read(this.buffer, off, len); if (l == -1) { return -1; } else { this.bufferlen = off + l; this.metrics.incrementBytesTransferred(l); return l; } } protected boolean hasBufferedData() { return this.bufferpos < this.bufferlen; } public int read() throws IOException { int noRead = 0; while (!hasBufferedData()) { noRead = fillBuffer(); if (noRead == -1) { return -1; } } return this.buffer[this.bufferpos++] & 0xff; } public int read(final byte[] b, int off, int len) throws IOException { if (b == null) { return 0; } if (hasBufferedData()) { int chunk = Math.min(len, this.bufferlen - this.bufferpos); System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); this.bufferpos += chunk; return chunk; } // If the remaining capacity is big enough, read directly from the // underlying input stream bypassing the buffer. if (len > this.minChunkLimit) { int read = this.instream.read(b, off, len); if (read > 0) { this.metrics.incrementBytesTransferred(read); } return read; } else { // otherwise read to the buffer first while (!hasBufferedData()) { int noRead = fillBuffer(); if (noRead == -1) { return -1; } } int chunk = Math.min(len, this.bufferlen - this.bufferpos); System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); this.bufferpos += chunk; return chunk; } } public int read(final byte[] b) throws IOException { if (b == null) { return 0; } return read(b, 0, b.length); } private int locateLF() { for (int i = this.bufferpos; i < this.bufferlen; i++) { if (this.buffer[i] == HTTP.LF) { return i; } } return -1; } /** * Reads a complete line of characters up to a line delimiter from this * session buffer into the given line buffer. The number of chars actually * read is returned as an integer. The line delimiter itself is discarded. * If no char is available because the end of the stream has been reached, * the value <code>-1</code> is returned. This method blocks until input * data is available, end of file is detected, or an exception is thrown. * <p> * This method treats a lone LF as a valid line delimiters in addition * to CR-LF required by the HTTP specification. * * @param charbuffer the line buffer. * @return one line of characters * @exception IOException if an I/O error occurs. */ public int readLine(final CharArrayBuffer charbuffer) throws IOException { if (charbuffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } int noRead = 0; boolean retry = true; while (retry) { // attempt to find end of line (LF) int i = locateLF(); if (i != -1) { // end of line found. if (this.linebuffer.isEmpty()) { // the entire line is preset in the read buffer return lineFromReadBuffer(charbuffer, i); } retry = false; int len = i + 1 - this.bufferpos; this.linebuffer.append(this.buffer, this.bufferpos, len); this.bufferpos = i + 1; } else { // end of line not found if (hasBufferedData()) { int len = this.bufferlen - this.bufferpos; this.linebuffer.append(this.buffer, this.bufferpos, len); this.bufferpos = this.bufferlen; } noRead = fillBuffer(); if (noRead == -1) { retry = false; } } if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) { throw new IOException("Maximum line length limit exceeded"); } } if (noRead == -1 && this.linebuffer.isEmpty()) { // indicate the end of stream return -1; } return lineFromLineBuffer(charbuffer); } /** * Reads a complete line of characters up to a line delimiter from this * session buffer. The line delimiter itself is discarded. If no char is * available because the end of the stream has been reached, * <code>null</code> is returned. This method blocks until input data is * available, end of file is detected, or an exception is thrown. * <p> * This method treats a lone LF as a valid line delimiters in addition * to CR-LF required by the HTTP specification. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ private int lineFromLineBuffer(final CharArrayBuffer charbuffer) throws IOException { // discard LF if found int l = this.linebuffer.length(); if (l > 0) { if (this.linebuffer.byteAt(l - 1) == HTTP.LF) { l--; this.linebuffer.setLength(l); } // discard CR if found if (l > 0) { if (this.linebuffer.byteAt(l - 1) == HTTP.CR) { l--; this.linebuffer.setLength(l); } } } l = this.linebuffer.length(); if (this.ascii) { charbuffer.append(this.linebuffer, 0, l); } else { // This is VERY memory inefficient, BUT since non-ASCII charsets are // NOT meant to be used anyway, there's no point optimizing it String s = new String(this.linebuffer.buffer(), 0, l, this.charset); l = s.length(); charbuffer.append(s); } this.linebuffer.clear(); return l; } private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) throws IOException { int off = this.bufferpos; int len; this.bufferpos = pos + 1; if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) { // skip CR if found pos--; } len = pos - off; if (this.ascii) { charbuffer.append(this.buffer, off, len); } else { // This is VERY memory inefficient, BUT since non-ASCII charsets are // NOT meant to be used anyway, there's no point optimizing it String s = new String(this.buffer, off, len, this.charset); charbuffer.append(s); len = s.length(); } return len; } public String readLine() throws IOException { CharArrayBuffer charbuffer = new CharArrayBuffer(64); int l = readLine(charbuffer); if (l != -1) { return charbuffer.toString(); } else { return null; } } public HttpTransportMetrics 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.io; import java.io.IOException; import java.io.InputStream; import org.apache.ogt.http.ConnectionClosedException; import org.apache.ogt.http.io.BufferInfo; import org.apache.ogt.http.io.SessionInputBuffer; /** * Input stream 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> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, it will read until the "end" of its limit on * close, which allows for the seamless execution of subsequent HTTP 1.1 * requests, while not requiring the client to remember to read the entire * contents of the response. * * * @since 4.0 */ public class ContentLengthInputStream extends InputStream { private static final int BUFFER_SIZE = 2048; /** * The maximum number of bytes that can be read from the stream. Subsequent * read operations will return -1. */ private long contentLength; /** The current position */ private long pos = 0; /** True if the stream is closed. */ private boolean closed = false; /** * Wrapped input stream that all calls are delegated to. */ private SessionInputBuffer in = null; /** * Wraps a session input buffer and cuts off output after a defined number * of bytes. * * @param in The session input buffer * @param contentLength The maximum number of bytes that can be read from * the stream. Subsequent read operations will return -1. */ public ContentLengthInputStream(final SessionInputBuffer in, long contentLength) { super(); if (in == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (contentLength < 0) { throw new IllegalArgumentException("Content length may not be negative"); } this.in = in; this.contentLength = contentLength; } /** * <p>Reads until the end of the known length of content.</p> * * <p>Does not close the underlying socket input, but instead leaves it * primed to parse the next response.</p> * @throws IOException If an IO problem occurs. */ public void close() throws IOException { if (!closed) { try { if (pos < contentLength) { byte buffer[] = new byte[BUFFER_SIZE]; while (read(buffer) >= 0) { } } } finally { // close after above so that we don't throw an exception trying // to read after closed! closed = true; } } } public int available() throws IOException { if (this.in instanceof BufferInfo) { int len = ((BufferInfo) this.in).length(); return Math.min(len, (int) (this.contentLength - this.pos)); } else { return 0; } } /** * Read the next byte from the stream * @return The next byte or -1 if the end of stream has been reached. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read() */ public int read() throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } int b = this.in.read(); if (b == -1) { if (pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } } else { pos++; } return b; } /** * Does standard {@link InputStream#read(byte[], int, int)} behavior, but * also notifies the watcher when the contents have been consumed. * * @param b The byte array to fill. * @param off Start filling at this position. * @param len The number of bytes to attempt to read. * @return The number of bytes read, or -1 if the end of content has been * reached. * * @throws java.io.IOException Should an error occur on the wrapped stream. */ public int read (byte[] b, int off, int len) throws java.io.IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (pos >= contentLength) { return -1; } if (pos + len > contentLength) { len = (int) (contentLength - pos); } int count = this.in.read(b, off, len); if (count == -1 && pos < contentLength) { throw new ConnectionClosedException( "Premature end of Content-Length delimited message body (expected: " + contentLength + "; received: " + pos); } if (count > 0) { pos += count; } return count; } /** * Read more bytes from the stream. * @param b The byte array to put the new data in. * @return The number of bytes read into the buffer. * @throws IOException If an IO problem occurs * @see java.io.InputStream#read(byte[]) */ public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Skips and discards a number of bytes from the input stream. * @param n The number of bytes to skip. * @return The actual number of bytes skipped. <= 0 if no bytes * are skipped. * @throws IOException If an error occurs while skipping bytes. * @see InputStream#skip(long) */ public long skip(long n) throws IOException { if (n <= 0) { return 0; } byte[] buffer = new byte[BUFFER_SIZE]; // make sure we don't skip more bytes than are // still available long remaining = Math.min(n, this.contentLength - this.pos); // skip and keep track of the bytes actually skipped long count = 0; while (remaining > 0) { int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); if (l == -1) { break; } count += l; remaining -= l; } return count; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.io; import java.io.IOException; import java.io.InputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.MalformedChunkCodingException; import org.apache.ogt.http.TruncatedChunkException; import org.apache.ogt.http.io.BufferInfo; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.util.CharArrayBuffer; import org.apache.ogt.http.util.ExceptionUtils; /** * Implements chunked transfer coding. The content is received in small chunks. * Entities transferred using this input stream can be of unlimited length. * After the stream is read to the end, it provides access to the trailers, * if any. * <p> * Note that this class NEVER closes the underlying stream, even when close * gets called. Instead, it will read until the "end" of its chunking on * close, which allows for the seamless execution of subsequent HTTP 1.1 * requests, while not requiring the client to remember to read the entire * contents of the response. * * * @since 4.0 * */ public class ChunkedInputStream extends InputStream { private static final int CHUNK_LEN = 1; private static final int CHUNK_DATA = 2; private static final int CHUNK_CRLF = 3; private static final int BUFFER_SIZE = 2048; /** The session input buffer */ private final SessionInputBuffer in; private final CharArrayBuffer buffer; private int state; /** The chunk size */ private int chunkSize; /** The current position within the current chunk */ private int pos; /** True if we've reached the end of stream */ private boolean eof = false; /** True if this stream is closed */ private boolean closed = false; private Header[] footers = new Header[] {}; /** * Wraps session input stream and reads chunk coded input. * * @param in The session input buffer */ public ChunkedInputStream(final SessionInputBuffer in) { super(); if (in == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } this.in = in; this.pos = 0; this.buffer = new CharArrayBuffer(16); this.state = CHUNK_LEN; } public int available() throws IOException { if (this.in instanceof BufferInfo) { int len = ((BufferInfo) this.in).length(); return Math.min(len, this.chunkSize - this.pos); } else { return 0; } } /** * <p> Returns all the data in a chunked stream in coalesced form. A chunk * is followed by a CRLF. The method returns -1 as soon as a chunksize of 0 * is detected.</p> * * <p> Trailer headers are read automatically at the end of the stream and * can be obtained with the getResponseFooters() method.</p> * * @return -1 of the end of the stream has been reached or the next data * byte * @throws IOException in case of an I/O error */ public int read() throws IOException { if (this.closed) { throw new IOException("Attempted read from closed stream."); } if (this.eof) { return -1; } if (state != CHUNK_DATA) { nextChunk(); if (this.eof) { return -1; } } int b = in.read(); if (b != -1) { pos++; if (pos >= chunkSize) { state = CHUNK_CRLF; } } return b; } /** * Read some bytes from the stream. * @param b The byte array that will hold the contents from the stream. * @param off The offset into the byte array at which bytes will start to be * placed. * @param len the maximum number of bytes that can be returned. * @return The number of bytes returned or -1 if the end of stream has been * reached. * @throws IOException in case of an I/O error */ public int read (byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException("Attempted read from closed stream."); } if (eof) { return -1; } if (state != CHUNK_DATA) { nextChunk(); if (eof) { return -1; } } len = Math.min(len, chunkSize - pos); int bytesRead = in.read(b, off, len); if (bytesRead != -1) { pos += bytesRead; if (pos >= chunkSize) { state = CHUNK_CRLF; } return bytesRead; } else { eof = true; throw new TruncatedChunkException("Truncated chunk " + "( expected size: " + chunkSize + "; actual size: " + pos + ")"); } } /** * Read some bytes from the stream. * @param b The byte array that will hold the contents from the stream. * @return The number of bytes returned or -1 if the end of stream has been * reached. * @throws IOException in case of an I/O error */ public int read (byte[] b) throws IOException { return read(b, 0, b.length); } /** * Read the next chunk. * @throws IOException in case of an I/O error */ private void nextChunk() throws IOException { chunkSize = getChunkSize(); if (chunkSize < 0) { throw new MalformedChunkCodingException("Negative chunk size"); } state = CHUNK_DATA; pos = 0; if (chunkSize == 0) { eof = true; parseTrailerHeaders(); } } /** * Expects the stream to start with a chunksize in hex with optional * comments after a semicolon. The line must end with a CRLF: "a3; some * comment\r\n" Positions the stream at the start of the next line. * * @param in The new input stream. * @param required <tt>true<tt/> if a valid chunk must be present, * <tt>false<tt/> otherwise. * * @return the chunk size as integer * * @throws IOException when the chunk size could not be parsed */ private int getChunkSize() throws IOException { int st = this.state; switch (st) { case CHUNK_CRLF: this.buffer.clear(); int i = this.in.readLine(this.buffer); if (i == -1) { return 0; } if (!this.buffer.isEmpty()) { throw new MalformedChunkCodingException( "Unexpected content at the end of chunk"); } state = CHUNK_LEN; //$FALL-THROUGH$ case CHUNK_LEN: this.buffer.clear(); i = this.in.readLine(this.buffer); if (i == -1) { return 0; } int separator = this.buffer.indexOf(';'); if (separator < 0) { separator = this.buffer.length(); } try { return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16); } catch (NumberFormatException e) { throw new MalformedChunkCodingException("Bad chunk header"); } default: throw new IllegalStateException("Inconsistent codec state"); } } /** * Reads and stores the Trailer headers. * @throws IOException in case of an I/O error */ private void parseTrailerHeaders() throws IOException { try { this.footers = AbstractMessageParser.parseHeaders (in, -1, -1, null); } catch (HttpException e) { IOException ioe = new MalformedChunkCodingException("Invalid footer: " + e.getMessage()); ExceptionUtils.initCause(ioe, e); throw ioe; } } /** * Upon close, this reads the remainder of the chunked message, * leaving the underlying socket at a position to start reading the * next response without scanning. * @throws IOException in case of an I/O error */ public void close() throws IOException { if (!closed) { try { if (!eof) { // read and discard the remainder of the message byte buffer[] = new byte[BUFFER_SIZE]; while (read(buffer) >= 0) { } } } finally { eof = true; closed = true; } } } public Header[] getFooters() { return (Header[])this.footers.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.impl.io; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.ogt.http.Header; 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.io.HttpMessageParser; import org.apache.ogt.http.io.SessionInputBuffer; import org.apache.ogt.http.message.BasicLineParser; import org.apache.ogt.http.message.LineParser; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.CharArrayBuffer; /** * Abstract base class for HTTP message parsers that obtain input from * an instance of {@link SessionInputBuffer}. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public abstract class AbstractMessageParser implements HttpMessageParser { private static final int HEAD_LINE = 0; private static final int HEADERS = 1; private final SessionInputBuffer sessionBuffer; private final int maxHeaderCount; private final int maxLineLen; private final List headerLines; protected final LineParser lineParser; private int state; private HttpMessage message; /** * 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.maxHeaderCount = params.getIntParameter( CoreConnectionPNames.MAX_HEADER_COUNT, -1); this.maxLineLen = params.getIntParameter( CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT; this.headerLines = new ArrayList(); this.state = HEAD_LINE; } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @return array of HTTP headers * @param parser line parser to use. Can be <code>null</code>, in which case * the default implementation of this interface will be used. * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, LineParser parser) throws HttpException, IOException { if (parser == null) { parser = BasicLineParser.DEFAULT; } List headerLines = new ArrayList(); return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser, headerLines); } /** * Parses HTTP headers from the data receiver stream according to the generic * format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3. * * @param inbuffer Session input buffer * @param maxHeaderCount maximum number of headers allowed. If the number * of headers received from the data stream exceeds maxCount value, an * IOException will be thrown. Setting this parameter to a negative value * or zero will disable the check. * @param maxLineLen maximum number of characters for a header line, * including the continuation lines. Setting this parameter to a negative * value or zero will disable the check. * @param parser line parser to use. * @param headerLines List of header lines. This list will be used to store * intermediate results. This makes it possible to resume parsing of * headers in case of a {@link java.io.InterruptedIOException}. * * @return array of HTTP headers * * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation * * @since 4.1 */ public static Header[] parseHeaders( final SessionInputBuffer inbuffer, int maxHeaderCount, int maxLineLen, final LineParser parser, final List headerLines) throws HttpException, IOException { if (inbuffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } if (parser == null) { throw new IllegalArgumentException("Line parser may not be null"); } if (headerLines == null) { throw new IllegalArgumentException("Header line list may not be null"); } CharArrayBuffer current = null; CharArrayBuffer previous = null; for (;;) { if (current == null) { current = new CharArrayBuffer(64); } else { current.clear(); } int l = inbuffer.readLine(current); if (l == -1 || current.length() < 1) { break; } // Parse the header name and value // Check for folded headers first // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2 // discussion on folded headers if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) { // we have continuation folded header // so append value int i = 0; while (i < current.length()) { char ch = current.charAt(i); if (ch != ' ' && ch != '\t') { break; } i++; } if (maxLineLen > 0 && previous.length() + 1 + current.length() - i > maxLineLen) { throw new IOException("Maximum line length limit exceeded"); } previous.append(' '); previous.append(current, i, current.length() - i); } else { headerLines.add(current); previous = current; current = null; } if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) { throw new IOException("Maximum header count exceeded"); } } Header[] headers = new Header[headerLines.size()]; for (int i = 0; i < headerLines.size(); i++) { CharArrayBuffer buffer = (CharArrayBuffer) headerLines.get(i); try { headers[i] = parser.parseHeader(buffer); } catch (ParseException ex) { throw new ProtocolException(ex.getMessage()); } } return headers; } /** * Subclasses must override this method to generate an instance of * {@link HttpMessage} based on the initial input from the session buffer. * <p> * Usually this method is expected to read just the very first line or * the very first valid from the data stream and based on the input generate * an appropriate instance of {@link HttpMessage}. * * @param sessionBuffer the session input buffer. * @return HTTP message based on the input from the session buffer. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation. * @throws ParseException in case of a parse error. */ protected abstract HttpMessage parseHead(SessionInputBuffer sessionBuffer) throws IOException, HttpException, ParseException; public HttpMessage parse() throws IOException, HttpException { int st = this.state; switch (st) { case HEAD_LINE: try { this.message = parseHead(this.sessionBuffer); } catch (ParseException px) { throw new ProtocolException(px.getMessage(), px); } this.state = HEADERS; //$FALL-THROUGH$ case HEADERS: Header[] headers = AbstractMessageParser.parseHeaders( this.sessionBuffer, this.maxHeaderCount, this.maxLineLen, this.lineParser, this.headerLines); this.message.setHeaders(headers); HttpMessage result = this.message; this.message = null; this.headerLines.clear(); this.state = HEAD_LINE; return result; default: throw new IllegalStateException("Inconsistent parser state"); } } }
Java