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.protocol;
import java.io.IOException;
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.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* RequestContent is the most important interceptor for outgoing requests.
* It is responsible for delimiting content length by adding
* <code>Content-Length</code> or <code>Transfer-Content</code> headers based
* on the properties of the enclosed entity and the protocol version.
* This interceptor is required for correct functioning of client side protocol
* processors.
*
* @since 4.0
*/
public class RequestContent implements HttpRequestInterceptor {
public RequestContent() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (request instanceof HttpEntityEnclosingRequest) {
if (request.containsHeader(HTTP.TRANSFER_ENCODING)) {
throw new ProtocolException("Transfer-encoding header already present");
}
if (request.containsHeader(HTTP.CONTENT_LEN)) {
throw new ProtocolException("Content-Length header already present");
}
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
if (entity == null) {
request.addHeader(HTTP.CONTENT_LEN, "0");
return;
}
// Must specify a transfer encoding or a content length
if (entity.isChunked() || entity.getContentLength() < 0) {
if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(
"Chunked transfer encoding not allowed for " + ver);
}
request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
} else {
request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
}
// Specify a content type if known
if (entity.getContentType() != null && !request.containsHeader(
HTTP.CONTENT_TYPE )) {
request.addHeader(entity.getContentType());
}
// Specify a content encoding if known
if (entity.getContentEncoding() != null && !request.containsHeader(
HTTP.CONTENT_ENCODING)) {
request.addHeader(entity.getContentEncoding());
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.net.InetAddress;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* RequestTargetHost is responsible for adding <code>Host</code> header. This
* interceptor is required for client side protocol processors.
*
* @since 4.0
*/
public class RequestTargetHost implements HttpRequestInterceptor {
public RequestTargetHost() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) {
return;
}
if (!request.containsHeader(HTTP.TARGET_HOST)) {
HttpHost targethost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (targethost == null) {
HttpConnection conn = (HttpConnection) context
.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn instanceof HttpInetConnection) {
// Populate the context with a default HTTP host based on the
// inet address of the target host
InetAddress address = ((HttpInetConnection) conn).getRemoteAddress();
int port = ((HttpInetConnection) conn).getRemotePort();
if (address != null) {
targethost = new HttpHost(address.getHostName(), port);
}
}
if (targethost == null) {
if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
return;
} else {
throw new ProtocolException("Target host missing");
}
}
}
request.addHeader(HTTP.TARGET_HOST, targethost.toHostString());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.net.ProtocolException;
import org.apache.ogt.http.HttpClientConnection;
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.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.params.CoreProtocolPNames;
/**
* HttpRequestExecutor is a client side HTTP protocol handler based on the
* blocking I/O model that implements the essential requirements of the HTTP
* protocol for the client side message processing, as described by RFC 2616.
* <br>
* HttpRequestExecutor relies on {@link HttpProcessor} to generate mandatory
* protocol headers for all outgoing messages and apply common, cross-cutting
* message transformations to all incoming and outgoing messages. Application
* specific processing can be implemented outside HttpRequestExecutor once the
* request has been executed and a response has been received.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* </ul>
*
* @since 4.0
*/
public class HttpRequestExecutor {
/**
* Create a new request executor.
*/
public HttpRequestExecutor() {
super();
}
/**
* Decide whether a response comes with an entity.
* The implementation in this class is based on RFC 2616.
* <br/>
* Derived executors can override this method to handle
* methods and response codes not specified in RFC 2616.
*
* @param request the request, to obtain the executed method
* @param response the response, to obtain the status code
*/
protected boolean canResponseHaveBody(final HttpRequest request,
final HttpResponse response) {
if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
/**
* Sends the request and obtain a response.
*
* @param request the request to execute.
* @param conn the connection over which to execute the request.
*
* @return the response to the request.
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public HttpResponse execute(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("Client connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
try {
HttpResponse response = doSendRequest(request, conn, context);
if (response == null) {
response = doReceiveResponse(request, conn, context);
}
return response;
} catch (IOException ex) {
closeConnection(conn);
throw ex;
} catch (HttpException ex) {
closeConnection(conn);
throw ex;
} catch (RuntimeException ex) {
closeConnection(conn);
throw ex;
}
}
private final static void closeConnection(final HttpClientConnection conn) {
try {
conn.close();
} catch (IOException ignore) {
}
}
/**
* Pre-process the given request using the given protocol processor and
* initiates the process of request execution.
*
* @param request the request to prepare
* @param processor the processor to use
* @param context the context for sending the request
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void preProcess(
final HttpRequest request,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
processor.process(request, context);
}
/**
* Send the given request over the given connection.
* <p>
* This method also handles the expect-continue handshake if necessary.
* If it does not have to handle an expect-continue handshake, it will
* not use the connection for reading or anything else that depends on
* data coming in over the connection.
*
* @param request the request to send, already
* {@link #preProcess preprocessed}
* @param conn the connection over which to send the request,
* already established
* @param context the context for sending the request
*
* @return a terminal response received as part of an expect-continue
* handshake, or
* <code>null</code> if the expect-continue handshake is not used
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected HttpResponse doSendRequest(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.FALSE);
conn.sendRequestHeader(request);
if (request instanceof HttpEntityEnclosingRequest) {
// Check for expect-continue handshake. We have to flush the
// headers and wait for an 100-continue response to handle it.
// If we get a different response, we must not send the entity.
boolean sendentity = true;
final ProtocolVersion ver =
request.getRequestLine().getProtocolVersion();
if (((HttpEntityEnclosingRequest) request).expectContinue() &&
!ver.lessEquals(HttpVersion.HTTP_1_0)) {
conn.flush();
// As suggested by RFC 2616 section 8.2.3, we don't wait for a
// 100-continue response forever. On timeout, send the entity.
int tms = request.getParams().getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000);
if (conn.isResponseAvailable(tms)) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
if (status != HttpStatus.SC_CONTINUE) {
throw new ProtocolException(
"Unexpected response: " + response.getStatusLine());
}
// discard 100-continue
response = null;
} else {
sendentity = false;
}
}
}
if (sendentity) {
conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
}
}
conn.flush();
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE);
return response;
}
/**
* Waits for and receives a response.
* This method will automatically ignore intermediate responses
* with status code 1xx.
*
* @param request the request for which to obtain the response
* @param conn the connection over which the request was sent
* @param context the context for receiving the response
*
* @return the terminal response, not yet post-processed
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected HttpResponse doReceiveResponse(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
int statuscode = 0;
while (response == null || statuscode < HttpStatus.SC_OK) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
statuscode = response.getStatusLine().getStatusCode();
} // while intermediate response
return response;
}
/**
* Post-processes the given response using the given protocol processor and
* completes the process of request execution.
* <p>
* This method does <i>not</i> read the response entity, if any.
* The connection over which content of the response entity is being
* streamed from cannot be reused until {@link HttpEntity#consumeContent()}
* has been invoked.
*
* @param response the response object to post-process
* @param processor the processor to use
* @param context the context for post-processing the response
*
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void postProcess(
final HttpResponse response,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
processor.process(response, context);
}
} // class HttpRequestExecutor
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Generates a date in the format required by the HTTP protocol.
*
* @since 4.0
*/
public class HttpDateGenerator {
/** Date format pattern used to generate the header in RFC 1123 format. */
public static final
String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/** The time zone to use in the date header. */
public static final TimeZone GMT = TimeZone.getTimeZone("GMT");
private final DateFormat dateformat;
private long dateAsLong = 0L;
private String dateAsText = null;
public HttpDateGenerator() {
super();
this.dateformat = new SimpleDateFormat(PATTERN_RFC1123, Locale.US);
this.dateformat.setTimeZone(GMT);
}
public synchronized String getCurrentDate() {
long now = System.currentTimeMillis();
if (now - this.dateAsLong > 1000) {
// Generate new date string
this.dateAsText = this.dateformat.format(new Date(now));
this.dateAsLong = now;
}
return this.dateAsText;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Immutable {@link HttpProcessor}.
*
* @since 4.1
*/
//@ThreadSafe
public final class ImmutableHttpProcessor implements HttpProcessor {
private final HttpRequestInterceptor[] requestInterceptors;
private final HttpResponseInterceptor[] responseInterceptors;
public ImmutableHttpProcessor(
final HttpRequestInterceptor[] requestInterceptors,
final HttpResponseInterceptor[] responseInterceptors) {
super();
if (requestInterceptors != null) {
int count = requestInterceptors.length;
this.requestInterceptors = new HttpRequestInterceptor[count];
for (int i = 0; i < count; i++) {
this.requestInterceptors[i] = requestInterceptors[i];
}
} else {
this.requestInterceptors = new HttpRequestInterceptor[0];
}
if (responseInterceptors != null) {
int count = responseInterceptors.length;
this.responseInterceptors = new HttpResponseInterceptor[count];
for (int i = 0; i < count; i++) {
this.responseInterceptors[i] = responseInterceptors[i];
}
} else {
this.responseInterceptors = new HttpResponseInterceptor[0];
}
}
public ImmutableHttpProcessor(
final HttpRequestInterceptorList requestInterceptors,
final HttpResponseInterceptorList responseInterceptors) {
super();
if (requestInterceptors != null) {
int count = requestInterceptors.getRequestInterceptorCount();
this.requestInterceptors = new HttpRequestInterceptor[count];
for (int i = 0; i < count; i++) {
this.requestInterceptors[i] = requestInterceptors.getRequestInterceptor(i);
}
} else {
this.requestInterceptors = new HttpRequestInterceptor[0];
}
if (responseInterceptors != null) {
int count = responseInterceptors.getResponseInterceptorCount();
this.responseInterceptors = new HttpResponseInterceptor[count];
for (int i = 0; i < count; i++) {
this.responseInterceptors[i] = responseInterceptors.getResponseInterceptor(i);
}
} else {
this.responseInterceptors = new HttpResponseInterceptor[0];
}
}
public ImmutableHttpProcessor(final HttpRequestInterceptor[] requestInterceptors) {
this(requestInterceptors, null);
}
public ImmutableHttpProcessor(final HttpResponseInterceptor[] responseInterceptors) {
this(null, responseInterceptors);
}
public void process(
final HttpRequest request,
final HttpContext context) throws IOException, HttpException {
for (int i = 0; i < this.requestInterceptors.length; i++) {
this.requestInterceptors[i].process(request, context);
}
}
public void process(
final HttpResponse response,
final HttpContext context) throws IOException, HttpException {
for (int i = 0; i < this.responseInterceptors.length; i++) {
this.responseInterceptors[i].process(response, 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.protocol;
import java.util.List;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Provides access to an ordered list of response interceptors.
* Lists are expected to be built upfront and used read-only afterwards
* for {@link HttpProcessor processing}.
*
* @since 4.0
*/
public interface HttpResponseInterceptorList {
/**
* Appends a response interceptor to this list.
*
* @param interceptor the response interceptor to add
*/
void addResponseInterceptor(HttpResponseInterceptor interceptor);
/**
* Inserts a response interceptor at the specified index.
*
* @param interceptor the response interceptor to add
* @param index the index to insert the interceptor at
*/
void addResponseInterceptor(HttpResponseInterceptor interceptor, int index);
/**
* Obtains the current size of this list.
*
* @return the number of response interceptors in this list
*/
int getResponseInterceptorCount();
/**
* Obtains a response interceptor from this list.
*
* @param index the index of the interceptor to obtain,
* 0 for first
*
* @return the interceptor at the given index, or
* <code>null</code> if the index is out of range
*/
HttpResponseInterceptor getResponseInterceptor(int index);
/**
* Removes all response interceptors from this list.
*/
void clearResponseInterceptors();
/**
* Removes all response interceptor of the specified class
*
* @param clazz the class of the instances to be removed.
*/
void removeResponseInterceptorByClass(Class clazz);
/**
* Sets the response interceptors in this list.
* This list will be cleared and re-initialized to contain
* all response interceptors from the argument list.
* If the argument list includes elements that are not response
* interceptors, the behavior is implementation dependent.
*
* @param list the list of response interceptors
*/
void setInterceptors(List list);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
/**
* ResponseContent is the most important interceptor for outgoing responses.
* It is responsible for delimiting content length by adding
* <code>Content-Length</code> or <code>Transfer-Content</code> headers based
* on the properties of the enclosed entity and the protocol version.
* This interceptor is required for correct functioning of server side protocol
* processors.
*
* @since 4.0
*/
public class ResponseContent implements HttpResponseInterceptor {
public ResponseContent() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (response.containsHeader(HTTP.TRANSFER_ENCODING)) {
throw new ProtocolException("Transfer-encoding header already present");
}
if (response.containsHeader(HTTP.CONTENT_LEN)) {
throw new ProtocolException("Content-Length header already present");
}
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
} else if (len >= 0) {
response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
}
// Specify a content type if known
if (entity.getContentType() != null && !response.containsHeader(
HTTP.CONTENT_TYPE )) {
response.addHeader(entity.getContentType());
}
// Specify a content encoding if known
if (entity.getContentEncoding() != null && !response.containsHeader(
HTTP.CONTENT_ENCODING)) {
response.addHeader(entity.getContentEncoding());
}
} else {
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT) {
response.addHeader(HTTP.CONTENT_LEN, "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.protocol;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* HTTP protocol processor is a collection of protocol interceptors that
* implements the 'Chain of Responsibility' pattern, where each individual
* protocol interceptor is expected to work on a particular aspect of the HTTP
* protocol the interceptor is responsible for.
* <p>
* Usually the order in which interceptors are executed should not matter as
* long as they do not depend on a particular state of the execution context.
* If protocol interceptors have interdependencies and therefore must be
* executed in a particular order, they should be added to the protocol
* processor in the same sequence as their expected execution order.
* <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 HttpProcessor
extends HttpRequestInterceptor, HttpResponseInterceptor {
// no additional methods
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
/**
* HttpContext represents execution state of an HTTP process. It is a structure
* that can be used to map an attribute name to an attribute value. Internally
* HTTP context implementations are usually backed by a {@link HashMap}.
* <p>
* The primary purpose of the HTTP context is to facilitate information sharing
* among various logically related components. HTTP context can be used
* to store a processing state for one message or several consecutive messages.
* Multiple logically related messages can participate in a logical session
* if the same context is reused between consecutive messages.
*
* @since 4.0
*/
public interface HttpContext {
/** The prefix reserved for use by HTTP components. "http." */
public static final String RESERVED_PREFIX = "http.";
/**
* Obtains attribute with the given name.
*
* @param id the attribute name.
* @return attribute value, or <code>null</code> if not set.
*/
Object getAttribute(String id);
/**
* Sets value of the attribute with the given name.
*
* @param id the attribute name.
* @param obj the attribute value.
*/
void setAttribute(String id, Object obj);
/**
* Removes attribute with the given name from the context.
*
* @param id the attribute name.
* @return attribute value, or <code>null</code> if not set.
*/
Object removeAttribute(String id);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* Thread-safe extension of the {@link BasicHttpContext}.
*
* @since 4.0
*/
public class SyncBasicHttpContext extends BasicHttpContext {
public SyncBasicHttpContext(final HttpContext parentContext) {
super(parentContext);
}
public synchronized Object getAttribute(final String id) {
return super.getAttribute(id);
}
public synchronized void setAttribute(final String id, final Object obj) {
super.setAttribute(id, obj);
}
public synchronized Object removeAttribute(final String id) {
return super.removeAttribute(id);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
/**
* Default implementation of {@link HttpProcessor}.
* <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
*/
//@NotThreadSafe // Lists are not synchronized
public final class BasicHttpProcessor implements
HttpProcessor, HttpRequestInterceptorList, HttpResponseInterceptorList, Cloneable {
// Don't allow direct access, as nulls are not allowed
protected final List requestInterceptors = new ArrayList();
protected final List responseInterceptors = new ArrayList();
public void addRequestInterceptor(final HttpRequestInterceptor itcp) {
if (itcp == null) {
return;
}
this.requestInterceptors.add(itcp);
}
public void addRequestInterceptor(
final HttpRequestInterceptor itcp, int index) {
if (itcp == null) {
return;
}
this.requestInterceptors.add(index, itcp);
}
public void addResponseInterceptor(
final HttpResponseInterceptor itcp, int index) {
if (itcp == null) {
return;
}
this.responseInterceptors.add(index, itcp);
}
public void removeRequestInterceptorByClass(final Class clazz) {
for (Iterator it = this.requestInterceptors.iterator();
it.hasNext(); ) {
Object request = it.next();
if (request.getClass().equals(clazz)) {
it.remove();
}
}
}
public void removeResponseInterceptorByClass(final Class clazz) {
for (Iterator it = this.responseInterceptors.iterator();
it.hasNext(); ) {
Object request = it.next();
if (request.getClass().equals(clazz)) {
it.remove();
}
}
}
public final void addInterceptor(final HttpRequestInterceptor interceptor) {
addRequestInterceptor(interceptor);
}
public final void addInterceptor(final HttpRequestInterceptor interceptor, int index) {
addRequestInterceptor(interceptor, index);
}
public int getRequestInterceptorCount() {
return this.requestInterceptors.size();
}
public HttpRequestInterceptor getRequestInterceptor(int index) {
if ((index < 0) || (index >= this.requestInterceptors.size()))
return null;
return (HttpRequestInterceptor) this.requestInterceptors.get(index);
}
public void clearRequestInterceptors() {
this.requestInterceptors.clear();
}
public void addResponseInterceptor(final HttpResponseInterceptor itcp) {
if (itcp == null) {
return;
}
this.responseInterceptors.add(itcp);
}
public final void addInterceptor(final HttpResponseInterceptor interceptor) {
addResponseInterceptor(interceptor);
}
public final void addInterceptor(final HttpResponseInterceptor interceptor, int index) {
addResponseInterceptor(interceptor, index);
}
public int getResponseInterceptorCount() {
return this.responseInterceptors.size();
}
public HttpResponseInterceptor getResponseInterceptor(int index) {
if ((index < 0) || (index >= this.responseInterceptors.size()))
return null;
return (HttpResponseInterceptor) this.responseInterceptors.get(index);
}
public void clearResponseInterceptors() {
this.responseInterceptors.clear();
}
/**
* Sets the interceptor lists.
* First, both interceptor lists maintained by this processor
* will be cleared.
* Subsequently,
* elements of the argument list that are request interceptors will be
* added to the request interceptor list.
* Elements that are response interceptors will be
* added to the response interceptor list.
* Elements that are both request and response interceptor will be
* added to both lists.
* Elements that are neither request nor response interceptor
* will be ignored.
*
* @param list the list of request and response interceptors
* from which to initialize
*/
public void setInterceptors(final List list) {
if (list == null) {
throw new IllegalArgumentException("List must not be null.");
}
this.requestInterceptors.clear();
this.responseInterceptors.clear();
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
if (obj instanceof HttpRequestInterceptor) {
addInterceptor((HttpRequestInterceptor)obj);
}
if (obj instanceof HttpResponseInterceptor) {
addInterceptor((HttpResponseInterceptor)obj);
}
}
}
/**
* Clears both interceptor lists maintained by this processor.
*/
public void clearInterceptors() {
clearRequestInterceptors();
clearResponseInterceptors();
}
public void process(
final HttpRequest request,
final HttpContext context)
throws IOException, HttpException {
for (int i = 0; i < this.requestInterceptors.size(); i++) {
HttpRequestInterceptor interceptor =
(HttpRequestInterceptor) this.requestInterceptors.get(i);
interceptor.process(request, context);
}
}
public void process(
final HttpResponse response,
final HttpContext context)
throws IOException, HttpException {
for (int i = 0; i < this.responseInterceptors.size(); i++) {
HttpResponseInterceptor interceptor =
(HttpResponseInterceptor) this.responseInterceptors.get(i);
interceptor.process(response, context);
}
}
/**
* Sets up the target to have the same list of interceptors
* as the current instance.
*
* @param target object to be initialised
*/
protected void copyInterceptors(final BasicHttpProcessor target) {
target.requestInterceptors.clear();
target.requestInterceptors.addAll(this.requestInterceptors);
target.responseInterceptors.clear();
target.responseInterceptors.addAll(this.responseInterceptors);
}
/**
* Creates a copy of this instance
*
* @return new instance of the BasicHttpProcessor
*/
public BasicHttpProcessor copy() {
BasicHttpProcessor clone = new BasicHttpProcessor();
copyInterceptors(clone);
return clone;
}
public Object clone() throws CloneNotSupportedException {
BasicHttpProcessor clone = (BasicHttpProcessor) super.clone();
copyInterceptors(clone);
return 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.protocol;
import java.io.IOException;
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.HttpRequestInterceptor;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* RequestExpectContinue is responsible for enabling the 'expect-continue'
* handshake by adding <code>Expect</code> header. This interceptor is
* recommended for client side protocol processors.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
* </ul>
*
* @since 4.0
*/
public class RequestExpectContinue implements HttpRequestInterceptor {
public RequestExpectContinue() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
// Do not send the expect header if request body is known to be empty
if (entity != null && entity.getContentLength() != 0) {
ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
if (HttpProtocolParams.useExpectContinue(request.getParams())
&& !ver.lessEquals(HttpVersion.HTTP_1_0)) {
request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_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.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
/**
* RequestConnControl is responsible for adding <code>Connection</code> header
* to the outgoing requests, which is essential for managing persistence of
* <code>HTTP/1.0</code> connections. This interceptor is recommended for
* client side protocol processors.
*
* @since 4.0
*/
public class RequestConnControl implements HttpRequestInterceptor {
public RequestConnControl() {
super();
}
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
// Default policy is to keep connection alive
// whenever possible
request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.List;
import org.apache.ogt.http.HttpRequestInterceptor;
/**
* Provides access to an ordered list of request interceptors.
* Lists are expected to be built upfront and used read-only afterwards
* for {@link HttpProcessor processing}.
*
* @since 4.0
*/
public interface HttpRequestInterceptorList {
/**
* Appends a request interceptor to this list.
*
* @param interceptor the request interceptor to add
*/
void addRequestInterceptor(HttpRequestInterceptor interceptor);
/**
* Inserts a request interceptor at the specified index.
*
* @param interceptor the request interceptor to add
* @param index the index to insert the interceptor at
*/
void addRequestInterceptor(HttpRequestInterceptor interceptor, int index);
/**
* Obtains the current size of this list.
*
* @return the number of request interceptors in this list
*/
int getRequestInterceptorCount();
/**
* Obtains a request interceptor from this list.
*
* @param index the index of the interceptor to obtain,
* 0 for first
*
* @return the interceptor at the given index, or
* <code>null</code> if the index is out of range
*/
HttpRequestInterceptor getRequestInterceptor(int index);
/**
* Removes all request interceptors from this list.
*/
void clearRequestInterceptors();
/**
* Removes all request interceptor of the specified class
*
* @param clazz the class of the instances to be removed.
*/
void removeRequestInterceptorByClass(Class clazz);
/**
* Sets the request interceptors in this list.
* This list will be cleared and re-initialized to contain
* all request interceptors from the argument list.
* If the argument list includes elements that are not request
* interceptors, the behavior is implementation dependent.
*
* @param list the list of request interceptors
*/
void setInterceptors(List list);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.Map;
/**
* Maintains a map of HTTP request handlers keyed by a request URI pattern.
* <br>
* Patterns may have three formats:
* <ul>
* <li><code>*</code></li>
* <li><code>*<uri></code></li>
* <li><code><uri>*</code></li>
* </ul>
* <br>
* This class can be used to resolve an instance of
* {@link HttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver {
private final UriPatternMatcher matcher;
public HttpRequestHandlerRegistry() {
matcher = new UriPatternMatcher();
}
/**
* Registers the given {@link HttpRequestHandler} as a handler for URIs
* matching the given pattern.
*
* @param pattern the pattern to register the handler for.
* @param handler the handler.
*/
public void register(final String pattern, final HttpRequestHandler handler) {
if (pattern == null) {
throw new IllegalArgumentException("URI request pattern may not be null");
}
if (handler == null) {
throw new IllegalArgumentException("Request handler may not be null");
}
matcher.register(pattern, handler);
}
/**
* Removes registered handler, if exists, for the given pattern.
*
* @param pattern the pattern to unregister the handler for.
*/
public void unregister(final String pattern) {
matcher.unregister(pattern);
}
/**
* Sets handlers from the given map.
* @param map the map containing handlers keyed by their URI patterns.
*/
public void setHandlers(final Map map) {
matcher.setObjects(map);
}
public HttpRequestHandler lookup(final String requestURI) {
return (HttpRequestHandler) matcher.lookup(requestURI);
}
/**
* @deprecated
*/
protected boolean matchUriRequestPattern(final String pattern, final String requestUri) {
return matcher.matchUriRequestPattern(pattern, requestUri);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.params.CoreProtocolPNames;
/**
* ResponseServer is responsible for adding <code>Server</code> header. This
* interceptor is recommended for server side protocol processors.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#ORIGIN_SERVER}</li>
* </ul>
*
* @since 4.0
*/
public class ResponseServer implements HttpResponseInterceptor {
public ResponseServer() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (!response.containsHeader(HTTP.SERVER_HEADER)) {
String s = (String) response.getParams().getParameter(
CoreProtocolPNames.ORIGIN_SERVER);
if (s != null) {
response.addHeader(HTTP.SERVER_HEADER, s);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* {@link HttpContext} attribute names for protocol execution.
*
* @since 4.0
*/
public interface ExecutionContext {
/**
* Attribute name of a {@link org.apache.ogt.http.HttpConnection} object that
* represents the actual HTTP connection.
*/
public static final String HTTP_CONNECTION = "http.connection";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpRequest} object that
* represents the actual HTTP request.
*/
public static final String HTTP_REQUEST = "http.request";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpResponse} object that
* represents the actual HTTP response.
*/
public static final String HTTP_RESPONSE = "http.response";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpHost} object that
* represents the connection target.
*/
public static final String HTTP_TARGET_HOST = "http.target_host";
/**
* Attribute name of a {@link org.apache.ogt.http.HttpHost} object that
* represents the connection proxy.
*/
public static final String HTTP_PROXY_HOST = "http.proxy_host";
/**
* Attribute name of a {@link Boolean} object that represents the
* the flag indicating whether the actual request has been fully transmitted
* to the target host.
*/
public static final String HTTP_REQ_SENT = "http.request_sent";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.io.IOException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
/**
* ResponseConnControl is responsible for adding <code>Connection</code> header
* to the outgoing responses, which is essential for managing persistence of
* <code>HTTP/1.0</code> connections. This interceptor is recommended for
* server side protocol processors.
*
* @since 4.0
*/
public class ResponseConnControl implements HttpResponseInterceptor {
public ResponseConnControl() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// Always drop connection after certain type of responses
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_BAD_REQUEST ||
status == HttpStatus.SC_REQUEST_TIMEOUT ||
status == HttpStatus.SC_LENGTH_REQUIRED ||
status == HttpStatus.SC_REQUEST_TOO_LONG ||
status == HttpStatus.SC_REQUEST_URI_TOO_LONG ||
status == HttpStatus.SC_SERVICE_UNAVAILABLE ||
status == HttpStatus.SC_NOT_IMPLEMENTED) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
// Always drop connection for HTTP/1.0 responses and below
// if the content body cannot be correctly delimited
HttpEntity entity = response.getEntity();
if (entity != null) {
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
if (entity.getContentLength() < 0 &&
(!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) {
response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
return;
}
}
// Drop connection if requested by the client
HttpRequest request = (HttpRequest)
context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (request != null) {
Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE);
if (header != null) {
response.setHeader(HTTP.CONN_DIRECTIVE, header.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.protocol;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
/**
* ResponseDate is responsible for adding <code>Date<c/ode> header to the
* outgoing responses. This interceptor is recommended for server side protocol
* processors.
*
* @since 4.0
*/
public class ResponseDate implements HttpResponseInterceptor {
private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator();
public ResponseDate() {
super();
}
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException
("HTTP response may not be null.");
}
int status = response.getStatusLine().getStatusCode();
if ((status >= HttpStatus.SC_OK) &&
!response.containsHeader(HTTP.DATE_HEADER)) {
String httpdate = DATE_GENERATOR.getCurrentDate();
response.setHeader(HTTP.DATE_HEADER, httpdate);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
/**
* {@link HttpContext} implementation that delegates resolution of an attribute
* to the given default {@link HttpContext} instance if the attribute is not
* present in the local one. The state of the local context can be mutated,
* whereas the default context is treated as read-only.
*
* @since 4.0
*/
public final class DefaultedHttpContext implements HttpContext {
private final HttpContext local;
private final HttpContext defaults;
public DefaultedHttpContext(final HttpContext local, final HttpContext defaults) {
super();
if (local == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
this.local = local;
this.defaults = defaults;
}
public Object getAttribute(final String id) {
Object obj = this.local.getAttribute(id);
if (obj == null) {
return this.defaults.getAttribute(id);
} else {
return obj;
}
}
public Object removeAttribute(final String id) {
return this.local.removeAttribute(id);
}
public void setAttribute(final String id, final Object obj) {
this.local.setAttribute(id, obj);
}
public HttpContext 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.protocol;
import java.io.IOException;
import org.apache.ogt.http.ConnectionReuseStrategy;
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.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.UnsupportedHttpVersionException;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.EncodingUtils;
import org.apache.ogt.http.util.EntityUtils;
/**
* HttpService is a server side HTTP protocol handler based in the blocking
* I/O model that implements the essential requirements of the HTTP protocol
* for the server side message processing as described by RFC 2616.
* <br>
* HttpService relies on {@link HttpProcessor} to generate mandatory protocol
* headers for all outgoing messages and apply common, cross-cutting message
* transformations to all incoming and outgoing messages, whereas individual
* {@link HttpRequestHandler}s are expected to take care of application specific
* content generation and processing.
* <br>
* HttpService relies on {@link HttpRequestHandler} to resolve matching request
* handler for a particular request URI of an incoming HTTP request.
* <br>
* HttpService can use optional {@link HttpExpectationVerifier} to ensure that
* incoming requests meet server's expectations.
*
* @since 4.0
*/
public class HttpService {
/**
* TODO: make all variables final in the next major version
*/
private volatile HttpParams params = null;
private volatile HttpProcessor processor = null;
private volatile HttpRequestHandlerResolver handlerResolver = null;
private volatile ConnectionReuseStrategy connStrategy = null;
private volatile HttpResponseFactory responseFactory = null;
private volatile HttpExpectationVerifier expectationVerifier = null;
/**
* Create a new HTTP service.
*
* @param processor the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
* @param handlerResolver the handler resolver. May be null.
* @param expectationVerifier the expectation verifier. May be null.
* @param params the HTTP parameters
*
* @since 4.1
*/
public HttpService(
final HttpProcessor processor,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory,
final HttpRequestHandlerResolver handlerResolver,
final HttpExpectationVerifier expectationVerifier,
final HttpParams params) {
super();
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.processor = processor;
this.connStrategy = connStrategy;
this.responseFactory = responseFactory;
this.handlerResolver = handlerResolver;
this.expectationVerifier = expectationVerifier;
this.params = params;
}
/**
* Create a new HTTP service.
*
* @param processor the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
* @param handlerResolver the handler resolver. May be null.
* @param params the HTTP parameters
*
* @since 4.1
*/
public HttpService(
final HttpProcessor processor,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory,
final HttpRequestHandlerResolver handlerResolver,
final HttpParams params) {
this(processor, connStrategy, responseFactory, handlerResolver, null, params);
}
/**
* Create a new HTTP service.
*
* @param proc the processor to use on requests and responses
* @param connStrategy the connection reuse strategy
* @param responseFactory the response factory
*
* @deprecated use {@link HttpService#HttpService(HttpProcessor,
* ConnectionReuseStrategy, HttpResponseFactory, HttpRequestHandlerResolver, HttpParams)}
*/
public HttpService(
final HttpProcessor proc,
final ConnectionReuseStrategy connStrategy,
final HttpResponseFactory responseFactory) {
super();
setHttpProcessor(proc);
setConnReuseStrategy(connStrategy);
setResponseFactory(responseFactory);
}
/**
* @deprecated set {@link HttpProcessor} using constructor
*/
public void setHttpProcessor(final HttpProcessor processor) {
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
this.processor = processor;
}
/**
* @deprecated set {@link ConnectionReuseStrategy} using constructor
*/
public void setConnReuseStrategy(final ConnectionReuseStrategy connStrategy) {
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
this.connStrategy = connStrategy;
}
/**
* @deprecated set {@link HttpResponseFactory} using constructor
*/
public void setResponseFactory(final HttpResponseFactory responseFactory) {
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
/**
* @deprecated set {@link HttpResponseFactory} using constructor
*/
public void setParams(final HttpParams params) {
this.params = params;
}
/**
* @deprecated set {@link HttpRequestHandlerResolver} using constructor
*/
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
/**
* @deprecated set {@link HttpExpectationVerifier} using constructor
*/
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public HttpParams getParams() {
return this.params;
}
/**
* Handles receives one HTTP request over the given connection within the
* given execution context and sends a response back to the client.
*
* @param conn the active connection to the client
* @param context the actual execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
public void handleRequest(
final HttpServerConnection conn,
final HttpContext context) throws IOException, HttpException {
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
HttpResponse response = null;
try {
HttpRequest request = conn.receiveRequestHeader();
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
ProtocolVersion ver =
request.getRequestLine().getProtocolVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
response = this.responseFactory.newHttpResponse(ver,
HttpStatus.SC_CONTINUE, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
}
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
conn.sendResponseHeader(response);
conn.flush();
response = null;
conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
}
} else {
conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
}
}
if (response == null) {
response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_OK, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
this.processor.process(request, context);
doService(request, response, context);
}
// Make sure the request content is fully consumed
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
EntityUtils.consume(entity);
}
} catch (HttpException ex) {
response = this.responseFactory.newHttpResponse
(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(ex, response);
}
this.processor.process(response, context);
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.flush();
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
}
/**
* Handles the given exception and generates an HTTP response to be sent
* back to the client to inform about the exceptional condition encountered
* in the course of the request processing.
*
* @param ex the exception.
* @param response the HTTP response.
*/
protected void handleException(final HttpException ex, final HttpResponse response) {
if (ex instanceof MethodNotSupportedException) {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
} else if (ex instanceof UnsupportedHttpVersionException) {
response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
} else if (ex instanceof ProtocolException) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
} else {
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
ByteArrayEntity entity = new ByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
/**
* The default implementation of this method attempts to resolve an
* {@link HttpRequestHandler} for the request URI of the given request
* and, if found, executes its
* {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method.
* <p>
* Super-classes can override this method in order to provide a custom
* implementation of the request processing logic.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param context the execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
protected void doService(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
if (handler != null) {
handler.handle(request, response, context);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Maintains a map of objects keyed by a request URI pattern.
* <br>
* Patterns may have three formats:
* <ul>
* <li><code>*</code></li>
* <li><code>*<uri></code></li>
* <li><code><uri>*</code></li>
* </ul>
* <br>
* This class can be used to resolve an object matching a particular request
* URI.
*
* @since 4.0
*/
public class UriPatternMatcher {
/**
* TODO: Replace with ConcurrentHashMap
*/
private final Map map;
public UriPatternMatcher() {
super();
this.map = new HashMap();
}
/**
* Registers the given object for URIs matching the given pattern.
*
* @param pattern the pattern to register the handler for.
* @param obj the object.
*/
public synchronized void register(final String pattern, final Object obj) {
if (pattern == null) {
throw new IllegalArgumentException("URI request pattern may not be null");
}
this.map.put(pattern, obj);
}
/**
* Removes registered object, if exists, for the given pattern.
*
* @param pattern the pattern to unregister.
*/
public synchronized void unregister(final String pattern) {
if (pattern == null) {
return;
}
this.map.remove(pattern);
}
/**
* @deprecated use {@link #setObjects(Map)}
*/
public synchronized void setHandlers(final Map map) {
if (map == null) {
throw new IllegalArgumentException("Map of handlers may not be null");
}
this.map.clear();
this.map.putAll(map);
}
/**
* Sets objects from the given map.
* @param map the map containing objects keyed by their URI patterns.
*/
public synchronized void setObjects(final Map map) {
if (map == null) {
throw new IllegalArgumentException("Map of handlers may not be null");
}
this.map.clear();
this.map.putAll(map);
}
/**
* Looks up an object matching the given request URI.
*
* @param requestURI the request URI
* @return object or <code>null</code> if no match is found.
*/
public synchronized Object lookup(String requestURI) {
if (requestURI == null) {
throw new IllegalArgumentException("Request URI may not be null");
}
//Strip away the query part part if found
int index = requestURI.indexOf("?");
if (index != -1) {
requestURI = requestURI.substring(0, index);
}
// direct match?
Object obj = this.map.get(requestURI);
if (obj == null) {
// pattern match?
String bestMatch = null;
for (Iterator it = this.map.keySet().iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (matchUriRequestPattern(pattern, requestURI)) {
// we have a match. is it any better?
if (bestMatch == null
|| (bestMatch.length() < pattern.length())
|| (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) {
obj = this.map.get(pattern);
bestMatch = pattern;
}
}
}
}
return obj;
}
/**
* Tests if the given request URI matches the given pattern.
*
* @param pattern the pattern
* @param requestUri the request URI
* @return <code>true</code> if the request URI matches the pattern,
* <code>false</code> otherwise.
*/
protected boolean matchUriRequestPattern(final String pattern, final String requestUri) {
if (pattern.equals("*")) {
return true;
} else {
return
(pattern.endsWith("*") && requestUri.startsWith(pattern.substring(0, pattern.length() - 1))) ||
(pattern.startsWith("*") && requestUri.endsWith(pattern.substring(1, pattern.length())));
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.protocol;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation of {@link HttpContext}.
* <p>
* Please note methods of this class are not synchronized and therefore may
* be threading unsafe.
*
* @since 4.0
*/
public class BasicHttpContext implements HttpContext {
private final HttpContext parentContext;
private Map map = null;
public BasicHttpContext() {
this(null);
}
public BasicHttpContext(final HttpContext parentContext) {
super();
this.parentContext = parentContext;
}
public Object getAttribute(final String id) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
Object obj = null;
if (this.map != null) {
obj = this.map.get(id);
}
if (obj == null && this.parentContext != null) {
obj = this.parentContext.getAttribute(id);
}
return obj;
}
public void setAttribute(final String id, final Object obj) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
if (this.map == null) {
this.map = new HashMap();
}
this.map.put(id, obj);
}
public Object removeAttribute(final String id) {
if (id == null) {
throw new IllegalArgumentException("Id may not be null");
}
if (this.map != null) {
return this.map.remove(id);
} else {
return null;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* Signals that the target server failed to respond with a valid HTTP response.
*
* @since 4.0
*/
public class NoHttpResponseException extends IOException {
private static final long serialVersionUID = -7658940387386078766L;
/**
* Creates a new NoHttpResponseException with the specified detail message.
*
* @param message exception message
*/
public NoHttpResponseException(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 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 = <the OCTETs making up the field-value
* and consisting of either *TEXT or combinations
* of token, separators, and quoted-string>
*</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*<any char except "=", ",", ";", <"> and
* white space>
* quoted-string = <"> *( text | quoted-char ) <">
* text = any char except <">
* 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.