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.mockup;
import java.net.URI;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
/**
* Mockup of a {@link ProxySelector}.
* Always returns a fixed list.
*/
public class ProxySelectorMockup extends ProxySelector {
protected List<Proxy> proxyList;
/**
* Creates a mock proxy selector.
*
* @param proxies the list of proxies, or
* <code>null</code> for direct connections
*/
public ProxySelectorMockup(List<Proxy> proxies) {
if (proxies == null) {
proxies = new ArrayList<Proxy>(1);
proxies.add(Proxy.NO_PROXY);
} else if (proxies.isEmpty()) {
throw new IllegalArgumentException
("Proxy list must not be empty.");
}
proxyList = proxies;
}
/**
* Obtains the constructor argument.
*
* @param ignored not used by this mockup
*
* @return the list passed to the constructor,
* or a default list with "DIRECT" as the only element
*/
@Override
public List<Proxy> select(URI ignored) {
return proxyList;
}
/**
* Does nothing.
*/
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// no body
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.conn;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
/**
* Static helper methods.
*/
public final class Helper {
/** Disabled default constructor. */
private Helper() {
// no body
}
/**
* Executes a request.
*/
public static HttpResponse execute(HttpRequest req,
HttpClientConnection conn,
HttpHost target,
HttpRequestExecutor exec,
HttpProcessor proc,
HttpParams params,
HttpContext ctxt)
throws Exception {
ctxt.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
ctxt.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
ctxt.setAttribute(ExecutionContext.HTTP_REQUEST, req);
req.setParams(new DefaultedHttpParams(req.getParams(), params));
exec.preProcess(req, proc, ctxt);
HttpResponse rsp = exec.execute(req, conn, ctxt);
rsp.setParams(new DefaultedHttpParams(rsp.getParams(), params));
exec.postProcess(rsp, proc, ctxt);
return rsp;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.conn;
import java.io.IOException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.impl.conn.AbstractClientConnAdapter;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Mockup connection adapter.
*/
public class ClientConnAdapterMockup extends AbstractClientConnAdapter {
public ClientConnAdapterMockup(ClientConnectionManager mgr) {
super(mgr, null);
}
public void close() {
}
public HttpRoute getRoute() {
throw new UnsupportedOperationException("just a mockup");
}
public void layerProtocol(HttpContext context, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException {
throw new UnsupportedOperationException("just a mockup");
}
public void shutdown() {
}
public void tunnelTarget(boolean secure, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public Object getState() {
throw new UnsupportedOperationException("just a mockup");
}
public void setState(Object state) {
throw new UnsupportedOperationException("just a mockup");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.conn.tsccm;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import org.apache.ogt.http.impl.conn.tsccm.WaitingThread;
/**
* Thread to await something.
*/
public class AwaitThread extends Thread {
protected final WaitingThread wait_object;
protected final Lock wait_lock;
protected final Date wait_deadline;
protected volatile boolean waiting;
protected volatile Throwable exception;
/**
* Creates a new thread.
* When this thread is started, it will wait on the argument object.
*/
public AwaitThread(WaitingThread where, Lock lck, Date deadline) {
wait_object = where;
wait_lock = lck;
wait_deadline = deadline;
}
/**
* This method is executed when the thread is started.
*/
@Override
public void run() {
try {
wait_lock.lock();
waiting = true;
wait_object.await(wait_deadline);
} catch (Throwable dart) {
exception = dart;
} finally {
waiting = false;
wait_lock.unlock();
}
// terminate
}
public Throwable getException() {
return exception;
}
public boolean isWaiting() {
try {
wait_lock.lock();
return waiting;
} finally {
wait_lock.unlock();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.util.concurrent.TimeUnit;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* Thread to get a connection from a connection manager.
* Used by connection manager tests.
* Code based on HttpClient 3.x class <code>TestHttpConnectionManager</code>.
*/
public class GetConnThread extends Thread {
protected final HttpRoute conn_route;
protected final long conn_timeout;
protected final ClientConnectionRequest conn_request;
protected volatile ManagedClientConnection connection;
protected volatile Throwable exception;
/**
* Creates a new thread for requesting a connection from the given manager.
*
* When this thread is started, it will try to obtain a connection.
* The timeout is in milliseconds.
*/
public GetConnThread(ClientConnectionManager mgr,
HttpRoute route, long timeout) {
this(mgr.requestConnection(route, null), route, timeout);
}
/**
* Creates a new for requesting a connection from the given request object.
*
* When this thread is started, it will try to obtain a connection.
* The timeout is in milliseconds.
*/
public GetConnThread(ClientConnectionRequest connectionRequest,
HttpRoute route, long timeout) {
conn_route = route;
conn_timeout = timeout;
conn_request = connectionRequest;
}
/**
* This method is executed when the thread is started.
*/
@Override
public void run() {
try {
connection = conn_request.getConnection
(conn_timeout, TimeUnit.MILLISECONDS);
} catch (Throwable dart) {
exception = dart;
}
// terminate
}
public Throwable getException() {
return exception;
}
public ManagedClientConnection getConnection() {
return connection;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.conn;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.util.EntityUtils;
/**
* Executes a request from a new thread.
*
*/
public class ExecReqThread extends GetConnThread {
protected final ClientConnectionManager conn_manager;
protected final RequestSpec request_spec;
protected volatile HttpResponse response;
protected volatile byte[] response_data;
/**
* Executes a request.
* This involves the following steps:
* <ol>
* <li>obtain a connection (see base class)</li>
* <li>open the connection</li>
* <li>prepare context and request</li>
* <li>execute request to obtain the response</li>
* <li>consume the response entity (if there is one)</li>
* <li>release the connection</li>
* </ol>
*/
public ExecReqThread(ClientConnectionManager mgr,
HttpRoute route, long timeout,
RequestSpec reqspec) {
super(mgr, route, timeout);
this.conn_manager = mgr;
request_spec = reqspec;
}
public HttpResponse getResponse() {
return response;
}
public byte[] getResponseData() {
return response_data;
}
/**
* This method is invoked when the thread is started.
* It invokes the base class implementation.
*/
@Override
public void run() {
super.run(); // obtain connection
if (connection == null)
return; // problem obtaining connection
try {
request_spec.context.setAttribute
(ExecutionContext.HTTP_CONNECTION, connection);
doOpenConnection();
HttpRequest request = (HttpRequest) request_spec.context.
getAttribute(ExecutionContext.HTTP_REQUEST);
request_spec.executor.preProcess
(request, request_spec.processor, request_spec.context);
response = request_spec.executor.execute
(request, connection, request_spec.context);
request_spec.executor.postProcess
(response, request_spec.processor, request_spec.context);
doConsumeResponse();
} catch (Throwable dart) {
dart.printStackTrace(System.out);
if (exception != null)
exception = dart;
} finally {
conn_manager.releaseConnection(connection, -1, null);
}
}
/**
* Opens the connection after it has been obtained.
*/
protected void doOpenConnection() throws Exception {
connection.open
(conn_route, request_spec.context, request_spec.params);
}
/**
* Reads the response entity, if there is one.
*/
protected void doConsumeResponse() throws Exception {
if (response.getEntity() != null)
response_data = EntityUtils.toByteArray(response.getEntity());
}
/**
* Helper class collecting request data.
* The request and target are expected in the context.
*/
public static class RequestSpec {
public HttpRequestExecutor executor;
public HttpProcessor processor;
public HttpContext context;
public HttpParams params;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicHeader;
/**
* Implementation of Amazon S3 authentication. This scheme must be used
* preemptively only.
* <p>
* Reference Document: {@link http
* ://docs.amazonwebservices.com/AmazonS3/latest/index
* .html?RESTAuthentication.html}
*/
public class AWSScheme implements AuthScheme {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static final String NAME = "AWS";
public AWSScheme() {
}
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
// If the Date header has not been provided add it as it is required
if (request.getFirstHeader("Date") == null) {
Header dateHeader = new BasicHeader("Date", DateUtils.formatDate(new Date()));
request.addHeader(dateHeader);
}
String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(request.getAllHeaders());
String canonicalizedResource = getCanonicalizedResource(request.getRequestLine().getUri(),
(request.getFirstHeader("Host") != null ? request.getFirstHeader("Host").getValue()
: null));
String contentMD5 = request.getFirstHeader("Content-MD5") != null ? request.getFirstHeader(
"Content-MD5").getValue() : "";
String contentType = request.getFirstHeader("Content-Type") != null ? request
.getFirstHeader("Content-Type").getValue() : "";
String date = request.getFirstHeader("Date").getValue();
String method = request.getRequestLine().getMethod();
StringBuilder toSign = new StringBuilder();
toSign.append(method).append("\n");
toSign.append(contentMD5).append("\n");
toSign.append(contentType).append("\n");
toSign.append(date).append("\n");
toSign.append(canonicalizedAmzHeaders);
toSign.append(canonicalizedResource);
String signature = calculateRFC2104HMAC(toSign.toString(), credentials.getPassword());
String headerValue = NAME + " " + credentials.getUserPrincipal().getName() + ":" + signature.trim();
return new BasicHeader("Authorization", headerValue);
}
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data
* The data to be signed.
* @param key
* The signing key.
* @return The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws RuntimeException
* when signature generation fails
*/
private static String calculateRFC2104HMAC(
final String data,
final String key) throws AuthenticationException {
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
return Base64.encodeBase64String(rawHmac);
} catch (InvalidKeyException ex) {
throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex);
} catch (NoSuchAlgorithmException ex) {
throw new AuthenticationException(HMAC_SHA1_ALGORITHM +
" algorithm is not supported", ex);
}
}
/**
* Returns the canonicalized AMZ headers.
*
* @param headers
* The list of request headers.
* @return The canonicalized AMZ headers.
*/
private static String getCanonicalizedAmzHeaders(final Header[] headers) {
StringBuilder sb = new StringBuilder();
Pattern spacePattern = Pattern.compile("\\s+");
// Create a lexographically sorted list of headers that begin with x-amz
SortedMap<String, String> amzHeaders = new TreeMap<String, String>();
for (Header header : headers) {
String name = header.getName().toLowerCase();
if (name.startsWith("x-amz-")) {
String value = "";
if (amzHeaders.containsKey(name))
value = amzHeaders.get(name) + "," + header.getValue();
else
value = header.getValue();
// All newlines and multiple spaces must be replaced with a
// single space character.
Matcher m = spacePattern.matcher(value);
value = m.replaceAll(" ");
amzHeaders.put(name, value);
}
}
// Concatenate all AMZ headers
for (Entry<String, String> entry : amzHeaders.entrySet()) {
sb.append(entry.getKey()).append(':').append(entry.getValue()).append("\n");
}
return sb.toString();
}
/**
* Returns the canonicalized resource.
*
* @param uri
* The resource uri
* @param hostName
* the host name
* @return The canonicalized resource.
*/
private static String getCanonicalizedResource(String uri, String hostName) {
StringBuilder sb = new StringBuilder();
// Append the bucket if there is one
if (hostName != null) {
// If the host name contains a port number remove it
if (hostName.contains(":"))
hostName = hostName.substring(0, hostName.indexOf(":"));
// Now extract the bucket if there is one
if (hostName.endsWith(".s3.amazonaws.com")) {
String bucketName = hostName.substring(0, hostName.length() - 17);
sb.append("/" + bucketName);
}
}
int queryIdx = uri.indexOf("?");
// Append the resource path
if (queryIdx >= 0)
sb.append(uri.substring(0, queryIdx));
else
sb.append(uri.substring(0, uri.length()));
// Append the AWS sub-resource
if (queryIdx >= 0) {
String query = uri.substring(queryIdx - 1, uri.length());
if (query.contains("?acl"))
sb.append("?acl");
else if (query.contains("?location"))
sb.append("?location");
else if (query.contains("?logging"))
sb.append("?logging");
else if (query.contains("?torrent"))
sb.append("?torrent");
}
return sb.toString();
}
public String getParameter(String name) {
return null;
}
public String getRealm() {
return null;
}
public String getSchemeName() {
return NAME;
}
public boolean isComplete() {
return true;
}
public boolean isConnectionBased() {
return false;
}
public void processChallenge(final Header header) throws MalformedChallengeException {
// Nothing to do here
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link AWSScheme} instances.
*/
public class AWSSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new AWSScheme();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.impl.auth.SpnegoTokenGenerator;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.util.ASN1Dump;
/**
* Takes Kerberos ticket and wraps into a SPNEGO token. Leaving some optional fields out.
*/
public class BouncySpnegoTokenGenerator implements SpnegoTokenGenerator {
private final Log log = LogFactory.getLog(getClass());
private final DERObjectIdentifier spnegoOid;
private final DERObjectIdentifier kerbOid;
public BouncySpnegoTokenGenerator() {
super();
this.spnegoOid = new DERObjectIdentifier("1.3.6.1.5.5.2");
this.kerbOid = new DERObjectIdentifier("1.2.840.113554.1.2.2");
}
public byte [] generateSpnegoDERObject(byte [] kerbTicket) throws IOException {
DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket);
DERSequence kerbOidSeq = new DERSequence(kerbOid);
DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq);
DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tagged0);
v.add(tagged2);
DERSequence seq = new DERSequence(v);
DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ASN1OutputStream asn1Out = new ASN1OutputStream(out);
ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object();
ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object();
int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length;
byte [] lenBytes = writeLength(length);
byte[] appWrap = new byte[lenBytes.length + 1];
appWrap[0] = 0x60;
for(int i=1; i < appWrap.length; i++){
appWrap[i] = lenBytes[i-1];
}
asn1Out.write(appWrap);
asn1Out.writeObject(spnegoOid.toASN1Object());
asn1Out.writeObject(taggedSpnego.toASN1Object());
byte[] app = out.toByteArray();
ASN1InputStream in = new ASN1InputStream(app);
if (log.isDebugEnabled() ){
int skip = 12;
byte [] manipBytes = new byte[app.length - skip];
for(int i=skip; i < app.length; i++){
manipBytes[i-skip] = app[i];
}
ASN1InputStream ourSpnego = new ASN1InputStream( manipBytes );
log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject()));
}
return in.readObject().getDEREncoded();
}
private byte [] writeLength(int length) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (length > 127) {
int size = 1;
int val = length;
while ((val >>>= 8) != 0) {
size++;
}
out.write((byte) (size | 0x80));
for (int i = (size - 1) * 8; i >= 0; i -= 8) {
out.write((byte) (length >> i));
}
} else {
out.write((byte) length);
}
return out.toByteArray();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Random;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.entity.mime.content.ContentBody;
import org.apache.ogt.http.message.BasicHeader;
import org.apache.ogt.http.protocol.HTTP;
/**
* Multipart/form coded HTTP entity consisting of multiple body parts.
*
* @since 4.0
*/
public class MultipartEntity implements HttpEntity {
/**
* The pool of ASCII chars to be used for generating a multipart boundary.
*/
private final static char[] MULTIPART_CHARS =
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
private final HttpMultipart multipart;
private final Header contentType;
// @GuardedBy("dirty") // we always read dirty before accessing length
private long length;
private volatile boolean dirty; // used to decide whether to recalculate length
/**
* Creates an instance using the specified parameters
* @param mode the mode to use, may be {@code null}, in which case {@link HttpMultipartMode#STRICT} is used
* @param boundary the boundary string, may be {@code null}, in which case {@link #generateBoundary()} is invoked to create the string
* @param charset the character set to use, may be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
*/
public MultipartEntity(
HttpMultipartMode mode,
String boundary,
Charset charset) {
super();
if (boundary == null) {
boundary = generateBoundary();
}
if (mode == null) {
mode = HttpMultipartMode.STRICT;
}
this.multipart = new HttpMultipart("form-data", charset, boundary, mode);
this.contentType = new BasicHeader(
HTTP.CONTENT_TYPE,
generateContentType(boundary, charset));
this.dirty = true;
}
/**
* Creates an instance using the specified {@link HttpMultipartMode} mode.
* Boundary and charset are set to {@code null}.
* @param mode the desired mode
*/
public MultipartEntity(final HttpMultipartMode mode) {
this(mode, null, null);
}
/**
* Creates an instance using mode {@link HttpMultipartMode#STRICT}
*/
public MultipartEntity() {
this(HttpMultipartMode.STRICT, null, null);
}
protected String generateContentType(
final String boundary,
final Charset charset) {
StringBuilder buffer = new StringBuilder();
buffer.append("multipart/form-data; boundary=");
buffer.append(boundary);
if (charset != null) {
buffer.append("; charset=");
buffer.append(charset.name());
}
return buffer.toString();
}
protected String generateBoundary() {
StringBuilder buffer = new StringBuilder();
Random rand = new Random();
int count = rand.nextInt(11) + 30; // a random size from 30 to 40
for (int i = 0; i < count; i++) {
buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
return buffer.toString();
}
public void addPart(final FormBodyPart bodyPart) {
this.multipart.addBodyPart(bodyPart);
this.dirty = true;
}
public void addPart(final String name, final ContentBody contentBody) {
addPart(new FormBodyPart(name, contentBody));
}
public boolean isRepeatable() {
for (FormBodyPart part: this.multipart.getBodyParts()) {
ContentBody body = part.getBody();
if (body.getContentLength() < 0) {
return false;
}
}
return true;
}
public boolean isChunked() {
return !isRepeatable();
}
public boolean isStreaming() {
return !isRepeatable();
}
public long getContentLength() {
if (this.dirty) {
this.length = this.multipart.getTotalLength();
this.dirty = false;
}
return this.length;
}
public Header getContentType() {
return this.contentType;
}
public Header getContentEncoding() {
return null;
}
public void consumeContent()
throws IOException, UnsupportedOperationException{
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException(
"Multipart form entity does not implement #getContent()");
}
public void writeTo(final OutputStream outstream) throws IOException {
this.multipart.writeTo(outstream);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime;
import java.nio.charset.Charset;
/**
*
* @since 4.0
*/
public final class MIME {
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_TRANSFER_ENC = "Content-Transfer-Encoding";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String ENC_8BIT = "8bit";
public static final String ENC_BINARY = "binary";
/** The default character set to be used, i.e. "US-ASCII" */
public static final Charset DEFAULT_CHARSET = Charset.forName("US-ASCII");
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime;
/**
* Minimal MIME field.
*
* @since 4.0
*/
public class MinimalField {
private final String name;
private final String value;
MinimalField(final String name, final String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public String getBody() {
return this.value;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(this.name);
buffer.append(": ");
buffer.append(this.value);
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.entity.mime.content;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* @since 4.0
*/
public interface ContentBody extends ContentDescriptor {
String getFilename();
void writeTo(OutputStream out) 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.mime.content;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class FileBody extends AbstractContentBody {
private final File file;
private final String filename;
private final String charset;
/**
* @since 4.1
*/
public FileBody(final File file,
final String filename,
final String mimeType,
final String charset) {
super(mimeType);
if (file == null) {
throw new IllegalArgumentException("File may not be null");
}
this.file = file;
if (filename != null)
this.filename = filename;
else
this.filename = file.getName();
this.charset = charset;
}
/**
* @since 4.1
*/
public FileBody(final File file,
final String mimeType,
final String charset) {
this(file, null, mimeType, charset);
}
public FileBody(final File file, final String mimeType) {
this(file, mimeType, null);
}
public FileBody(final File file) {
this(file, "application/octet-stream");
}
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream in = new FileInputStream(this.file);
try {
byte[] tmp = new byte[4096];
int l;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} finally {
in.close();
}
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public String getCharset() {
return charset;
}
public long getContentLength() {
return this.file.length();
}
public String getFilename() {
return filename;
}
public File getFile() {
return this.file;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime.content;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class InputStreamBody extends AbstractContentBody {
private final InputStream in;
private final String filename;
public InputStreamBody(final InputStream in, final String mimeType, final String filename) {
super(mimeType);
if (in == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
this.in = in;
this.filename = filename;
}
public InputStreamBody(final InputStream in, final String filename) {
this(in, "application/octet-stream", filename);
}
public InputStream getInputStream() {
return this.in;
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
try {
byte[] tmp = new byte[4096];
int l;
while ((l = this.in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} finally {
this.in.close();
}
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public String getCharset() {
return null;
}
public long getContentLength() {
return -1;
}
public String getFilename() {
return this.filename;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime.content;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
import org.apache.ogt.http.entity.mime.content.AbstractContentBody;
/**
* Body part that is built using a byte array containing a file.
*
* @since 4.1
*/
public class ByteArrayBody extends AbstractContentBody {
/**
* The contents of the file contained in this part.
*/
private final byte[] data;
/**
* The name of the file contained in this part.
*/
private final String filename;
/**
* Creates a new ByteArrayBody.
*
* @param data The contents of the file contained in this part.
* @param mimeType The mime type of the file contained in this part.
* @param filename The name of the file contained in this part.
*/
public ByteArrayBody(final byte[] data, final String mimeType, final String filename) {
super(mimeType);
if (data == null) {
throw new IllegalArgumentException("byte[] may not be null");
}
this.data = data;
this.filename = filename;
}
/**
* Creates a new ByteArrayBody.
*
* @param data The contents of the file contained in this part.
* @param filename The name of the file contained in this part.
*/
public ByteArrayBody(final byte[] data, final String filename) {
this(data, "application/octet-stream", filename);
}
public String getFilename() {
return filename;
}
public void writeTo(final OutputStream out) throws IOException {
out.write(data);
}
public String getCharset() {
return null;
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public long getContentLength() {
return data.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.entity.mime.content;
/**
* Represents common content properties.
*/
public interface ContentDescriptor {
/**
* Returns the body descriptors MIME type.
* @see #getMediaType()
* @see #getSubType()
* @return The MIME type, which has been parsed from the
* content-type definition. Must not be null, but
* "text/plain", if no content-type was specified.
*/
String getMimeType();
/**
* Gets the defaulted MIME media type for this content.
* For example <code>TEXT</code>, <code>IMAGE</code>, <code>MULTIPART</code>
* @see #getMimeType()
* @return the MIME media type when content-type specified,
* otherwise the correct default (<code>TEXT</code>)
*/
String getMediaType();
/**
* Gets the defaulted MIME sub type for this content.
* @see #getMimeType()
* @return the MIME media type when content-type is specified,
* otherwise the correct default (<code>PLAIN</code>)
*/
String getSubType();
/**
* <p>The body descriptors character set, defaulted appropriately for the MIME type.</p>
* <p>
* For <code>TEXT</code> types, this will be defaulted to <code>us-ascii</code>.
* For other types, when the charset parameter is missing this property will be null.
* </p>
* @return Character set, which has been parsed from the
* content-type definition. Not null for <code>TEXT</code> types, when unset will
* be set to default <code>us-ascii</code>. For other types, when unset,
* null will be returned.
*/
String getCharset();
/**
* Returns the body descriptors transfer encoding.
* @return The transfer encoding. Must not be null, but "7bit",
* if no transfer-encoding was specified.
*/
String getTransferEncoding();
/**
* Returns the body descriptors content-length.
* @return Content length, if known, or -1, to indicate the absence of a
* content-length header.
*/
long getContentLength();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime.content;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class StringBody extends AbstractContentBody {
private final byte[] content;
private final Charset charset;
/**
* @since 4.1
*/
public static StringBody create(
final String text,
final String mimeType,
final Charset charset) throws IllegalArgumentException {
try {
return new StringBody(text, mimeType, charset);
} catch (UnsupportedEncodingException ex) {
throw new IllegalArgumentException("Charset " + charset + " is not supported", ex);
}
}
/**
* @since 4.1
*/
public static StringBody create(
final String text, final Charset charset) throws IllegalArgumentException {
return create(text, null, charset);
}
/**
* @since 4.1
*/
public static StringBody create(final String text) throws IllegalArgumentException {
return create(text, null, null);
}
/**
* Create a StringBody from the specified text, mime type and character set.
*
* @param text to be used for the body, not {@code null}
* @param mimeType the mime type, not {@code null}
* @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(
final String text,
final String mimeType,
Charset charset) throws UnsupportedEncodingException {
super(mimeType);
if (text == null) {
throw new IllegalArgumentException("Text may not be null");
}
if (charset == null) {
charset = Charset.forName("US-ASCII");
}
this.content = text.getBytes(charset.name());
this.charset = charset;
}
/**
* Create a StringBody from the specified text and character set.
* The mime type is set to "text/plain".
*
* @param text to be used for the body, not {@code null}
* @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(final String text, final Charset charset) throws UnsupportedEncodingException {
this(text, "text/plain", charset);
}
/**
* Create a StringBody from the specified text.
* The mime type is set to "text/plain".
* The hosts default charset is used.
*
* @param text to be used for the body, not {@code null}
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(final String text) throws UnsupportedEncodingException {
this(text, "text/plain", null);
}
public Reader getReader() {
return new InputStreamReader(
new ByteArrayInputStream(this.content),
this.charset);
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream in = new ByteArrayInputStream(this.content);
byte[] tmp = new byte[4096];
int l;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
}
public String getTransferEncoding() {
return MIME.ENC_8BIT;
}
public String getCharset() {
return this.charset.name();
}
public long getContentLength() {
return this.content.length;
}
public String getFilename() {
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.entity.mime.content;
/**
*
* @since 4.0
*/
public abstract class AbstractContentBody implements ContentBody {
private final String mimeType;
private final String mediaType;
private final String subType;
public AbstractContentBody(final String mimeType) {
super();
if (mimeType == null) {
throw new IllegalArgumentException("MIME type may not be null");
}
this.mimeType = mimeType;
int i = mimeType.indexOf('/');
if (i != -1) {
this.mediaType = mimeType.substring(0, i);
this.subType = mimeType.substring(i + 1);
} else {
this.mediaType = mimeType;
this.subType = null;
}
}
public String getMimeType() {
return this.mimeType;
}
public String getMediaType() {
return this.mediaType;
}
public String getSubType() {
return this.subType;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.mime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.entity.mime.content.ContentBody;
import org.apache.ogt.http.util.ByteArrayBuffer;
/**
* HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
* capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
* the browser compatible modes.
*
* @since 4.0
*/
public class HttpMultipart {
private static ByteArrayBuffer encode(
final Charset charset, final String string) {
ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
bab.append(encoded.array(), encoded.position(), encoded.remaining());
return bab;
}
private static void writeBytes(
final ByteArrayBuffer b, final OutputStream out) throws IOException {
out.write(b.buffer(), 0, b.length());
}
private static void writeBytes(
final String s, final Charset charset, final OutputStream out) throws IOException {
ByteArrayBuffer b = encode(charset, s);
writeBytes(b, out);
}
private static void writeBytes(
final String s, final OutputStream out) throws IOException {
ByteArrayBuffer b = encode(MIME.DEFAULT_CHARSET, s);
writeBytes(b, out);
}
private static void writeField(
final MinimalField field, final OutputStream out) throws IOException {
writeBytes(field.getName(), out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), out);
writeBytes(CR_LF, out);
}
private static void writeField(
final MinimalField field, final Charset charset, final OutputStream out) throws IOException {
writeBytes(field.getName(), charset, out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), charset, out);
writeBytes(CR_LF, out);
}
private static final ByteArrayBuffer FIELD_SEP = encode(MIME.DEFAULT_CHARSET, ": ");
private static final ByteArrayBuffer CR_LF = encode(MIME.DEFAULT_CHARSET, "\r\n");
private static final ByteArrayBuffer TWO_DASHES = encode(MIME.DEFAULT_CHARSET, "--");
private final String subType;
private final Charset charset;
private final String boundary;
private final List<FormBodyPart> parts;
private final HttpMultipartMode mode;
/**
* Creates an instance with the specified settings.
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @param mode the mode to use
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpMultipart(final String subType, final Charset charset, final String boundary, HttpMultipartMode mode) {
super();
if (subType == null) {
throw new IllegalArgumentException("Multipart subtype may not be null");
}
if (boundary == null) {
throw new IllegalArgumentException("Multipart boundary may not be null");
}
this.subType = subType;
this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
this.boundary = boundary;
this.parts = new ArrayList<FormBodyPart>();
this.mode = mode;
}
/**
* Creates an instance with the specified settings.
* Mode is set to {@link HttpMultipartMode#STRICT}
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpMultipart(final String subType, final Charset charset, final String boundary) {
this(subType, charset, boundary, HttpMultipartMode.STRICT);
}
public HttpMultipart(final String subType, final String boundary) {
this(subType, null, boundary);
}
public String getSubType() {
return this.subType;
}
public Charset getCharset() {
return this.charset;
}
public HttpMultipartMode getMode() {
return this.mode;
}
public List<FormBodyPart> getBodyParts() {
return this.parts;
}
public void addBodyPart(final FormBodyPart part) {
if (part == null) {
return;
}
this.parts.add(part);
}
public String getBoundary() {
return this.boundary;
}
private void doWriteTo(
final HttpMultipartMode mode,
final OutputStream out,
boolean writeContent) throws IOException {
ByteArrayBuffer boundary = encode(this.charset, getBoundary());
for (FormBodyPart part: this.parts) {
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(CR_LF, out);
Header header = part.getHeader();
switch (mode) {
case STRICT:
for (MinimalField field: header) {
writeField(field, out);
}
break;
case BROWSER_COMPATIBLE:
// Only write Content-Disposition
// Use content charset
MinimalField cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION);
writeField(cd, this.charset, out);
String filename = part.getBody().getFilename();
if (filename != null) {
MinimalField ct = part.getHeader().getField(MIME.CONTENT_TYPE);
writeField(ct, this.charset, out);
}
break;
}
writeBytes(CR_LF, out);
if (writeContent) {
part.getBody().writeTo(out);
}
writeBytes(CR_LF, out);
}
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(TWO_DASHES, out);
writeBytes(CR_LF, out);
}
/**
* Writes out the content in the multipart/form encoding. This method
* produces slightly different formatting depending on its compatibility
* mode.
*
* @see #getMode()
*/
public void writeTo(final OutputStream out) throws IOException {
doWriteTo(this.mode, out, true);
}
/**
* Determines the total length of the multipart content (content length of
* individual parts plus that of extra elements required to delimit the parts
* from one another). If any of the @{link BodyPart}s contained in this object
* is of a streaming entity of unknown length the total length is also unknown.
* <p/>
* This method buffers only a small amount of data in order to determine the
* total length of the entire entity. The content of individual parts is not
* buffered.
*
* @return total length of the multipart entity if known, <code>-1</code>
* otherwise.
*/
public long getTotalLength() {
long contentLen = 0;
for (FormBodyPart part: this.parts) {
ContentBody body = part.getBody();
long len = body.getContentLength();
if (len >= 0) {
contentLen += len;
} else {
return -1;
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
doWriteTo(this.mode, out, false);
byte[] extra = out.toByteArray();
return contentLen + extra.length;
} catch (IOException ex) {
// Should never happen
return -1;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The header of an entity (see RFC 2045).
*/
public class Header implements Iterable<MinimalField> {
private final List<MinimalField> fields;
private final Map<String, List<MinimalField>> fieldMap;
public Header() {
super();
this.fields = new LinkedList<MinimalField>();
this.fieldMap = new HashMap<String, List<MinimalField>>();
}
public void addField(final MinimalField field) {
if (field == null) {
return;
}
String key = field.getName().toLowerCase(Locale.US);
List<MinimalField> values = this.fieldMap.get(key);
if (values == null) {
values = new LinkedList<MinimalField>();
this.fieldMap.put(key, values);
}
values.add(field);
this.fields.add(field);
}
public List<MinimalField> getFields() {
return new ArrayList<MinimalField>(this.fields);
}
public MinimalField getField(final String name) {
if (name == null) {
return null;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> list = this.fieldMap.get(key);
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
public List<MinimalField> getFields(final String name) {
if (name == null) {
return null;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> list = this.fieldMap.get(key);
if (list == null || list.isEmpty()) {
return Collections.emptyList();
} else {
return new ArrayList<MinimalField>(list);
}
}
public int removeFields(final String name) {
if (name == null) {
return 0;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> removed = fieldMap.remove(key);
if (removed == null || removed.isEmpty()) {
return 0;
}
this.fields.removeAll(removed);
return removed.size();
}
public void setField(final MinimalField field) {
if (field == null) {
return;
}
String key = field.getName().toLowerCase(Locale.US);
List<MinimalField> list = fieldMap.get(key);
if (list == null || list.isEmpty()) {
addField(field);
return;
}
list.clear();
list.add(field);
int firstOccurrence = -1;
int index = 0;
for (Iterator<MinimalField> it = this.fields.iterator(); it.hasNext(); index++) {
MinimalField f = it.next();
if (f.getName().equalsIgnoreCase(field.getName())) {
it.remove();
if (firstOccurrence == -1) {
firstOccurrence = index;
}
}
}
this.fields.add(firstOccurrence, field);
}
public Iterator<MinimalField> iterator() {
return Collections.unmodifiableList(fields).iterator();
}
@Override
public String toString() {
return this.fields.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.entity.mime;
import org.apache.ogt.http.entity.mime.content.ContentBody;
/**
* FormBodyPart class represents a content body that can be used as a part of multipart encoded
* entities. This class automatically populates the header with standard fields based on
* the content description of the enclosed body.
*
* @since 4.0
*/
public class FormBodyPart {
private final String name;
private final Header header;
private final ContentBody body;
public FormBodyPart(final String name, final ContentBody body) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
if (body == null) {
throw new IllegalArgumentException("Body may not be null");
}
this.name = name;
this.body = body;
this.header = new Header();
generateContentDisp(body);
generateContentType(body);
generateTransferEncoding(body);
}
public String getName() {
return this.name;
}
public ContentBody getBody() {
return this.body;
}
public Header getHeader() {
return this.header;
}
public void addField(final String name, final String value) {
if (name == null) {
throw new IllegalArgumentException("Field name may not be null");
}
this.header.addField(new MinimalField(name, value));
}
protected void generateContentDisp(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append("form-data; name=\"");
buffer.append(getName());
buffer.append("\"");
if (body.getFilename() != null) {
buffer.append("; filename=\"");
buffer.append(body.getFilename());
buffer.append("\"");
}
addField(MIME.CONTENT_DISPOSITION, buffer.toString());
}
protected void generateContentType(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append(body.getMimeType()); // MimeType cannot be null
if (body.getCharset() != null) { // charset may legitimately be null
buffer.append("; charset=");
buffer.append(body.getCharset());
}
addField(MIME.CONTENT_TYPE, buffer.toString());
}
protected void generateTransferEncoding(final ContentBody body) {
addField(MIME.CONTENT_TRANSFER_ENC, body.getTransferEncoding()); // TE cannot be 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.entity.mime;
/**
*
* @since 4.0
*/
public enum HttpMultipartMode {
/** RFC 822, RFC 2045, RFC 2046 compliant */
STRICT,
/** browser-compatible mode, i.e. only write Content-Disposition; use content charset */
BROWSER_COMPATIBLE
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.entity.mime;
import java.io.File;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.mime.MultipartEntity;
import org.apache.ogt.http.entity.mime.content.FileBody;
import org.apache.ogt.http.entity.mime.content.StringBody;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A content encoder capable of transferring data directly from a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentEncoder extends ContentEncoder {
/**
* Transfers a portion of entity content from the given file channel
* to the underlying network channel.
*
* @param src the source FileChannel to transfer data from.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
*@throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel src, long position, long count) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* Abstract exception handler intended to deal with potentially recoverable
* I/O exceptions thrown by an I/O reactor.
*
* @since 4.0
*/
public interface IOReactorExceptionHandler {
/**
* This method is expected to examine the I/O exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable I/O exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link IOReactorException} and terminate
*/
boolean handle(IOException ex);
/**
* This method is expected to examine the runtime exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable runtime exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link RuntimeException} and terminate
*/
boolean handle(RuntimeException ex);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session output buffer for non-blocking connections. This interface
* facilitates intermediate buffering of output data streamed out to
* a destination channel and writing data to the buffer from a source, usually
* {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also
* provides methods for writing lines of text.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to flush the content of this buffer to the given
* destination {@link WritableByteChannel}.
*
* @param channel the destination channel.
* @return The number of bytes written, possibly zero.
* @throws IOException in case of an I/O error.
*/
int flush(WritableByteChannel channel)
throws IOException;
/**
* Copies content of the source buffer into this buffer. The capacity of
* the destination will be expanded in order to accommodate the entire
* content of the source buffer.
*
* @param src the source buffer.
*/
void write(ByteBuffer src);
/**
* Reads a sequence of bytes from the source channel into this buffer.
*
* @param src the source channel.
*/
void write(ReadableByteChannel src)
throws IOException;
/**
* Copies content of the source buffer into this buffer as one line of text
* including a line delimiter. The capacity of the destination will be
* expanded in order to accommodate the entire content of the source buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param src the source buffer.
*/
void writeLine(CharArrayBuffer src)
throws CharacterCodingException;
/**
* Copies content of the given string into this buffer as one line of text
* including a line delimiter.
* The capacity of the destination will be expanded in order to accommodate
* the entire string.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the string.
*/
void writeLine(String s)
throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.nio.channels.SelectionKey;
/**
* Type of I/O event notifications I/O sessions can declare interest in.
*
* @since 4.0
*/
public interface EventMask {
/**
* Interest in data input.
*/
public static final int READ = SelectionKey.OP_READ;
/**
* Interest in data output.
*/
public static final int WRITE = SelectionKey.OP_WRITE;
/**
* Interest in data input/output.
*/
public static final int READ_WRITE = READ | WRITE;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
/**
* ListenerEndpoint interface represents an endpoint used by an I/O reactor
* to listen for incoming connection from remote clients.
*
* @since 4.0
*/
public interface ListenerEndpoint {
/**
* Returns the socket address of this endpoint.
*
* @return socket address.
*/
SocketAddress getAddress();
/**
* Returns an instance of {@link IOException} thrown during initialization
* of this endpoint or <code>null</code>, if initialization was successful.
*
* @return I/O exception object or <code>null</code>.
*/
IOException getException();
/**
* Waits for completion of initialization process of this endpoint.
*
* @throws InterruptedException in case the initialization process was
* interrupted.
*/
void waitFor() throws InterruptedException;
/**
* Determines if this endpoint has been closed and is no longer listens
* for incoming connections.
*
* @return <code>true</code> if the endpoint has been closed,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Closes this endpoint. The endpoint will stop accepting incoming
* connection.
*/
void close();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* SessionRequestCallback interface can be used to get notifications of
* completion of session requests asynchronously without having to wait
* for it, blocking the current thread of execution.
*
* @since 4.0
*/
public interface SessionRequestCallback {
/**
* Triggered on successful completion of a {@link SessionRequest}.
* The {@link SessionRequest#getSession()} method can now be used to obtain
* the new I/O session.
*
* @param request session request.
*/
void completed(SessionRequest request);
/**
* Triggered on unsuccessful completion a {@link SessionRequest}.
* The {@link SessionRequest#getException()} method can now be used to
* obtain the cause of the error.
*
* @param request session request.
*/
void failed(SessionRequest request);
/**
* Triggered if a {@link SessionRequest} times out.
*
* @param request session request.
*/
void timeout(SessionRequest request);
/**
* Triggered on cancellation of a {@link SessionRequest}.
*
* @param request session request.
*/
void cancelled(SessionRequest request);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
import java.nio.channels.ByteChannel;
/**
* IOSession interface represents a sequence of logically related data exchanges
* between two end points.
* <p>
* The channel associated with implementations of this interface can be used to
* read data from and write data to the session.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot use
* the context of the thread to store a session's state. All details about
* a particular session must be stored within the session itself, usually
* using execution context associated with it.
* <p>
* Implementations of this interface are expected to be threading safe.
*
* @since 4.0
*/
public interface IOSession {
/**
* Name of the context attribute key, which can be used to obtain the
* session attachment object.
*/
public static final String ATTACHMENT_KEY = "http.session.attachment";
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = Integer.MAX_VALUE;
/**
* Returns the underlying I/O channel associated with this session.
*
* @return the I/O channel.
*/
ByteChannel channel();
/**
* Returns address of the remote peer.
*
* @return socket address.
*/
SocketAddress getRemoteAddress();
/**
* Returns local address.
*
* @return socket address.
*/
SocketAddress getLocalAddress();
/**
* Returns mask of I/O evens this session declared interest in.
*
* @return I/O event mask.
*/
int getEventMask();
/**
* Declares interest in I/O event notifications by setting the event mask
* associated with the session
*
* @param ops new I/O event mask.
*/
void setEventMask(int ops);
/**
* Declares interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void setEvent(int op);
/**
* Clears interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void clearEvent(int op);
/**
* Terminates the session gracefully and closes the underlying I/O channel.
* This method ensures that session termination handshake, such as the one
* used by the SSL/TLS protocol, is correctly carried out.
*/
void close();
/**
* Terminates the session by shutting down the underlying I/O channel.
*/
void shutdown();
/**
* Returns status of the session:
* <p>
* {@link #ACTIVE}: session is active.
* <p>
* {@link #CLOSING}: session is being closed.
* <p>
* {@link #CLOSED}: session has been terminated.
*
* @return session status.
*/
int getStatus();
/**
* Determines if the session has been terminated.
*
* @return <code>true</code> if the session has been terminated,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Returns value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @return socket timeout.
*/
int getSocketTimeout();
/**
* Sets value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @param timeout socket timeout.
*/
void setSocketTimeout(int timeout);
/**
* Quite often I/O sessions need to maintain internal I/O buffers in order
* to transform input / output data prior to returning it to the consumer or
* writing it to the underlying channel. Memory management in HttpCore NIO
* is based on the fundamental principle that the data consumer can read
* only as much input data as it can process without having to allocate more
* memory. That means, quite often some input data may remain unread in one
* of the internal or external session buffers. The I/O reactor can query
* the status of these session buffers, and make sure the consumer gets
* notified correctly as more data gets stored in one of the session
* buffers, thus allowing the consumer to read the remaining data once it
* is able to process it
* <p>
* I/O sessions can be made aware of the status of external session buffers
* using the {@link SessionBufferStatus} interface.
*
* @param status
*/
void setBufferStatus(SessionBufferStatus status);
/**
* Determines if the input buffer associated with the session contains data.
*
* @return <code>true</code> if the session input buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedInput();
/**
* Determines if the output buffer associated with the session contains
* data.
*
* @return <code>true</code> if the session output buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedOutput();
/**
* This method can be used to associate a particular object with the
* session by the given attribute name.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot
* use the context of the thread to store a session's state. All details
* about a particular session must be stored within the session itself.
*
* @param name name of the attribute.
* @param obj value of the attribute.
*/
void setAttribute(String name, Object obj);
/**
* Returns the value of the attribute with the given name. The value can be
* <code>null</code> if not set.
* <p>
* The value of the session attachment object can be obtained using
* {@link #ATTACHMENT_KEY} name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute.
* @return value of the attribute.
*/
Object getAttribute(String name);
/**
* Removes attribute with the given name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute to be removed.
* @return value of the removed attribute.
*/
Object removeAttribute(String name);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session input buffer for non-blocking connections. This interface facilitates
* intermediate buffering of input data streamed from a source channel and
* reading buffered data to a destination, usually {@link ByteBuffer} or
* {@link WritableByteChannel}. This interface also provides methods for reading
* lines of text.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to fill the buffer with data from the given
* {@link ReadableByteChannel}.
*
* @param src the source channel
* @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
* channel has reached end-of-stream.
* @throws IOException in case of an I/O error.
*/
int fill(ReadableByteChannel src) throws IOException;
/**
* Reads one byte from the buffer. If the buffer is empty this method can
* throw a runtime exception. The exact type of runtime exception thrown
* by this method depends on implementation.
*
* @return one byte
*/
int read();
/**
* Reads a sequence of bytes from this buffer into the destination buffer,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer and capacity of the
* destination buffer, but cannot be more than <code>maxLen</code> value.
*
* @param dst the destination buffer.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst, int maxLen);
/**
* Reads a sequence of bytes from this buffer into the destination buffer.
* The exact number of bytes transferred depends on availability of data
* in this buffer and capacity of the destination buffer.
*
* @param dst the destination buffer.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst);
/**
* Reads a sequence of bytes from this buffer into the destination channel,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer, but cannot be more than
* <code>maxLen</code> value.
*
* @param dst the destination channel.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst, int maxLen) throws IOException;
/**
* Reads a sequence of bytes from this buffer into the destination channel.
* The exact number of bytes transferred depends on availability of data in
* this buffer.
*
* @param dst the destination channel.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst) throws IOException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to the destination buffer. If a complete line is
* available in the buffer, the sequence of chars is transferred to the
* destination buffer the method returns <code>true</code>. The line
* delimiter itself is discarded. If a complete line is not available in
* the buffer, this method returns <code>false</code> without transferring
* anything to the destination buffer. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param dst the destination buffer.
* @param endOfStream
* @return <code>true</code> if a sequence of chars representing a complete
* line has been transferred to the destination buffer, <code>false</code>
* otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
boolean readLine(CharArrayBuffer dst, boolean endOfStream)
throws CharacterCodingException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to a newly created string. If a complete line is
* available in the buffer, the sequence of chars is transferred to a newly
* created string. The line delimiter itself is discarded. If a complete
* line is not available in the buffer, this method returns
* <code>null</code>. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param endOfStream
* @return a string representing a complete line, if available.
* <code>null</code> otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
String readLine(boolean endOfStream)
throws CharacterCodingException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
/**
* SessionRequest interface represents a request to establish a new connection
* (or session) to a remote host. It can be used to monitor the status of the
* request, to block waiting for its completion, or to cancel the request.
* <p>
* Implementations of this interface are expected to be threading safe.
*
* @since 4.0
*/
public interface SessionRequest {
/**
* Returns socket address of the remote host.
*
* @return socket address of the remote host
*/
SocketAddress getRemoteAddress();
/**
* Returns local socket address.
*
* @return local socket address.
*/
SocketAddress getLocalAddress();
/**
* Returns attachment object will be added to the session's context upon
* initialization. This object can be used to pass an initial processing
* state to the protocol handler.
*
* @return attachment object.
*/
Object getAttachment();
/**
* Determines whether the request has been completed (either successfully
* or unsuccessfully).
*
* @return <code>true</true> if the request has been completed,
* <code>false</true> if still pending.
*/
boolean isCompleted();
/**
* Returns {@link IOSession} instance created as a result of this request
* or <code>null</code> if the request is still pending.
*
* @return I/O session or <code>null</code> if the request is still pending.
*/
IOSession getSession();
/**
* Returns {@link IOException} instance if the request could not be
* successfully executed due to an I/O error or <code>null</code> if no
* error occurred to this point.
*
* @return I/O exception or <code>null</code> if no error occurred to
* this point.
*/
IOException getException();
/**
* Waits for completion of this session request.
*
* @throws InterruptedException in case the execution process was
* interrupted.
*/
void waitFor() throws InterruptedException;
/**
* Sets connect timeout value in milliseconds.
*
* @param timeout connect timeout value in milliseconds.
*/
void setConnectTimeout(int timeout);
/**
* Returns connect timeout value in milliseconds.
*
* @return connect timeout value in milliseconds.
*/
int getConnectTimeout();
/**
* Cancels the request. Invocation of this method will set the status of
* the request to completed and will unblock threads blocked in
* the {{@link #waitFor()}} method.
*/
void cancel();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* I/O exception that can be thrown by an I/O reactor. Usually exceptions
* of this type are fatal and are not recoverable.
*
* @since 4.0
*/
public class IOReactorException extends IOException {
private static final long serialVersionUID = -4248110651729635749L;
public IOReactorException(final String message, final Exception cause) {
super(message);
if (cause != null) {
initCause(cause);
}
}
public IOReactorException(final String message) {
super(message);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* HttpCore NIO is based on the Reactor pattern as described by Doug Lea.
* The purpose of I/O reactors is to react to I/O events and to dispatch event
* notifications to individual I/O sessions. The main idea of I/O reactor
* pattern is to break away from the one thread per connection model imposed
* by the classic blocking I/O model.
* <p>
* The IOReactor interface represents an abstract object implementing
* the Reactor pattern.
* <p>
* I/O reactors usually employ a small number of dispatch threads (often as
* few as one) to dispatch I/O event notifications to a much greater number
* (often as many as several thousands) of I/O sessions or connections. It is
* generally recommended to have one dispatch thread per CPU core.
*
* @since 4.0
*/
public interface IOReactor {
/**
* Returns the current status of the reactor.
*
* @return reactor status.
*/
IOReactorStatus getStatus();
/**
* Starts the reactor and initiates the dispatch of I/O event notifications
* to the given {@link IOEventDispatch}.
*
* @param eventDispatch the I/O event dispatch.
* @throws IOException in case of an I/O error.
*/
void execute(IOEventDispatch eventDispatch)
throws IOException;
/**
* Initiates shutdown of the reactor and blocks approximately for the given
* period of time in milliseconds waiting for the reactor to terminate all
* active connections, to shut down itself and to release system resources
* it currently holds.
*
* @param waitMs wait time in milliseconds.
* @throws IOException in case of an I/O error.
*/
void shutdown(long waitMs)
throws IOException;
/**
* Initiates shutdown of the reactor and blocks for a default period of
* time waiting for the reactor to terminate all active connections, to shut
* down itself and to release system resources it currently holds. It is
* up to individual implementations to decide for how long this method can
* remain blocked.
*
* @throws IOException in case of an I/O error.
*/
void shutdown()
throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* IOReactorStatus represents an internal status of an I/O reactor.
*
* @since 4.0
*/
public enum IOReactorStatus {
/**
* The reactor is inactive / has not been started
*/
INACTIVE,
/**
* The reactor is active / processing I/O events.
*/
ACTIVE,
/**
* Shutdown of the reactor has been requested.
*/
SHUTDOWN_REQUEST,
/**
* The reactor is shutting down.
*/
SHUTTING_DOWN,
/**
* The reactor has shut down.
*/
SHUT_DOWN;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* IOEventDispatch interface is used by I/O reactors to notify clients of I/O
* events pending for a particular session. All methods of this interface are
* executed on a dispatch thread of the I/O reactor. Therefore, it is important
* that processing that takes place in the event methods will not block the
* dispatch thread for too long, as the I/O reactor will be unable to react to
* other events.
*
* @since 4.0
*/
public interface IOEventDispatch {
/**
* Triggered after the given session has been just created.
*
* @param session the I/O session.
*/
void connected(IOSession session);
/**
* Triggered when the given session has input pending.
*
* @param session the I/O session.
*/
void inputReady(IOSession session);
/**
* Triggered when the given session is ready for output.
*
* @param session the I/O session.
*/
void outputReady(IOSession session);
/**
* Triggered when the given session as timed out.
*
* @param session the I/O session.
*/
void timeout(IOSession session);
/**
* Triggered when the given session has been terminated.
*
* @param session the I/O session.
*/
void disconnected(IOSession session);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
/**
* ConnectingIOReactor represents an I/O reactor capable of establishing
* connections to remote hosts.
*
* @since 4.0
*/
public interface ConnectingIOReactor extends IOReactor {
/**
* Requests a connection to a remote host.
* <p>
* Opening a connection to a remote host usually tends to be a time
* consuming process and may take a while to complete. One can monitor and
* control the process of session initialization by means of the
* {@link SessionRequest} interface.
* <p>
* There are several parameters one can use to exert a greater control over
* the process of session initialization:
* <p>
* A non-null local socket address parameter can be used to bind the socket
* to a specific local address.
* <p>
* An attachment object can added to the new session's context upon
* initialization. This object can be used to pass an initial processing
* state to the protocol handler.
* <p>
* It is often desirable to be able to react to the completion of a session
* request asynchronously without having to wait for it, blocking the
* current thread of execution. One can optionally provide an implementation
* {@link SessionRequestCallback} instance to get notified of events related
* to session requests, such as request completion, cancellation, failure or
* timeout.
*
* @param remoteAddress the socket address of the remote host.
* @param localAddress the local socket address. Can be <code>null</code>,
* in which can the default local address and a random port will be used.
* @param attachment the attachment object. Can be <code>null</code>.
* @param callback interface. Can be <code>null</code>.
* @return session request object.
*/
SessionRequest connect(
SocketAddress remoteAddress,
SocketAddress localAddress,
Object attachment,
SessionRequestCallback callback);
}
| Java |
/*
* $Date:
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* SessionBufferStatus interface is intended to query the status of session
* I/O buffers.
*
* @since 4.0
*/
public interface SessionBufferStatus {
/**
* Determines if the session input buffer contains data.
*
* @return <code>true</code> if the session input buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedInput();
/**
* Determines if the session output buffer contains data.
*
* @return <code>true</code> if the session output buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedOutput();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
import java.util.Set;
import java.io.IOException;
/**
* ListeningIOReactor represents an I/O reactor capable of listening for
* incoming connections on one or several ports.
*
* @since 4.0
*/
public interface ListeningIOReactor extends IOReactor {
/**
* Opens a new listener endpoint with the given socket address. Once
* the endpoint is fully initialized it starts accepting incoming
* connections and propagates I/O activity notifications to the I/O event
* dispatcher.
* <p>
* {@link ListenerEndpoint#waitFor()} can be used to wait for the
* listener to be come ready to accept incoming connections.
* <p>
* {@link ListenerEndpoint#close()} can be used to shut down
* the listener even before it is fully initialized.
*
* @param address the socket address to listen on.
* @return listener endpoint.
*/
ListenerEndpoint listen(SocketAddress address);
/**
* Suspends the I/O reactor preventing it from accepting new connections on
* all active endpoints.
*
* @throws IOException in case of an I/O error.
*/
void pause()
throws IOException;
/**
* Resumes the I/O reactor restoring its ability to accept incoming
* connections on all active endpoints.
*
* @throws IOException in case of an I/O error.
*/
void resume()
throws IOException;
/**
* Returns a set of endpoints for this I/O reactor.
*
* @return set of endpoints.
*/
Set<ListenerEndpoint> getEndpoints();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpProcessor;
/**
* @since 4.0
*/
public abstract class NHttpHandlerBase {
protected static final String CONN_STATE = "http.nio.conn-state";
protected final HttpProcessor httpProcessor;
protected final ConnectionReuseStrategy connStrategy;
protected final ByteBufferAllocator allocator;
protected final HttpParams params;
protected EventListener eventListener;
public NHttpHandlerBase(
final HttpProcessor httpProcessor,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
if (httpProcessor == null) {
throw new IllegalArgumentException("HTTP processor may not be null.");
}
if (connStrategy == null) {
throw new IllegalArgumentException("Connection reuse strategy may not be null");
}
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.httpProcessor = httpProcessor;
this.connStrategy = connStrategy;
this.allocator = allocator;
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setEventListener(final EventListener eventListener) {
this.eventListener = eventListener;
}
protected void closeConnection(final NHttpConnection conn, final Throwable cause) {
try {
// Try to close it nicely
conn.close();
} catch (IOException ex) {
try {
// Just shut the damn thing down
conn.shutdown();
} catch (IOException ignore) {
}
}
}
protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) {
try {
conn.shutdown();
} catch (IOException ignore) {
}
}
protected void handleTimeout(final NHttpConnection conn) {
try {
if (conn.getStatus() == NHttpConnection.ACTIVE) {
conn.close();
if (conn.getStatus() == NHttpConnection.CLOSING) {
// Give the connection some grace time to
// close itself nicely
conn.setSocketTimeout(250);
}
if (this.eventListener != null) {
this.eventListener.connectionTimeout(conn);
}
} else {
conn.shutdown();
}
} catch (IOException ignore) {
}
}
protected boolean canResponseHaveBody(
final HttpRequest request, final HttpResponse response) {
if (request != null && "HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.HttpContext;
/**
* HTTP request execution handler can be used by client-side protocol handlers
* to trigger the submission of a new HTTP request and the processing of an
* HTTP response.
*
*
* @since 4.0
*/
public interface HttpRequestExecutionHandler {
/**
* Triggered when a new connection has been established and the
* HTTP context needs to be initialized.
*
* <p>The attachment object is the same object which was passed
* to the connecting I/O reactor when the connection request was
* made. The attachment may optionally contain some state information
* required in order to correctly initialize the HTTP context.
*
* @see ConnectingIOReactor#connect
*
* @param context the actual HTTP context
* @param attachment the object passed to the connecting I/O reactor
* upon the request for a new connection.
*/
void initalizeContext(HttpContext context, Object attachment);
/**
* Triggered when the underlying connection is ready to send a new
* HTTP request to the target host. This method may return
* <code>null</null> if the client is not yet ready to send a
* request. In this case the connection will remain open and
* can be activated at a later point.
*
* @param context the actual HTTP context
* @return an HTTP request to be sent or <code>null</null> if no
* request needs to be sent
*/
HttpRequest submitRequest(HttpContext context);
/**
* Triggered when an HTTP response is ready to be processed.
*
* @param response the HTTP response to be processed
* @param context the actual HTTP context
*/
void handleResponse(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when the connection is terminated. This event can be used
* to release objects stored in the context or perform some other kind
* of cleanup.
*
* @param context the actual HTTP context
*/
void finalizeContext(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.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.protocol.HttpContext;
/**
* NHttpRequestHandler represents a routine for asynchronous processing of
* a specific group of non-blocking HTTP requests. Protocol handlers are
* designed to take care of protocol specific aspects, whereas individual
* request handlers are expected to take care of application specific HTTP
* processing. The main purpose of a request handler is to generate a response
* object with a content entity to be sent back to the client in response to
* the given request
*
* @since 4.0
*/
public interface NHttpRequestHandler {
/**
* Triggered when a request is received with an entity. This method should
* return a {@link ConsumingNHttpEntity} that will be used to consume the
* entity. <code>null</code> is a valid response value, and will indicate
* that the entity should be silently ignored.
* <p>
* After the entity is fully consumed,
* {@link #handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)}
* is called to notify a full request & entity are ready to be processed.
*
* @param request the entity enclosing request.
* @param context the execution context.
* @return non-blocking HTTP entity.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
ConsumingNHttpEntity entityRequest(HttpEntityEnclosingRequest request,
HttpContext context)
throws HttpException, IOException;
/**
* Initiates processing of the request. This method does not have to submit
* a response immediately. It can defer transmission of the HTTP response
* back to the client without blocking the I/O thread by delegating the
* process of handling the HTTP request to a worker thread. The worker
* thread in its turn can use the instance of {@link NHttpResponseTrigger}
* passed as a parameter to submit a response as at a later point of time
* once content of the response becomes available.
*
* @param request the HTTP request.
* @param response the HTTP response.
* @param trigger the response trigger.
* @param context the HTTP execution context.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation or a processing
* problem.
*/
void handle(HttpRequest request, HttpResponse response,
NHttpResponseTrigger trigger, 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.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpResponseFactory;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandlerResolver;
/**
* @deprecated No longer used.
*
* @since 4.0
*/
@Deprecated
public abstract class NHttpServiceHandlerBase extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected HttpExpectationVerifier expectationVerifier;
protected HttpRequestHandlerResolver handlerResolver;
public NHttpServiceHandlerBase(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
public NHttpServiceHandlerBase(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.NHttpEntityWrapper;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.entity.SkipContentListener;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Fully asynchronous HTTP client side protocol handler that implements the
* essential requirements of the HTTP protocol for the server side message
* processing as described by RFC 2616. It is capable of executing HTTP requests
* with nearly constant memory footprint. Only HTTP message heads are stored in
* memory, while content of message bodies is streamed directly from the entity
* to the underlying channel (and vice versa) using {@link ConsumingNHttpEntity}
* and {@link ProducingNHttpEntity} interfaces.
*
* When using this implementation, it is important to ensure that entities
* supplied for writing implement {@link ProducingNHttpEntity}. Doing so will allow
* the entity to be written out asynchronously. If entities supplied for writing
* do not implement the {@link ProducingNHttpEntity} interface, a delegate is
* added that buffers the entire contents in memory. Additionally, the
* buffering might take place in the I/O dispatch thread, which could cause I/O
* to block temporarily. For best results, one must ensure that all entities
* set on {@link HttpRequest}s from {@link NHttpRequestExecutionHandler}
* implement {@link ProducingNHttpEntity}.
*
* If incoming responses enclose a content entity,
* {@link NHttpRequestExecutionHandler} are expected to return a
* {@link ConsumingNHttpEntity} for reading the content. After the entity is
* finished reading the data,
* {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method is called to process the response.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* </ul>
*
* @see ConsumingNHttpEntity
* @see ProducingNHttpEntity
*
* @since 4.0
*/
public class AsyncNHttpClientHandler extends NHttpHandlerBase
implements NHttpClientHandler {
protected NHttpRequestExecutionHandler execHandler;
public AsyncNHttpClientHandler(
final HttpProcessor httpProcessor,
final NHttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
this.execHandler = execHandler;
}
public AsyncNHttpClientHandler(
final HttpProcessor httpProcessor,
final NHttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
HttpContext context = conn.getContext();
initialize(conn, attachment);
ClientConnState connState = new ClientConnState();
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
requestReady(conn);
}
public void closed(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
connState.reset();
} catch (IOException ex) {
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
this.execHandler.finalizeContext(context);
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void requestReady(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
if (connState.getOutputState() != ClientConnState.READY) {
return;
}
try {
HttpRequest request = this.execHandler.submitRequest(context);
if (request == null) {
return;
}
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(request, context);
HttpEntityEnclosingRequest entityReq = null;
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest) {
entityReq = (HttpEntityEnclosingRequest) request;
entity = entityReq.getEntity();
}
if (entity instanceof ProducingNHttpEntity) {
connState.setProducingEntity((ProducingNHttpEntity) entity);
} else if (entity != null) {
connState.setProducingEntity(new NHttpEntityWrapper(entity));
}
connState.setRequest(request);
conn.submitRequest(request);
connState.setOutputState(ClientConnState.REQUEST_SENT);
if (entityReq != null && entityReq.expectContinue()) {
int timeout = conn.getSocketTimeout();
connState.setTimeout(timeout);
timeout = this.params.getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
conn.setSocketTimeout(timeout);
connState.setOutputState(ClientConnState.EXPECT_CONTINUE);
} else if (connState.getProducingEntity() != null) {
connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity();
try {
consumingEntity.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
processResponse(conn, connState);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
conn.suspendOutput();
return;
}
ProducingNHttpEntity entity = connState.getProducingEntity();
entity.produceContent(encoder, conn);
if (encoder.isCompleted()) {
connState.setOutputState(ClientConnState.REQUEST_BODY_DONE);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
HttpResponse response = conn.getHttpResponse();
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
HttpRequest request = connState.getRequest();
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
continueRequest(conn, connState);
}
return;
} else {
connState.setResponse(response);
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
cancelRequest(conn, connState);
} else if (connState.getOutputState() == ClientConnState.REQUEST_BODY_STREAM) {
// Early response
cancelRequest(conn, connState);
connState.invalidate();
conn.suspendOutput();
}
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
response.setEntity(null);
this.httpProcessor.process(response, context);
processResponse(conn, connState);
} else {
HttpEntity entity = response.getEntity();
if (entity != null) {
ConsumingNHttpEntity consumingEntity = this.execHandler.responseEntity(
response, context);
if (consumingEntity == null) {
consumingEntity = new ConsumingNHttpEntityTemplate(
entity, new SkipContentListener(this.allocator));
}
response.setEntity(consumingEntity);
connState.setConsumingEntity(consumingEntity);
this.httpProcessor.process(response, context);
}
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void timeout(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
continueRequest(conn, connState);
return;
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
handleTimeout(conn);
}
private void initialize(
final NHttpClientConnection conn,
final Object attachment) {
HttpContext context = conn.getContext();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.execHandler.initalizeContext(context, attachment);
}
/**
* @throws IOException - not thrown currently
*/
private void continueRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.requestOutput();
connState.setOutputState(ClientConnState.REQUEST_BODY_STREAM);
}
private void cancelRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
connState.resetOutput();
}
/**
* @throws HttpException - not thrown currently
*/
private void processResponse(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException, HttpException {
if (!connState.isValid()) {
conn.close();
}
HttpContext context = conn.getContext();
HttpResponse response = connState.getResponse();
this.execHandler.handleResponse(response, context);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
if (conn.isOpen()) {
// Ready for another request
connState.resetInput();
connState.resetOutput();
conn.requestOutput();
}
}
protected static class ClientConnState {
public static final int READY = 0;
public static final int REQUEST_SENT = 1;
public static final int EXPECT_CONTINUE = 2;
public static final int REQUEST_BODY_STREAM = 4;
public static final int REQUEST_BODY_DONE = 8;
public static final int RESPONSE_RECEIVED = 16;
public static final int RESPONSE_BODY_STREAM = 32;
public static final int RESPONSE_BODY_DONE = 64;
private int outputState;
private HttpRequest request;
private HttpResponse response;
private ConsumingNHttpEntity consumingEntity;
private ProducingNHttpEntity producingEntity;
private boolean valid;
private int timeout;
public ClientConnState() {
super();
this.valid = true;
}
public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) {
this.consumingEntity = consumingEntity;
}
public void setProducingEntity(final ProducingNHttpEntity producingEntity) {
this.producingEntity = producingEntity;
}
public ProducingNHttpEntity getProducingEntity() {
return producingEntity;
}
public ConsumingNHttpEntity getConsumingEntity() {
return consumingEntity;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void resetInput() throws IOException {
this.response = null;
if (this.consumingEntity != null) {
this.consumingEntity.finish();
this.consumingEntity = null;
}
}
public void resetOutput() throws IOException {
this.request = null;
if (this.producingEntity != null) {
this.producingEntity.finish();
this.producingEntity = null;
}
this.outputState = READY;
}
public void reset() throws IOException {
resetInput();
resetOutput();
}
public boolean isValid() {
return this.valid;
}
public void invalidate() {
this.valid = false;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Client protocol handler implementation that provides compatibility with the
* blocking I/O by storing the full content of HTTP messages in memory.
* The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method will fire only when the entire message content has been read into a
* in-memory buffer. Please note that request execution / response processing
* take place the main I/O thread and therefore
* {@link HttpRequestExecutionHandler} methods should not block indefinitely.
* <p>
* When using this protocol handler {@link HttpEntity}'s content can be
* generated / consumed using standard {@link InputStream}/{@link OutputStream}
* classes.
* <p>
* IMPORTANT: This protocol handler should be used only when dealing with HTTP
* messages that are known to be limited in length.
*
*
* @since 4.0
*/
public class BufferingHttpClientHandler implements NHttpClientHandler {
private final AsyncNHttpClientHandler asyncHandler;
public BufferingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
this.asyncHandler = new AsyncNHttpClientHandler(
httpProcessor,
new ExecutionHandlerAdaptor(execHandler),
connStrategy,
allocator,
params);
}
public BufferingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setEventListener(final EventListener eventListener) {
this.asyncHandler.setEventListener(eventListener);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
this.asyncHandler.connected(conn, attachment);
}
public void closed(final NHttpClientConnection conn) {
this.asyncHandler.closed(conn);
}
public void requestReady(final NHttpClientConnection conn) {
this.asyncHandler.requestReady(conn);
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
this.asyncHandler.inputReady(conn, decoder);
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
this.asyncHandler.outputReady(conn, encoder);
}
public void responseReceived(final NHttpClientConnection conn) {
this.asyncHandler.responseReceived(conn);
}
public void exception(final NHttpClientConnection conn, final HttpException httpex) {
this.asyncHandler.exception(conn, httpex);
}
public void exception(final NHttpClientConnection conn, final IOException ioex) {
this.asyncHandler.exception(conn, ioex);
}
public void timeout(final NHttpClientConnection conn) {
this.asyncHandler.timeout(conn);
}
static class ExecutionHandlerAdaptor implements NHttpRequestExecutionHandler {
private final HttpRequestExecutionHandler execHandler;
public ExecutionHandlerAdaptor(final HttpRequestExecutionHandler execHandler) {
super();
this.execHandler = execHandler;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
this.execHandler.initalizeContext(context, attachment);
}
public void finalizeContext(final HttpContext context) {
this.execHandler.finalizeContext(context);
}
public HttpRequest submitRequest(final HttpContext context) {
return this.execHandler.submitRequest(context);
}
public ConsumingNHttpEntity responseEntity(
final HttpResponse response,
final HttpContext context) throws IOException {
return new BufferingNHttpEntity(
response.getEntity(),
new HeapByteBufferAllocator());
}
public void handleResponse(
final HttpResponse response,
final HttpContext context) throws IOException {
this.execHandler.handleResponse(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.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpConnection;
/**
* Event listener used by the HTTP protocol layer to report fatal exceptions
* and events that may need to be logged using a logging toolkit.
*
* @since 4.0
*/
public interface EventListener {
/**
* Triggered when an I/O error caused a connection to be terminated.
*
* @param ex the I/O exception.
* @param conn the connection.
*/
void fatalIOException(IOException ex, NHttpConnection conn);
/**
* Triggered when an HTTP protocol error caused a connection to be
* terminated.
*
* @param ex the protocol exception.
* @param conn the connection.
*/
void fatalProtocolException(HttpException ex, NHttpConnection conn);
/**
* Triggered when a new connection has been established.
*
* @param conn the connection.
*/
void connectionOpen(NHttpConnection conn);
/**
* Triggered when a connection has been terminated.
*
* @param conn the connection.
*/
void connectionClosed(NHttpConnection conn);
/**
* Triggered when a connection has timed out.
*
* @param conn the connection.
*/
void connectionTimeout(NHttpConnection conn);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Executor;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.ProtocolVersion;
import org.apache.http.ProtocolException;
import org.apache.http.UnsupportedHttpVersionException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.ContentBufferEntity;
import org.apache.http.nio.entity.ContentOutputStream;
import org.apache.http.nio.params.NIOReactorPNames;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ContentInputBuffer;
import org.apache.http.nio.util.ContentOutputBuffer;
import org.apache.http.nio.util.DirectByteBufferAllocator;
import org.apache.http.nio.util.SharedInputBuffer;
import org.apache.http.nio.util.SharedOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
/**
* Service protocol handler implementation that provide compatibility with
* the blocking I/O by utilizing shared content buffers and a fairly small pool
* of worker threads. The throttling protocol handler allocates input / output
* buffers of a constant length upon initialization and controls the rate of
* I/O events in order to ensure those content buffers do not ever get
* overflown. This helps ensure nearly constant memory footprint for HTTP
* connections and avoid the out of memory condition while streaming content
* in and out. The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method will fire immediately when a message is received. The protocol handler
* delegate the task of processing requests and generating response content to
* an {@link Executor}, which is expected to perform those tasks using
* dedicated worker threads in order to avoid blocking the I/O thread.
* <p/>
* Usually throttling protocol handlers need only a modest number of worker
* threads, much fewer than the number of concurrent connections. If the length
* of the message is smaller or about the size of the shared content buffer
* worker thread will just store content in the buffer and terminate almost
* immediately without blocking. The I/O dispatch thread in its turn will take
* care of sending out the buffered content asynchronously. The worker thread
* will have to block only when processing large messages and the shared buffer
* fills up. It is generally advisable to allocate shared buffers of a size of
* an average content body for optimal performance.
*
* @see NIOReactorPNames#CONTENT_BUFFER_SIZE
*
*
* @since 4.0
*/
public class ThrottlingHttpServiceHandler extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected final Executor executor;
protected HttpRequestHandlerResolver handlerResolver;
protected HttpExpectationVerifier expectationVerifier;
public ThrottlingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final Executor executor,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
if (executor == null) {
throw new IllegalArgumentException("Executor may not be null");
}
this.responseFactory = responseFactory;
this.executor = executor;
}
public ThrottlingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final Executor executor,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new DirectByteBufferAllocator(), executor, params);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void connected(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
int bufsize = this.params.getIntParameter(
NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480);
ServerConnState connState = new ServerConnState(bufsize, conn, allocator);
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
}
public void closed(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
if (connState != null) {
synchronized (connState) {
connState.close();
connState.notifyAll();
}
}
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
if (conn.isResponseSubmitted()) {
if (eventListener != null) {
eventListener.fatalProtocolException(httpex, conn);
}
return;
}
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
response.setEntity(null);
this.httpProcessor.process(response, context);
synchronized (connState) {
connState.setResponse(response);
// Response is ready to be committed
conn.requestOutput();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
public void requestReceived(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
final HttpRequest request = conn.getHttpRequest();
final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
synchronized (connState) {
boolean contentExpected = false;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
contentExpected = true;
}
}
if (!contentExpected) {
conn.suspendInput();
}
this.executor.execute(new Runnable() {
public void run() {
try {
handleRequest(request, connState, conn);
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
});
connState.notifyAll();
}
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
ContentInputBuffer buffer = connState.getInbuffer();
buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
connState.setInputState(ServerConnState.REQUEST_BODY_DONE);
} else {
connState.setInputState(ServerConnState.REQUEST_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.isExpectationFailed()) {
// Server expection failed
// Well-behaved client will not be sending
// a request body
conn.resetInput();
connState.setExpectationFailed(false);
}
HttpResponse response = connState.getResponse();
if (connState.getOutputState() == ServerConnState.READY
&& response != null
&& !conn.isResponseSubmitted()) {
conn.submitResponse(response);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (statusCode >= 200 && entity == null) {
connState.setOutputState(ServerConnState.RESPONSE_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setOutputState(ServerConnState.RESPONSE_SENT);
}
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = connState.getResponse();
ContentOutputBuffer buffer = connState.getOutbuffer();
buffer.produceContent(encoder);
if (encoder.isCompleted()) {
connState.setOutputState(ServerConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setOutputState(ServerConnState.RESPONSE_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
private 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);
}
private void handleRequest(
final HttpRequest request,
final ServerConnState connState,
final NHttpServerConnection conn) throws HttpException, IOException {
HttpContext context = conn.getContext();
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.READY) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setInputState(ServerConnState.REQUEST_RECEIVED);
connState.setRequest(request);
}
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
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;
}
HttpResponse response = null;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request;
if (eeRequest.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);
}
}
synchronized (connState) {
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
connState.setResponse(response);
conn.requestOutput();
// Block until 1xx response is sent to the client
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.RESPONSE_SENT) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.resetOutput();
response = null;
} else {
// Discard request entity
eeRequest.setEntity(null);
conn.suspendInput();
connState.setExpectationFailed(true);
}
}
}
// Create a wrapper entity instead of the original one
if (eeRequest.getEntity() != null) {
eeRequest.setEntity(new ContentBufferEntity(
eeRequest.getEntity(),
connState.getInbuffer()));
}
}
if (response == null) {
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_OK,
context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
try {
this.httpProcessor.process(request, context);
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);
}
} 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 (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest eeRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = eeRequest.getEntity();
EntityUtils.consume(entity);
}
// It should be safe to reset the input state at this point
connState.resetInput();
this.httpProcessor.process(response, context);
if (!canResponseHaveBody(request, response)) {
response.setEntity(null);
}
connState.setResponse(response);
// Response is ready to be committed
conn.requestOutput();
if (response.getEntity() != null) {
ContentOutputBuffer buffer = connState.getOutbuffer();
OutputStream outstream = new ContentOutputStream(buffer);
HttpEntity entity = response.getEntity();
entity.writeTo(outstream);
outstream.flush();
outstream.close();
}
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (currentState == ServerConnState.RESPONSE_DONE) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.resetOutput();
conn.requestInput();
connState.notifyAll();
}
}
@Override
protected void shutdownConnection(final NHttpConnection conn, final Throwable cause) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
super.shutdownConnection(conn, cause);
if (connState != null) {
connState.shutdown();
}
}
static class ServerConnState {
public static final int SHUTDOWN = -1;
public static final int READY = 0;
public static final int REQUEST_RECEIVED = 1;
public static final int REQUEST_BODY_STREAM = 2;
public static final int REQUEST_BODY_DONE = 4;
public static final int RESPONSE_SENT = 8;
public static final int RESPONSE_BODY_STREAM = 16;
public static final int RESPONSE_BODY_DONE = 32;
public static final int RESPONSE_DONE = 32;
private final SharedInputBuffer inbuffer;
private final SharedOutputBuffer outbuffer;
private volatile int inputState;
private volatile int outputState;
private volatile HttpRequest request;
private volatile HttpResponse response;
private volatile boolean expectationFailure;
public ServerConnState(
int bufsize,
final IOControl ioControl,
final ByteBufferAllocator allocator) {
super();
this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator);
this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator);
this.inputState = READY;
this.outputState = READY;
}
public ContentInputBuffer getInbuffer() {
return this.inbuffer;
}
public ContentOutputBuffer getOutbuffer() {
return this.outbuffer;
}
public int getInputState() {
return this.inputState;
}
public void setInputState(int inputState) {
this.inputState = inputState;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public boolean isExpectationFailed() {
return expectationFailure;
}
public void setExpectationFailed(boolean b) {
this.expectationFailure = b;
}
public void close() {
this.inbuffer.close();
this.outbuffer.close();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void shutdown() {
this.inbuffer.shutdown();
this.outbuffer.shutdown();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void resetInput() {
this.inbuffer.reset();
this.request = null;
this.inputState = READY;
}
public void resetOutput() {
this.outbuffer.reset();
this.response = null;
this.outputState = READY;
this.expectationFailure = false;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpProcessor;
/**
* @deprecated No longer used.
*
* @since 4.0
*/
@Deprecated
public abstract class NHttpClientHandlerBase extends NHttpHandlerBase
implements NHttpClientHandler {
protected HttpRequestExecutionHandler execHandler;
public NHttpClientHandlerBase(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
this.execHandler = execHandler;
}
public void closed(final NHttpClientConnection conn) {
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
/**
* Callback interface to submit HTTP responses asynchronously.
* <p/>
* The {@link NHttpRequestHandler#handle(org.apache.http.HttpRequest, HttpResponse, NHttpResponseTrigger, org.apache.http.protocol.HttpContext)}
* method does not have to submit a response immediately. It can defer
* transmission of the HTTP response back to the client without blocking the
* I/O thread by delegating the process of handling the HTTP request to a worker
* thread. The worker thread in its turn can use the instance of
* {@link NHttpResponseTrigger} passed as a parameter to submit a response as at
* a later point of time once the response becomes available.
*
* @since 4.0
*/
public interface NHttpResponseTrigger {
/**
* Submits a response to be sent back to the client as a result of
* processing of the request.
*/
void submitResponse(HttpResponse response);
/**
* Reports a protocol exception thrown while processing the request.
*/
void handleException(HttpException ex);
/**
* Report an IOException thrown while processing the request.
*/
void handleException(IOException ex);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.util.Map;
import org.apache.http.protocol.UriPatternMatcher;
/**
* 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 NHttpRequestHandler} 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 NHttpRequestHandlerRegistry implements NHttpRequestHandlerResolver {
private final UriPatternMatcher matcher;
public NHttpRequestHandlerRegistry() {
matcher = new UriPatternMatcher();
}
/**
* Registers the given {@link NHttpRequestHandler} 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 NHttpRequestHandler handler) {
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<String, ? extends NHttpRequestHandler> map) {
matcher.setObjects(map);
}
public NHttpRequestHandler lookup(String requestURI) {
return (NHttpRequestHandler) matcher.lookup(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.http.nio.protocol;
import java.io.IOException;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.ProtocolException;
import org.apache.http.ProtocolVersion;
import org.apache.http.UnsupportedHttpVersionException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntityTemplate;
import org.apache.http.nio.entity.NByteArrayEntity;
import org.apache.http.nio.entity.NHttpEntityWrapper;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.entity.SkipContentListener;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.util.EncodingUtils;
/**
* Fully asynchronous HTTP server side protocol handler implementation that
* implements the essential requirements of the HTTP protocol for the server
* side message processing as described by RFC 2616. It is capable of processing
* HTTP requests with nearly constant memory footprint. Only HTTP message heads
* are stored in memory, while content of message bodies is streamed directly
* from the entity to the underlying channel (and vice versa)
* {@link ConsumingNHttpEntity} and {@link ProducingNHttpEntity} interfaces.
* <p/>
* When using this class, it is important to ensure that entities supplied for
* writing implement {@link ProducingNHttpEntity}. Doing so will allow the
* entity to be written out asynchronously. If entities supplied for writing do
* not implement {@link ProducingNHttpEntity}, a delegate is added that buffers
* the entire contents in memory. Additionally, the buffering might take place
* in the I/O thread, which could cause I/O to block temporarily. For best
* results, ensure that all entities set on {@link HttpResponse}s from
* {@link NHttpRequestHandler}s implement {@link ProducingNHttpEntity}.
* <p/>
* If incoming requests enclose a content entity, {@link NHttpRequestHandler}s
* are expected to return a {@link ConsumingNHttpEntity} for reading the
* content. After the entity is finished reading the data,
* {@link NHttpRequestHandler#handle(HttpRequest, HttpResponse, NHttpResponseTrigger, HttpContext)}
* is called to generate a response.
* <p/>
* Individual {@link NHttpRequestHandler}s do not have to submit a response
* immediately. They can defer transmission of the HTTP response back to the
* client without blocking the I/O thread and to delegate the processing the
* HTTP request to a worker thread. The worker thread in its turn can use an
* instance of {@link NHttpResponseTrigger} passed as a parameter to submit
* a response as at a later point of time once the response becomes available.
*
* @see ConsumingNHttpEntity
* @see ProducingNHttpEntity
*
* @since 4.0
*/
public class AsyncNHttpServiceHandler extends NHttpHandlerBase
implements NHttpServiceHandler {
protected final HttpResponseFactory responseFactory;
protected NHttpRequestHandlerResolver handlerResolver;
protected HttpExpectationVerifier expectationVerifier;
public AsyncNHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
}
public AsyncNHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
public void setHandlerResolver(final NHttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void connected(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = new ServerConnState();
context.setAttribute(CONN_STATE, connState);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
}
public void requestReceived(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpRequest request = conn.getHttpRequest();
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
connState.setRequest(request);
NHttpRequestHandler requestHandler = getRequestHandler(request);
connState.setRequestHandler(requestHandler);
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;
}
HttpResponse response;
try {
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
if (entityRequest.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.submitResponse(response);
} else {
conn.resetInput();
sendResponse(conn, request, response);
}
}
// Request content is expected.
ConsumingNHttpEntity consumingEntity = null;
// Lookup request handler for this request
if (requestHandler != null) {
consumingEntity = requestHandler.entityRequest(entityRequest, context);
}
if (consumingEntity == null) {
consumingEntity = new ConsumingNHttpEntityTemplate(
entityRequest.getEntity(),
new SkipContentListener(this.allocator));
}
entityRequest.setEntity(consumingEntity);
connState.setConsumingEntity(consumingEntity);
} else {
// No request content is expected.
// Process request right away
conn.suspendInput();
processRequest(conn, request);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void closed(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
try {
connState.reset();
} catch (IOException ex) {
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
if (conn.isResponseSubmitted()) {
// There is not much that we can do if a response head
// has already been submitted
closeConnection(conn, httpex);
if (eventListener != null) {
eventListener.fatalProtocolException(httpex, conn);
}
return;
}
HttpContext context = conn.getContext();
try {
HttpResponse response = this.responseFactory.newHttpResponse(
HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
response.setEntity(null);
sendResponse(conn, null, response);
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void exception(final NHttpServerConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void timeout(final NHttpServerConnection conn) {
handleTimeout(conn);
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpRequest request = connState.getRequest();
ConsumingNHttpEntity consumingEntity = connState.getConsumingEntity();
try {
consumingEntity.consumeContent(decoder, conn);
if (decoder.isCompleted()) {
conn.suspendInput();
processRequest(conn, request);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void responseReady(final NHttpServerConnection conn) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
if (connState.isHandled()) {
return;
}
HttpRequest request = connState.getRequest();
try {
IOException ioex = connState.getIOException();
if (ioex != null) {
throw ioex;
}
HttpException httpex = connState.getHttpException();
if (httpex != null) {
HttpResponse response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handleException(httpex, response);
connState.setResponse(response);
}
HttpResponse response = connState.getResponse();
if (response != null) {
connState.setHandled(true);
sendResponse(conn, request, response);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
HttpResponse response = conn.getHttpResponse();
try {
ProducingNHttpEntity entity = connState.getProducingEntity();
entity.produceContent(encoder, conn);
if (encoder.isCompleted()) {
connState.finishOutput();
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
} else {
// Ready to process new request
connState.reset();
conn.requestInput();
}
responseComplete(response, context);
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
private void handleException(final HttpException ex, final HttpResponse response) {
int code = HttpStatus.SC_INTERNAL_SERVER_ERROR;
if (ex instanceof MethodNotSupportedException) {
code = HttpStatus.SC_NOT_IMPLEMENTED;
} else if (ex instanceof UnsupportedHttpVersionException) {
code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED;
} else if (ex instanceof ProtocolException) {
code = HttpStatus.SC_BAD_REQUEST;
}
response.setStatusCode(code);
byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
NByteArrayEntity entity = new NByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
/**
* @throws HttpException - not thrown currently
*/
private void processRequest(
final NHttpServerConnection conn,
final HttpRequest request) throws IOException, HttpException {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
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;
}
NHttpResponseTrigger trigger = new ResponseTriggerImpl(connState, conn);
try {
this.httpProcessor.process(request, context);
NHttpRequestHandler handler = connState.getRequestHandler();
if (handler != null) {
HttpResponse response = this.responseFactory.newHttpResponse(
ver, HttpStatus.SC_OK, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
handler.handle(
request,
response,
trigger,
context);
} else {
HttpResponse response = this.responseFactory.newHttpResponse(ver,
HttpStatus.SC_NOT_IMPLEMENTED, context);
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
trigger.submitResponse(response);
}
} catch (HttpException ex) {
trigger.handleException(ex);
}
}
private void sendResponse(
final NHttpServerConnection conn,
final HttpRequest request,
final HttpResponse response) throws IOException, HttpException {
HttpContext context = conn.getContext();
ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
// Now that a response is ready, we can cleanup the listener for the request.
connState.finishInput();
// Some processers need the request that generated this response.
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(response, context);
context.setAttribute(ExecutionContext.HTTP_REQUEST, null);
if (response.getEntity() != null && !canResponseHaveBody(request, response)) {
response.setEntity(null);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (entity instanceof ProducingNHttpEntity) {
connState.setProducingEntity((ProducingNHttpEntity) entity);
} else {
connState.setProducingEntity(new NHttpEntityWrapper(entity));
}
}
conn.submitResponse(response);
if (entity == null) {
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
} else {
// Ready to process new request
connState.reset();
conn.requestInput();
}
responseComplete(response, context);
}
}
/**
* Signals that this response has been fully sent. This will be called after
* submitting the response to a connection, if there is no entity in the
* response. If there is an entity, it will be called after the entity has
* completed.
*/
protected void responseComplete(HttpResponse response, HttpContext context) {
}
private NHttpRequestHandler getRequestHandler(HttpRequest request) {
NHttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
return handler;
}
protected static class ServerConnState {
private volatile NHttpRequestHandler requestHandler;
private volatile HttpRequest request;
private volatile ConsumingNHttpEntity consumingEntity;
private volatile HttpResponse response;
private volatile ProducingNHttpEntity producingEntity;
private volatile IOException ioex;
private volatile HttpException httpex;
private volatile boolean handled;
public void finishInput() throws IOException {
if (this.consumingEntity != null) {
this.consumingEntity.finish();
this.consumingEntity = null;
}
}
public void finishOutput() throws IOException {
if (this.producingEntity != null) {
this.producingEntity.finish();
this.producingEntity = null;
}
}
public void reset() throws IOException {
finishInput();
this.request = null;
finishOutput();
this.handled = false;
this.response = null;
this.ioex = null;
this.httpex = null;
this.requestHandler = null;
}
public NHttpRequestHandler getRequestHandler() {
return this.requestHandler;
}
public void setRequestHandler(final NHttpRequestHandler requestHandler) {
this.requestHandler = requestHandler;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public ConsumingNHttpEntity getConsumingEntity() {
return this.consumingEntity;
}
public void setConsumingEntity(final ConsumingNHttpEntity consumingEntity) {
this.consumingEntity = consumingEntity;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public ProducingNHttpEntity getProducingEntity() {
return this.producingEntity;
}
public void setProducingEntity(final ProducingNHttpEntity producingEntity) {
this.producingEntity = producingEntity;
}
public IOException getIOException() {
return this.ioex;
}
@Deprecated
public IOException getIOExepction() {
return this.ioex;
}
public void setIOException(final IOException ex) {
this.ioex = ex;
}
@Deprecated
public void setIOExepction(final IOException ex) {
this.ioex = ex;
}
public HttpException getHttpException() {
return this.httpex;
}
@Deprecated
public HttpException getHttpExepction() {
return this.httpex;
}
public void setHttpException(final HttpException ex) {
this.httpex = ex;
}
@Deprecated
public void setHttpExepction(final HttpException ex) {
this.httpex = ex;
}
public boolean isHandled() {
return this.handled;
}
public void setHandled(boolean handled) {
this.handled = handled;
}
}
private static class ResponseTriggerImpl implements NHttpResponseTrigger {
private final ServerConnState connState;
private final IOControl iocontrol;
private volatile boolean triggered;
public ResponseTriggerImpl(final ServerConnState connState, final IOControl iocontrol) {
super();
this.connState = connState;
this.iocontrol = iocontrol;
}
public void submitResponse(final HttpResponse response) {
if (response == null) {
throw new IllegalArgumentException("Response may not be null");
}
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setResponse(response);
this.iocontrol.requestOutput();
}
public void handleException(final HttpException ex) {
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setHttpException(ex);
this.iocontrol.requestOutput();
}
public void handleException(final IOException ex) {
if (this.triggered) {
throw new IllegalStateException("Response already triggered");
}
this.triggered = true;
this.connState.setIOException(ex);
this.iocontrol.requestOutput();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.ProducingNHttpEntity;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.protocol.HttpContext;
/**
* HTTP request execution handler can be used by client-side protocol handlers
* to trigger the submission of a new HTTP request and the processing of an HTTP
* response. When a new response entity is available for consumption,
* {@link #responseEntity(HttpResponse, HttpContext)} is called.
* After the {@link ConsumingNHttpEntity} consumes the response body,
* {@link #handleResponse(HttpResponse, HttpContext)} is notified that the
* response is fully read.
*
*
* @since 4.0
*/
public interface NHttpRequestExecutionHandler {
/**
* Triggered when a new connection has been established and the
* HTTP context needs to be initialized.
*
* <p>The attachment object is the same object which was passed
* to the connecting I/O reactor when the connection request was
* made. The attachment may optionally contain some state information
* required in order to correctly initalize the HTTP context.
*
* @see ConnectingIOReactor#connect
*
* @param context the actual HTTP context
* @param attachment the object passed to the connecting I/O reactor
* upon the request for a new connection.
*/
void initalizeContext(HttpContext context, Object attachment);
/**
* Triggered when the underlying connection is ready to send a new
* HTTP request to the target host. This method may return
* <code>null</null> if the client is not yet ready to send a
* request. In this case the connection will remain open and
* can be activated at a later point.
* <p>
* If the request has an entity, the entity <b>must</b> be an
* instance of {@link ProducingNHttpEntity}.
*
* @param context the actual HTTP context
* @return an HTTP request to be sent or <code>null</null> if no
* request needs to be sent
*/
HttpRequest submitRequest(HttpContext context);
/**
* Triggered when a response is received with an entity. This method should
* return a {@link ConsumingNHttpEntity} that will be used to consume the
* entity. <code>null</code> is a valid response value, and will indicate
* that the entity should be silently ignored.
* <p>
* After the entity is fully consumed,
* {@link NHttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* is called to notify a full response & entity are ready to be processed.
*
* @param response
* The response containing the existing entity.
* @param context
* the actual HTTP context
* @return An entity that will asynchronously consume the response's content
* body.
*/
ConsumingNHttpEntity responseEntity(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when an HTTP response is ready to be processed.
*
* @param response
* the HTTP response to be processed
* @param context
* the actual HTTP context
*/
void handleResponse(HttpResponse response, HttpContext context)
throws IOException;
/**
* Triggered when the connection is terminated. This event can be used
* to release objects stored in the context or perform some other kind
* of cleanup.
*
* @param context the actual HTTP context
*/
void finalizeContext(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.http.nio.protocol;
/**
* HttpRequestHandlerResolver can be used to resolve an instance of
* {@link NHttpRequestHandler} matching a particular request URI. Usually the
* resolved request handler will be used to process the request with the
* specified request URI.
*
* @since 4.0
*/
public interface NHttpRequestHandlerResolver {
/**
* Looks up a handler matching the given request URI.
*
* @param requestURI the request URI
* @return HTTP request handler or <code>null</code> if no match
* is found.
*/
NHttpRequestHandler lookup(String 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.http.nio.protocol;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* A simple implementation of {@link NHttpRequestHandler} that abstracts away
* the need to use {@link NHttpResponseTrigger}. Implementations need only to
* implement {@link #handle(HttpRequest, HttpResponse, HttpContext)}.
*
* @since 4.0
*/
public abstract class SimpleNHttpRequestHandler implements NHttpRequestHandler {
public final void handle(
final HttpRequest request,
final HttpResponse response,
final NHttpResponseTrigger trigger,
final HttpContext context) throws HttpException, IOException {
handle(request, response, context);
trigger.submitResponse(response);
}
public abstract void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.protocol;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.NHttpServerConnection;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpExpectationVerifier;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
/**
* Service protocol handler implementations that provide compatibility with
* the blocking I/O by storing the full content of HTTP messages in memory.
* The {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
* method will fire only when the entire message content has been read into
* an in-memory buffer. Please note that request processing take place the
* main I/O thread and therefore individual HTTP request handlers should not
* block indefinitely.
* <p>
* When using this protocol handler {@link HttpEntity}'s content can be
* generated / consumed using standard {@link InputStream}/{@link OutputStream}
* classes.
* <p>
* IMPORTANT: This protocol handler should be used only when dealing with HTTP
* messages that are known to be limited in length.
*
*
* @since 4.0
*/
public class BufferingHttpServiceHandler implements NHttpServiceHandler {
private final AsyncNHttpServiceHandler asyncHandler;
private HttpRequestHandlerResolver handlerResolver;
public BufferingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final HttpParams params) {
super();
this.asyncHandler = new AsyncNHttpServiceHandler(
httpProcessor,
responseFactory,
connStrategy,
allocator,
params);
this.asyncHandler.setHandlerResolver(new RequestHandlerResolverAdaptor());
}
public BufferingHttpServiceHandler(
final HttpProcessor httpProcessor,
final HttpResponseFactory responseFactory,
final ConnectionReuseStrategy connStrategy,
final HttpParams params) {
this(httpProcessor, responseFactory, connStrategy,
new HeapByteBufferAllocator(), params);
}
public void setEventListener(final EventListener eventListener) {
this.asyncHandler.setEventListener(eventListener);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.asyncHandler.setExpectationVerifier(expectationVerifier);
}
public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
this.handlerResolver = handlerResolver;
}
public void connected(final NHttpServerConnection conn) {
this.asyncHandler.connected(conn);
}
public void closed(final NHttpServerConnection conn) {
this.asyncHandler.closed(conn);
}
public void requestReceived(final NHttpServerConnection conn) {
this.asyncHandler.requestReceived(conn);
}
public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
this.asyncHandler.inputReady(conn, decoder);
}
public void responseReady(final NHttpServerConnection conn) {
this.asyncHandler.responseReady(conn);
}
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
this.asyncHandler.outputReady(conn, encoder);
}
public void exception(final NHttpServerConnection conn, final HttpException httpex) {
this.asyncHandler.exception(conn, httpex);
}
public void exception(final NHttpServerConnection conn, final IOException ioex) {
this.asyncHandler.exception(conn, ioex);
}
public void timeout(NHttpServerConnection conn) {
this.asyncHandler.timeout(conn);
}
class RequestHandlerResolverAdaptor implements NHttpRequestHandlerResolver {
public NHttpRequestHandler lookup(final String requestURI) {
HttpRequestHandler handler = handlerResolver.lookup(requestURI);
if (handler != null) {
return new RequestHandlerAdaptor(handler);
} else {
return null;
}
}
}
static class RequestHandlerAdaptor extends SimpleNHttpRequestHandler {
private final HttpRequestHandler requestHandler;
public RequestHandlerAdaptor(final HttpRequestHandler requestHandler) {
super();
this.requestHandler = requestHandler;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) throws HttpException, IOException {
return new BufferingNHttpEntity(
request.getEntity(),
new HeapByteBufferAllocator());
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
this.requestHandler.handle(request, 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.http.nio.protocol;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Executor;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.entity.ContentBufferEntity;
import org.apache.http.nio.entity.ContentOutputStream;
import org.apache.http.nio.params.NIOReactorPNames;
import org.apache.http.nio.protocol.ThrottlingHttpServiceHandler.ServerConnState;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.ContentInputBuffer;
import org.apache.http.nio.util.ContentOutputBuffer;
import org.apache.http.nio.util.DirectByteBufferAllocator;
import org.apache.http.nio.util.SharedInputBuffer;
import org.apache.http.nio.util.SharedOutputBuffer;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
/**
* Client protocol handler implementation that provide compatibility with
* the blocking I/O by utilizing shared content buffers and a fairly small pool
* of worker threads. The throttling protocol handler allocates input / output
* buffers of a constant length upon initialization and controls the rate of
* I/O events in order to ensure those content buffers do not ever get
* overflown. This helps ensure nearly constant memory footprint for HTTP
* connections and avoid the out of memory condition while streaming content
* in and out. The {@link HttpRequestExecutionHandler#handleResponse(HttpResponse, HttpContext)}
* method will fire immediately when a message is received. The protocol handler
* delegate the task of processing requests and generating response content to
* an {@link Executor}, which is expected to perform those tasks using
* dedicated worker threads in order to avoid blocking the I/O thread.
* <p/>
* Usually throttling protocol handlers need only a modest number of worker
* threads, much fewer than the number of concurrent connections. If the length
* of the message is smaller or about the size of the shared content buffer
* worker thread will just store content in the buffer and terminate almost
* immediately without blocking. The I/O dispatch thread in its turn will take
* care of sending out the buffered content asynchronously. The worker thread
* will have to block only when processing large messages and the shared buffer
* fills up. It is generally advisable to allocate shared buffers of a size of
* an average content body for optimal performance.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
* <li>{@link org.apache.http.nio.params.NIOReactorPNames#CONTENT_BUFFER_SIZE}</li>
* </ul>
*
* @since 4.0
*/
public class ThrottlingHttpClientHandler extends NHttpHandlerBase
implements NHttpClientHandler {
protected HttpRequestExecutionHandler execHandler;
protected final Executor executor;
public ThrottlingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final ByteBufferAllocator allocator,
final Executor executor,
final HttpParams params) {
super(httpProcessor, connStrategy, allocator, params);
if (execHandler == null) {
throw new IllegalArgumentException("HTTP request execution handler may not be null.");
}
if (executor == null) {
throw new IllegalArgumentException("Executor may not be null");
}
this.execHandler = execHandler;
this.executor = executor;
}
public ThrottlingHttpClientHandler(
final HttpProcessor httpProcessor,
final HttpRequestExecutionHandler execHandler,
final ConnectionReuseStrategy connStrategy,
final Executor executor,
final HttpParams params) {
this(httpProcessor, execHandler, connStrategy,
new DirectByteBufferAllocator(), executor, params);
}
public void connected(final NHttpClientConnection conn, final Object attachment) {
HttpContext context = conn.getContext();
initialize(conn, attachment);
int bufsize = this.params.getIntParameter(
NIOReactorPNames.CONTENT_BUFFER_SIZE, 20480);
ClientConnState connState = new ClientConnState(bufsize, conn, this.allocator);
context.setAttribute(CONN_STATE, connState);
if (this.eventListener != null) {
this.eventListener.connectionOpen(conn);
}
requestReady(conn);
}
public void closed(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
if (connState != null) {
synchronized (connState) {
connState.close();
connState.notifyAll();
}
}
this.execHandler.finalizeContext(context);
if (this.eventListener != null) {
this.eventListener.connectionClosed(conn);
}
}
public void exception(final NHttpClientConnection conn, final HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
public void exception(final NHttpClientConnection conn, final IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
public void requestReady(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() != ClientConnState.READY) {
return;
}
HttpRequest request = this.execHandler.submitRequest(context);
if (request == null) {
return;
}
request.setParams(
new DefaultedHttpParams(request.getParams(), this.params));
context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.httpProcessor.process(request, context);
connState.setRequest(request);
conn.submitRequest(request);
connState.setOutputState(ClientConnState.REQUEST_SENT);
conn.requestInput();
if (request instanceof HttpEntityEnclosingRequest) {
if (((HttpEntityEnclosingRequest) request).expectContinue()) {
int timeout = conn.getSocketTimeout();
connState.setTimeout(timeout);
timeout = this.params.getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 3000);
conn.setSocketTimeout(timeout);
connState.setOutputState(ClientConnState.EXPECT_CONTINUE);
} else {
sendRequestBody(
(HttpEntityEnclosingRequest) request,
connState,
conn);
}
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
conn.suspendOutput();
return;
}
ContentOutputBuffer buffer = connState.getOutbuffer();
buffer.produceContent(encoder);
if (encoder.isCompleted()) {
connState.setInputState(ClientConnState.REQUEST_BODY_DONE);
} else {
connState.setInputState(ClientConnState.REQUEST_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void responseReceived(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = conn.getHttpResponse();
response.setParams(
new DefaultedHttpParams(response.getParams(), this.params));
HttpRequest request = connState.getRequest();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < HttpStatus.SC_OK) {
// 1xx intermediate response
if (statusCode == HttpStatus.SC_CONTINUE
&& connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
connState.setOutputState(ClientConnState.REQUEST_SENT);
continueRequest(conn, connState);
}
return;
} else {
connState.setResponse(response);
connState.setInputState(ClientConnState.RESPONSE_RECEIVED);
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
conn.resetOutput();
}
}
if (!canResponseHaveBody(request, response)) {
conn.resetInput();
response.setEntity(null);
connState.setInputState(ClientConnState.RESPONSE_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
}
if (response.getEntity() != null) {
response.setEntity(new ContentBufferEntity(
response.getEntity(),
connState.getInbuffer()));
}
context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
this.httpProcessor.process(response, context);
handleResponse(response, connState, conn);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
} catch (HttpException ex) {
closeConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalProtocolException(ex, conn);
}
}
}
public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
HttpResponse response = connState.getResponse();
ContentInputBuffer buffer = connState.getInbuffer();
buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
connState.setInputState(ClientConnState.RESPONSE_BODY_DONE);
if (!this.connStrategy.keepAlive(response, context)) {
conn.close();
}
} else {
connState.setInputState(ClientConnState.RESPONSE_BODY_STREAM);
}
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
}
public void timeout(final NHttpClientConnection conn) {
HttpContext context = conn.getContext();
ClientConnState connState = (ClientConnState) context.getAttribute(CONN_STATE);
try {
synchronized (connState) {
if (connState.getOutputState() == ClientConnState.EXPECT_CONTINUE) {
connState.setOutputState(ClientConnState.REQUEST_SENT);
continueRequest(conn, connState);
connState.notifyAll();
return;
}
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (this.eventListener != null) {
this.eventListener.fatalIOException(ex, conn);
}
}
handleTimeout(conn);
}
private void initialize(
final NHttpClientConnection conn,
final Object attachment) {
HttpContext context = conn.getContext();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.execHandler.initalizeContext(context, attachment);
}
private void continueRequest(
final NHttpClientConnection conn,
final ClientConnState connState) throws IOException {
HttpRequest request = connState.getRequest();
int timeout = connState.getTimeout();
conn.setSocketTimeout(timeout);
sendRequestBody(
(HttpEntityEnclosingRequest) request,
connState,
conn);
}
/**
* @throws IOException - not thrown currently
*/
private void sendRequestBody(
final HttpEntityEnclosingRequest request,
final ClientConnState connState,
final NHttpClientConnection conn) throws IOException {
HttpEntity entity = request.getEntity();
if (entity != null) {
this.executor.execute(new Runnable() {
public void run() {
try {
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (!connState.isWorkerRunning()) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setWorkerRunning(true);
}
HttpEntity entity = request.getEntity();
OutputStream outstream = new ContentOutputStream(
connState.getOutbuffer());
entity.writeTo(outstream);
outstream.flush();
outstream.close();
synchronized (connState) {
connState.setWorkerRunning(false);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
}
}
});
}
}
private void handleResponse(
final HttpResponse response,
final ClientConnState connState,
final NHttpClientConnection conn) {
final HttpContext context = conn.getContext();
this.executor.execute(new Runnable() {
public void run() {
try {
// Block until previous request is fully processed and
// the worker thread no longer holds the shared buffer
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getOutputState();
if (!connState.isWorkerRunning()) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
return;
}
connState.setWorkerRunning(true);
}
execHandler.handleResponse(response, context);
synchronized (connState) {
try {
for (;;) {
int currentState = connState.getInputState();
if (currentState == ClientConnState.RESPONSE_DONE) {
break;
}
if (currentState == ServerConnState.SHUTDOWN) {
return;
}
connState.wait();
}
} catch (InterruptedException ex) {
connState.shutdown();
}
connState.resetInput();
connState.resetOutput();
if (conn.isOpen()) {
conn.requestOutput();
}
connState.setWorkerRunning(false);
connState.notifyAll();
}
} catch (IOException ex) {
shutdownConnection(conn, ex);
if (eventListener != null) {
eventListener.fatalIOException(ex, conn);
}
}
}
});
}
static class ClientConnState {
public static final int SHUTDOWN = -1;
public static final int READY = 0;
public static final int REQUEST_SENT = 1;
public static final int EXPECT_CONTINUE = 2;
public static final int REQUEST_BODY_STREAM = 4;
public static final int REQUEST_BODY_DONE = 8;
public static final int RESPONSE_RECEIVED = 16;
public static final int RESPONSE_BODY_STREAM = 32;
public static final int RESPONSE_BODY_DONE = 64;
public static final int RESPONSE_DONE = 64;
private final SharedInputBuffer inbuffer;
private final SharedOutputBuffer outbuffer;
private volatile int inputState;
private volatile int outputState;
private volatile HttpRequest request;
private volatile HttpResponse response;
private volatile int timeout;
private volatile boolean workerRunning;
public ClientConnState(
int bufsize,
final IOControl ioControl,
final ByteBufferAllocator allocator) {
super();
this.inbuffer = new SharedInputBuffer(bufsize, ioControl, allocator);
this.outbuffer = new SharedOutputBuffer(bufsize, ioControl, allocator);
this.inputState = READY;
this.outputState = READY;
}
public ContentInputBuffer getInbuffer() {
return this.inbuffer;
}
public ContentOutputBuffer getOutbuffer() {
return this.outbuffer;
}
public int getInputState() {
return this.inputState;
}
public void setInputState(int inputState) {
this.inputState = inputState;
}
public int getOutputState() {
return this.outputState;
}
public void setOutputState(int outputState) {
this.outputState = outputState;
}
public HttpRequest getRequest() {
return this.request;
}
public void setRequest(final HttpRequest request) {
this.request = request;
}
public HttpResponse getResponse() {
return this.response;
}
public void setResponse(final HttpResponse response) {
this.response = response;
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public boolean isWorkerRunning() {
return this.workerRunning;
}
public void setWorkerRunning(boolean b) {
this.workerRunning = b;
}
public void close() {
this.inbuffer.close();
this.outbuffer.close();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void shutdown() {
this.inbuffer.shutdown();
this.outbuffer.shutdown();
this.inputState = SHUTDOWN;
this.outputState = SHUTDOWN;
}
public void resetInput() {
this.inbuffer.reset();
this.request = null;
this.inputState = READY;
}
public void resetOutput() {
this.outbuffer.reset();
this.response = null;
this.outputState = READY;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
/**
* A {@link ReadableByteChannel} that delegates to a {@link ContentDecoder}.
* Attempts to close this channel are ignored, and {@link #isOpen} always
* returns <code>true</code>.
*
* @since 4.0
*/
public class ContentDecoderChannel implements ReadableByteChannel {
private final ContentDecoder decoder;
public ContentDecoderChannel(ContentDecoder decoder) {
this.decoder = decoder;
}
public int read(ByteBuffer dst) throws IOException {
return decoder.read(dst);
}
public void close() {}
public boolean isOpen() {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.HttpConnection;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
/**
* Abstract non-blocking HTTP connection interface. Each connection contains an
* HTTP execution context, which can be used to maintain a processing state,
* as well as the actual {@link HttpRequest} and {@link HttpResponse} that are
* being transmitted over this connection. Both the request and
* the response objects can be <code>null</code> if there is no incoming or
* outgoing message currently being transferred.
* <p>
* Please note non-blocking HTTP connections are stateful and not thread safe.
* Input / output operations on non-blocking HTTP connections should be
* restricted to the dispatch events triggered by the I/O event dispatch thread.
* However, the {@link IOControl} interface is fully threading safe and can be
* manipulated from any thread.
*
* @since 4.0
*/
public interface NHttpConnection extends HttpConnection, IOControl {
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = 2;
/**
* Returns status of the connection:
* <p>
* {@link #ACTIVE}: connection is active.
* <p>
* {@link #CLOSING}: connection is being closed.
* <p>
* {@link #CLOSED}: connection has been closed.
*
* @return connection status.
*/
int getStatus();
/**
* Returns the current HTTP request if one is being received / transmitted.
* Otherwise returns <code>null</code>.
*
* @return HTTP request, if available, <code>null</code> otherwise.
*/
HttpRequest getHttpRequest();
/**
* Returns the current HTTP response if one is being received / transmitted.
* Otherwise returns <tt>null</tt>.
*
* @return HTTP response, if available, <code>null</code> otherwise.
*/
HttpResponse getHttpResponse();
/**
* Returns an HTTP execution context associated with this connection.
* @return HTTP context
*/
HttpContext getContext();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpServerConnection} used by
* {@link IOEventDispatch} implementations to inform server-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpServerIOTarget extends NHttpServerConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the server protocol handler.
*/
void consumeInput(NHttpServiceHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the server protocol handler.
*/
void produceOutput(NHttpServiceHandler handler);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
/**
* Abstract HTTP message parser for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageParser<T extends HttpMessage> {
/**
* Resets the parser. The parser will be ready to start parsing another
* HTTP message.
*/
void reset();
/**
* Fills the internal buffer of the parser with input data from the
* given {@link ReadableByteChannel}.
*
* @param channel the input channel
* @return number of bytes read.
* @throws IOException in case of an I/O error.
*/
int fillBuffer(ReadableByteChannel channel)
throws IOException;
/**
* Attempts to parse a complete message head from the content of the
* internal buffer. If the message in the input buffer is incomplete
* this method will return <code>null</code>.
*
* @return HTTP message head, if available, <code>null</code> otherwise.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
T parse() throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
import org.apache.http.protocol.HTTP;
/**
* A simple, self contained, repeatable non-blocking entity that retrieves
* its content from a {@link String} object.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*
*/
public class NStringEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NStringEntity(final String s, String charset)
throws UnsupportedEncodingException {
if (s == null) {
throw new IllegalArgumentException("Source string may not be null");
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
this.content = s.getBytes(charset);
this.buffer = ByteBuffer.wrap(this.content);
setContentType(HTTP.PLAIN_TEXT_TYPE + HTTP.CHARSET_PARAM + charset);
}
public NStringEntity(final String s) throws UnsupportedEncodingException {
this(s, null);
}
public boolean isRepeatable() {
return true;
}
public long getContentLength() {
return this.buffer.limit();
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A listener for available data on a non-blocking {@link ConsumingNHttpEntity}.
*
* @since 4.0
*/
public interface ContentListener {
/**
* Notification that content is available to be read from the decoder.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void contentAvailable(ContentDecoder decoder, IOControl ioctrl)
throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finished();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A {@link ConsumingNHttpEntity} that forwards available content to a
* {@link ContentListener}.
*
* @since 4.0
*/
public class ConsumingNHttpEntityTemplate
extends HttpEntityWrapper implements ConsumingNHttpEntity {
private final ContentListener contentListener;
public ConsumingNHttpEntityTemplate(
final HttpEntity httpEntity,
final ContentListener contentListener) {
super(httpEntity);
this.contentListener = contentListener;
}
public ContentListener getContentListener() {
return contentListener;
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.contentListener.contentAvailable(decoder, ioctrl);
}
public void finish() {
this.contentListener.finished();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* An {@link HttpEntity} that can stream content out into a
* {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ProducingNHttpEntity extends HttpEntity {
/**
* Notification that content should be written to the encoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend output events if the entity is temporarily unable to
* produce more content.
* <p>
* When all content is finished, this <b>MUST</b> call {@link ContentEncoder#complete()}.
* Failure to do so could result in the entity never being written.
*
* @param encoder content encoder.
* @param ioctrl I/O control of the underlying connection.
*/
void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for writing can be released.
*/
void finish() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
/**
* An entity whose content is retrieved from a string. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NStringEntity}
*
* @since 4.0
*/
@Deprecated
public class StringNIOEntity extends StringEntity implements HttpNIOEntity {
public StringNIOEntity(
final String s,
String charset) throws UnsupportedEncodingException {
super(s, charset);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.protocol.AsyncNHttpServiceHandler;
/**
* A simple self contained, repeatable non-blocking entity that retrieves
* its content from a byte array.
*
* @see AsyncNHttpServiceHandler
* @since 4.0
*/
public class NByteArrayEntity
extends AbstractHttpEntity implements ProducingNHttpEntity {
protected final byte[] content;
protected final ByteBuffer buffer;
public NByteArrayEntity(final byte[] b) {
this.content = b;
this.buffer = ByteBuffer.wrap(b);
}
public void finish() {
buffer.rewind();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
encoder.write(buffer);
if(!buffer.hasRemaining())
encoder.complete();
}
public long getContentLength() {
return buffer.limit();
}
public boolean isRepeatable() {
return true;
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() {
return new ByteArrayInputStream(content);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
/**
* A simple {@link ContentListener} that reads and ignores all content.
*
* @since 4.0
*/
public class SkipContentListener implements ContentListener {
private final ByteBuffer buffer;
public SkipContentListener(final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.buffer = allocator.allocate(2048);
}
public void contentAvailable(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
int totalRead = 0;
int lastRead;
do {
buffer.clear();
lastRead = decoder.read(buffer);
if (lastRead > 0)
totalRead += lastRead;
} while (lastRead > 0);
}
public void finished() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* {@link ProducingNHttpEntity} compatibility adaptor for blocking HTTP
* entities.
*
* @since 4.0
*/
public class NHttpEntityWrapper
extends HttpEntityWrapper implements ProducingNHttpEntity {
private final ReadableByteChannel channel;
private final ByteBuffer buffer;
public NHttpEntityWrapper(final HttpEntity httpEntity) throws IOException {
super(httpEntity);
this.channel = Channels.newChannel(httpEntity.getContent());
this.buffer = ByteBuffer.allocate(4096);
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
@Override
public boolean isStreaming() {
return true;
}
/**
* This method throws {@link UnsupportedOperationException}.
*/
@Override
public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException("Does not support blocking methods");
}
/**
* This method is equivalent to the {@link #finish()} method.
* <br/>
* TODO: The name of this method is misnomer. It will be renamed to
* #finish() in the next major release.
*/
@Override
public void consumeContent() throws IOException {
finish();
}
public void produceContent(
final ContentEncoder encoder,
final IOControl ioctrl) throws IOException {
int i = this.channel.read(this.buffer);
this.buffer.flip();
encoder.write(this.buffer);
boolean buffering = this.buffer.hasRemaining();
this.buffer.compact();
if (i == -1 && !buffering) {
encoder.complete();
this.channel.close();
}
}
public void finish() {
try {
this.channel.close();
} catch (IOException ignore) {
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.nio.util.ContentOutputBuffer;
/**
* {@link OutputStream} adaptor for {@link ContentOutputBuffer}.
*
* @since 4.0
*/
public class ContentOutputStream extends OutputStream {
private final ContentOutputBuffer buffer;
public ContentOutputStream(final ContentOutputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Output buffer may not be null");
}
this.buffer = buffer;
}
@Override
public void close() throws IOException {
this.buffer.writeCompleted();
}
@Override
public void flush() throws IOException {
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.buffer.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
this.buffer.write(b, 0, b.length);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.nio.util.SimpleInputBuffer;
/**
* A {@link ConsumingNHttpEntity} that consumes content into a buffer. The
* content can be retrieved as an InputStream via
* {@link HttpEntity#getContent()}, or written to an output stream via
* {@link HttpEntity#writeTo(OutputStream)}.
*
* @since 4.0
*/
public class BufferingNHttpEntity extends HttpEntityWrapper implements
ConsumingNHttpEntity {
private final static int BUFFER_SIZE = 2048;
private final SimpleInputBuffer buffer;
private boolean finished;
private boolean consumed;
public BufferingNHttpEntity(
final HttpEntity httpEntity,
final ByteBufferAllocator allocator) {
super(httpEntity);
this.buffer = new SimpleInputBuffer(BUFFER_SIZE, allocator);
}
public void consumeContent(
final ContentDecoder decoder,
final IOControl ioctrl) throws IOException {
this.buffer.consumeContent(decoder);
if (decoder.isCompleted()) {
this.finished = true;
}
}
public void finish() {
this.finished = true;
}
@Override
public void consumeContent() throws IOException {
}
/**
* Obtains entity's content as {@link InputStream}.
*
* @throws IllegalStateException if content of the entity has not been
* fully received or has already been consumed.
*/
@Override
public InputStream getContent() throws IOException {
if (!this.finished) {
throw new IllegalStateException("Entity content has not been fully received");
}
if (this.consumed) {
throw new IllegalStateException("Entity content has been consumed");
}
this.consumed = true;
return new ContentInputStream(this.buffer);
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return true;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = getContent();
byte[] buffer = new byte[BUFFER_SIZE];
int l;
// consume until EOF
while ((l = instream.read(buffer)) != -1) {
outstream.write(buffer, 0, l);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* HTTP entity wrapper whose content is provided by a
* {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentBufferEntity extends BasicHttpEntity {
private HttpEntity wrappedEntity;
/**
* Creates new instance of ContentBufferEntity.
*
* @param entity the original entity.
* @param buffer the content buffer.
*/
public ContentBufferEntity(final HttpEntity entity, final ContentInputBuffer buffer) {
super();
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
this.wrappedEntity = entity;
setContent(new ContentInputStream(buffer));
}
@Override
public boolean isChunked() {
return this.wrappedEntity.isChunked();
}
@Override
public long getContentLength() {
return this.wrappedEntity.getContentLength();
}
@Override
public Header getContentType() {
return this.wrappedEntity.getContentType();
}
@Override
public Header getContentEncoding() {
return this.wrappedEntity.getContentEncoding();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.ContentEncoderChannel;
import org.apache.http.nio.FileContentEncoder;
import org.apache.http.nio.IOControl;
/**
* A self contained, repeatable non-blocking entity that retrieves its content
* from a file. This class is mostly used to stream large files of different
* types, so one needs to supply the content type of the file to make sure
* the content can be correctly recognized and processed by the recipient.
*
* @since 4.0
*/
public class NFileEntity extends AbstractHttpEntity implements ProducingNHttpEntity {
private final File file;
private FileChannel fileChannel;
private long idx = -1;
private boolean useFileChannels;
/**
* Creates new instance of NFileEntity from the given source {@link File}
* with the given content type. If <code>useFileChannels</code> is set to
* <code>true</code>, the entity will try to use {@link FileContentEncoder}
* interface to stream file content directly from the file channel.
*
* @param file the source file.
* @param contentType the content type of the file.
* @param useFileChannels flag whether the direct transfer from the file
* channel should be attempted.
*/
public NFileEntity(final File file, final String contentType, boolean useFileChannels) {
if (file == null) {
throw new IllegalArgumentException("File may not be null");
}
this.file = file;
this.useFileChannels = useFileChannels;
setContentType(contentType);
}
public NFileEntity(final File file, final String contentType) {
this(file, contentType, true);
}
public void finish() {
try {
if(fileChannel != null)
fileChannel.close();
} catch(IOException ignored) {}
fileChannel = null;
}
public long getContentLength() {
return file.length();
}
public boolean isRepeatable() {
return true;
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
if(fileChannel == null) {
FileInputStream in = new FileInputStream(file);
fileChannel = in.getChannel();
idx = 0;
}
long transferred;
if(useFileChannels && encoder instanceof FileContentEncoder) {
transferred = ((FileContentEncoder)encoder)
.transfer(fileChannel, idx, Long.MAX_VALUE);
} else {
transferred = fileChannel.
transferTo(idx, Long.MAX_VALUE, new ContentEncoderChannel(encoder));
}
if(transferred > 0)
idx += transferred;
if(idx >= fileChannel.size())
encoder.complete();
}
public boolean isStreaming() {
return false;
}
public InputStream getContent() throws IOException {
return new FileInputStream(this.file);
}
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream instream = new FileInputStream(this.file);
try {
byte[] tmp = new byte[4096];
int l;
while ((l = instream.read(tmp)) != -1) {
outstream.write(tmp, 0, l);
}
outstream.flush();
} finally {
instream.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
/**
* @deprecated Use {@link ProducingNHttpEntity}
*
* @since 4.0
*/
@Deprecated
public interface HttpNIOEntity extends HttpEntity {
ReadableByteChannel getChannel() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.FileEntity;
/**
* An entity whose content is retrieved from from a file. In addition to the standard
* {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NFileEntity}
*
* @since 4.0
*/
@Deprecated
public class FileNIOEntity extends FileEntity implements HttpNIOEntity {
public FileNIOEntity(final File file, final String contentType) {
super(file, contentType);
}
public ReadableByteChannel getChannel() throws IOException {
RandomAccessFile rafile = new RandomAccessFile(this.file, "r");
return rafile.getChannel();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.io.BufferInfo;
import org.apache.http.nio.util.ContentInputBuffer;
/**
* {@link InputStream} adaptor for {@link ContentInputBuffer}.
*
* @since 4.0
*/
public class ContentInputStream extends InputStream {
private final ContentInputBuffer buffer;
public ContentInputStream(final ContentInputBuffer buffer) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Input buffer may not be null");
}
this.buffer = buffer;
}
@Override
public int available() throws IOException {
if (this.buffer instanceof BufferInfo) {
return ((BufferInfo) this.buffer).length();
} else {
return super.available();
}
}
@Override
public int read(final byte[] b, int off, int len) throws IOException {
return this.buffer.read(b, off, len);
}
@Override
public int read(final byte[] b) throws IOException {
if (b == null) {
return 0;
}
return this.buffer.read(b, 0, b.length);
}
@Override
public int read() throws IOException {
return this.buffer.read();
}
@Override
public void close() throws IOException {
// read and discard the remainder of the message
byte tmp[] = new byte[1024];
while (this.buffer.read(tmp, 0, tmp.length) >= 0) {
}
super.close();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* A non-blocking {@link HttpEntity} that allows content to be streamed from a
* {@link ContentDecoder}.
*
* @since 4.0
*/
public interface ConsumingNHttpEntity extends HttpEntity {
/**
* Notification that content is available to be read from the decoder.
* {@link IOControl} instance passed as a parameter to the method can be
* used to suspend input events if the entity is temporarily unable to
* allocate more storage to accommodate all incoming content.
*
* @param decoder content decoder.
* @param ioctrl I/O control of the underlying connection.
*/
void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException;
/**
* Notification that any resources allocated for reading can be released.
*/
void finish() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.entity;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
/**
* An entity whose content is retrieved from a byte array. In addition to the
* standard {@link HttpEntity} interface this class also implements NIO specific
* {@link HttpNIOEntity}.
*
* @deprecated Use {@link NByteArrayEntity}
*
* @since 4.0
*/
@Deprecated
public class ByteArrayNIOEntity extends ByteArrayEntity implements HttpNIOEntity {
public ByteArrayNIOEntity(final byte[] b) {
super(b);
}
public ReadableByteChannel getChannel() throws IOException {
return Channels.newChannel(getContent());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
/**
* Abstract server-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpServiceHandler {
/**
* Triggered when a new incoming connection is created.
*
* @param conn new incoming connection HTTP connection.
*/
void connected(NHttpServerConnection conn);
/**
* Triggered when a new HTTP request is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP request object.
* <p/>
* If the request received encloses a request entity this method will
* be followed a series of
* {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls
* to transfer the request content.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains a new HTTP request
*/
void requestReceived(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the request entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming request content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpServerConnection conn, ContentDecoder decoder);
/**
* Triggered when the connection is ready to accept a new HTTP response.
* The protocol handler does not have to submit a response if it is not
* ready.
*
* @see NHttpServerConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReady(NHttpServerConnection conn);
/**
* Triggered when the underlying channel is ready for writing a
* next portion of the response entity through the corresponding
* content encoder.
* <p/>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpServerConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing response content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpServerConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpServerConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP request.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpServerConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpServerConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpServerConnection conn);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
/**
* Abstract non-blocking server-side HTTP connection interface. It can be used
* to receive HTTP requests and asynchronously submit HTTP responses.
*
* @see NHttpConnection
*
* @since 4.0
*/
public interface NHttpServerConnection extends NHttpConnection {
/**
* Submits {link @HttpResponse} to be sent to the client.
*
* @param response HTTP response
*
* @throws IOException if I/O error occurs while submitting the response
* @throws HttpException if the HTTP response violates the HTTP protocol.
*/
void submitResponse(HttpResponse response) throws IOException, HttpException;
/**
* Returns <code>true</code> if an HTTP response has been submitted to the
* client.
*
* @return <code>true</code> if an HTTP response has been submitted,
* <code>false</code> otherwise.
*/
boolean isResponseSubmitted();
/**
* Resets output state. This method can be used to prematurely terminate
* processing of the incoming HTTP request.
*/
void resetInput();
/**
* Resets input state. This method can be used to prematurely terminate
* processing of the outgoing HTTP response.
*/
void resetOutput();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
/**
* Abstract HTTP message writer for non-blocking connections.
*
* @since 4.0
*/
public interface NHttpMessageWriter<T extends HttpMessage> {
/**
* Resets the writer. The writer will be ready to start serializing another
* HTTP message.
*/
void reset();
/**
* Serializes out the HTTP message head.
*
* @param message HTTP message.
* @throws IOException in case of an I/O error.
* @throws HttpException in case the HTTP message is malformed or
* violates the HTTP protocol.
*/
void write(T message) throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import org.apache.http.HttpException;
/**
* Abstract client-side HTTP protocol handler.
*
* @since 4.0
*/
public interface NHttpClientHandler {
/**
* Triggered when a new outgoing connection is created.
*
* @param conn new outgoing HTTP connection.
* @param attachment an object that was attached to the session request
*/
void connected(NHttpClientConnection conn, Object attachment);
/**
* Triggered when the connection is ready to accept a new HTTP request.
* The protocol handler does not have to submit a request if it is not
* ready.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that is ready to accept a new HTTP request.
*/
void requestReady(NHttpClientConnection conn);
/**
* Triggered when an HTTP response is received. The connection
* passed as a parameter to this method is guaranteed to return
* a valid HTTP response object.
* <p/>
* If the response received encloses a response entity this method will
* be followed by a series of
* {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls
* to transfer the response content.
*
* @see NHttpClientConnection
*
* @param conn HTTP connection that contains an HTTP response
*/
void responseReceived(NHttpClientConnection conn);
/**
* Triggered when the underlying channel is ready for reading a
* new portion of the response entity through the corresponding
* content decoder.
* <p/>
* If the content consumer is unable to process the incoming content,
* input event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentDecoder
* @see IOControl
*
* @param conn HTTP connection that can produce a new portion of the
* incoming response content.
* @param decoder The content decoder to use to read content.
*/
void inputReady(NHttpClientConnection conn, ContentDecoder decoder);
/**
* Triggered when the underlying channel is ready for writing a next portion
* of the request entity through the corresponding content encoder.
* <p>
* If the content producer is unable to generate the outgoing content,
* output event notifications can be temporarily suspended using
* {@link IOControl} interface.
*
* @see NHttpClientConnection
* @see ContentEncoder
* @see IOControl
*
* @param conn HTTP connection that can accommodate a new portion
* of the outgoing request content.
* @param encoder The content encoder to use to write content.
*/
void outputReady(NHttpClientConnection conn, ContentEncoder encoder);
/**
* Triggered when an I/O error occurs while reading from or writing
* to the underlying channel.
*
* @param conn HTTP connection that caused an I/O error
* @param ex I/O exception
*/
void exception(NHttpClientConnection conn, IOException ex);
/**
* Triggered when an HTTP protocol violation occurs while receiving
* an HTTP response.
*
* @param conn HTTP connection that caused an HTTP protocol violation
* @param ex HTTP protocol violation exception
*/
void exception(NHttpClientConnection conn, HttpException ex);
/**
* Triggered when no input is detected on this connection over the
* maximum period of inactivity.
*
* @param conn HTTP connection that caused timeout condition.
*/
void timeout(NHttpClientConnection conn);
/**
* Triggered when the connection is closed.
*
* @param conn closed HTTP connection.
*/
void closed(NHttpClientConnection conn);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
/**
* Connection input/output control interface. It can be used to control interest
* in I/O event notifications for non-blocking HTTP connections.
* <p>
* Implementations of this interface are expected to be threading safe.
* Therefore it can be used to request / suspend I/O event notifications from
* any thread of execution.
*
* @since 4.0
*/
public interface IOControl {
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for input operations.
*/
void requestInput();
/**
* Suspends event notifications about the underlying channel being
* ready for input operations.
*/
void suspendInput();
/**
* Requests event notifications to be triggered when the underlying
* channel is ready for output operations.
*/
void requestOutput();
/**
* Suspends event notifications about the underlying channel being
* ready for output operations.
*/
void suspendOutput();
/**
* Shuts down the underlying channel.
*
* @throws IOException
*/
void shutdown() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
/**
* Parameter names for I/O reactors.
*
* @since 4.0
*/
public interface NIOReactorPNames {
/**
* Determines the size of the content input/output buffers used
* to buffer data while receiving or transmitting HTTP messages.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String CONTENT_BUFFER_SIZE = "http.nio.content-buffer-size";
/**
* Determines the time interval in milliseconds at which the
* I/O reactor wakes up to check for timed out sessions and session requests.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String SELECT_INTERVAL = "http.nio.select-interval";
/**
* Determines the grace period the I/O reactors are expected to block
* waiting for individual worker threads to terminate cleanly.
* <p>
* This parameter expects a value of type {@link Long}.
* </p>
*/
public static final String GRACE_PERIOD = "http.nio.grace-period";
/**
* Determines whether interestOps() queueing is enabled for the I/O reactors.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*
* @since 4.1
*/
public static final String INTEREST_OPS_QUEUEING = "http.nio.interest-ops-queueing";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpParams;
/**
* Utility class for accessing I/O reactor parameters in {@link HttpParams}.
*
* @since 4.0
*
* @see NIOReactorPNames
*/
public final class NIOReactorParams implements NIOReactorPNames {
private NIOReactorParams() {
super();
}
/**
* Obtains the value of {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
* If not set, defaults to <code>4096</code>.
*
* @param params HTTP parameters.
* @return content buffer size.
*/
public static int getContentBufferSize(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter(CONTENT_BUFFER_SIZE, 4096);
}
/**
* Sets value of the {@link NIOReactorPNames#CONTENT_BUFFER_SIZE} parameter.
*
* @param params HTTP parameters.
* @param size content buffer size.
*/
public static void setContentBufferSize(final HttpParams params, int size) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CONTENT_BUFFER_SIZE, size);
}
/**
* Obtains the value of {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
* If not set, defaults to <code>1000</code>.
*
* @param params HTTP parameters.
* @return I/O select interval in milliseconds.
*/
public static long getSelectInterval(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(SELECT_INTERVAL, 1000);
}
/**
* Sets value of the {@link NIOReactorPNames#SELECT_INTERVAL} parameter.
*
* @param params HTTP parameters.
* @param ms I/O select interval in milliseconds.
*/
public static void setSelectInterval(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(SELECT_INTERVAL, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#GRACE_PERIOD} parameter.
* If not set, defaults to <code>500</code>.
*
* @param params HTTP parameters.
* @return shutdown grace period in milliseconds.
*/
public static long getGracePeriod(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getLongParameter(GRACE_PERIOD, 500);
}
/**
* Sets value of the {@link NIOReactorPNames#GRACE_PERIOD} parameter.
*
* @param params HTTP parameters.
* @param ms shutdown grace period in milliseconds.
*/
public static void setGracePeriod(final HttpParams params, long ms) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setLongParameter(GRACE_PERIOD, ms);
}
/**
* Obtains the value of {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
* If not set, defaults to <code>false</code>.
*
* @param params HTTP parameters.
* @return interest ops queuing flag.
*
* @since 4.1
*/
public static boolean getInterestOpsQueueing(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter(INTEREST_OPS_QUEUEING, false);
}
/**
* Sets value of the {@link NIOReactorPNames#INTEREST_OPS_QUEUEING} parameter.
*
* @param params HTTP parameters.
* @param interestOpsQueueing interest ops queuing.
*
* @since 4.1
*/
public static void setInterestOpsQueueing(
final HttpParams params, boolean interestOpsQueueing) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(INTEREST_OPS_QUEUEING, interestOpsQueueing);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.params;
import org.apache.http.params.HttpAbstractParamBean;
import org.apache.http.params.HttpParams;
/**
* @since 4.0
*/
public class NIOReactorParamBean extends HttpAbstractParamBean {
public NIOReactorParamBean (final HttpParams params) {
super(params);
}
public void setContentBufferSize (int contentBufferSize) {
NIOReactorParams.setContentBufferSize(params, contentBufferSize);
}
public void setSelectInterval (long selectInterval) {
NIOReactorParams.setSelectInterval(params, selectInterval);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A {@link WritableByteChannel} that delegates to a {@link ContentEncoder}.
* Attempts to close this channel are ignored, and {@link #isOpen} always
* returns <code>true</code>.
*
* @since 4.0
*/
public class ContentEncoderChannel implements WritableByteChannel {
private final ContentEncoder contentEncoder;
public ContentEncoderChannel(ContentEncoder contentEncoder) {
this.contentEncoder = contentEncoder;
}
public int write(ByteBuffer src) throws IOException {
return contentEncoder.write(src);
}
public void close() {}
public boolean isOpen() {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import org.apache.http.nio.reactor.IOEventDispatch;
/**
* Extended version of the {@link NHttpClientConnection} used by
* {@link IOEventDispatch} implementations to inform client-side connection
* objects of I/O events.
*
* @since 4.0
*/
public interface NHttpClientIOTarget extends NHttpClientConnection {
/**
* Triggered when the connection is ready to consume input.
*
* @param handler the client protocol handler.
*/
void consumeInput(NHttpClientHandler handler);
/**
* Triggered when the connection is ready to produce output.
*
* @param handler the client protocol handler.
*/
void produceOutput(NHttpClientHandler handler);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* A content decoder capable of transferring data directly to a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentDecoder extends ContentDecoder {
/**
* Transfers a portion of entity content from the underlying network channel
* into the given file channel.<br>
*
* <b>Warning</b>: Many implementations cannot write beyond the length of the file.
* If the position exceeds the channel's size, some implementations
* may throw an IOException.
*
* @param dst the target FileChannel to transfer data into.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative.
* <b>Must be less than or equal to the size of the file</b>
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
* @throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel dst, long position, long count) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content decoder. HTTP content decoders can be used
* to read entity content from the underlying channel in small
* chunks and apply the required coding transformation.
*
* @since 4.0
*/
public interface ContentDecoder {
/**
* Reads a portion of content from the underlying channel
*
* @param dst The buffer into which entity content is to be transferred
* @return The number of bytes read, possibly zero, or -1 if the
* channel has reached end-of-stream
* @throws IOException if I/O error occurs while reading content
*/
int read(ByteBuffer dst) throws IOException;
/**
* Returns <code>true</code> if the entity has been received in its
* entirety.
*
* @return <code>true</code> if all the content has been consumed,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Abstract HTTP content encoder. HTTP content encoders can be used
* to apply the required coding transformation and write entity
* content to the underlying channel in small chunks.
*
* @since 4.0
*/
public interface ContentEncoder {
/**
* Writes a portion of entity content to the underlying channel.
*
* @param src The buffer from which content is to be retrieved
* @return The number of bytes read, possibly zero
* @throws IOException if I/O error occurs while writing content
*/
int write(ByteBuffer src) throws IOException;
/**
* Terminates the content stream.
*
* @throws IOException if I/O error occurs while writing content
*/
void complete() throws IOException;
/**
* Returns <code>true</code> if the entity has been transferred in its
* entirety.
*
* @return <code>true</code> if all the content has been produced,
* <code>false</code> otherwise.
*/
boolean isCompleted();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Buffer for storing content to be streamed out to a {@link ContentEncoder}.
*
* @since 4.0
*/
public interface ContentOutputBuffer {
/**
* Writes content from this buffer to the given {@link ContentEncoder}.
*
* @param encoder content encoder.
* @return number of bytes written.
* @throws IOException in case of an I/O error.
*/
int produceContent(ContentEncoder encoder) throws IOException;
/**
* Resets the buffer by clearing its state and stored content.
*/
void reset();
/**
* @deprecated No longer used.
*/
@Deprecated
void flush() throws IOException;
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, this method can throw a runtime exception. The exact type
* of runtime exception thrown by this method depends on implementation.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes the specified byte to this buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Indicates the content has been fully written.
* @exception IOException if an I/O error occurs.
*/
void writeCompleted() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentDecoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentInputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expect to transfer data from {@link ContentDecoder} to the buffer
* by calling {@link #consumeContent(ContentDecoder)}.
* <p>
* The worker thread is expected to read the data from the buffer by calling
* {@link #read()} or {@link #read(byte[], int, int)} methods.
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be shut down
* using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedInputBuffer extends ExpandableBuffer implements ContentInputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedInputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
public int consumeContent(final ContentDecoder decoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setInputMode();
int totalRead = 0;
int bytesRead;
while ((bytesRead = decoder.read(this.buffer)) > 0) {
totalRead += bytesRead;
}
if (bytesRead == -1 || decoder.isCompleted()) {
this.endOfStream = true;
}
if (!this.buffer.hasRemaining()) {
this.ioctrl.suspendInput();
}
this.condition.signalAll();
if (totalRead > 0) {
return totalRead;
} else {
if (this.endOfStream) {
return -1;
} else {
return 0;
}
}
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
protected void waitForData() throws IOException {
this.lock.lock();
try {
try {
while (!super.hasData() && !this.endOfStream) {
if (this.shutdown) {
throw new InterruptedIOException("Input operation aborted");
}
this.ioctrl.requestInput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while waiting for more data");
}
} finally {
this.lock.unlock();
}
}
public void close() {
if (this.shutdown) {
return;
}
this.endOfStream = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
protected boolean isShutdown() {
return this.shutdown;
}
protected boolean isEndOfStream() {
return this.shutdown || (!hasData() && this.endOfStream);
}
public int read() throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
return this.buffer.get() & 0xff;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b, int off, int len) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
this.lock.lock();
try {
if (!hasData()) {
waitForData();
}
if (isEndOfStream()) {
return -1;
}
setOutputMode();
int chunk = len;
if (chunk > this.buffer.remaining()) {
chunk = this.buffer.remaining();
}
this.buffer.get(b, off, chunk);
return chunk;
} finally {
this.lock.unlock();
}
}
public int read(final byte[] b) throws IOException {
if (this.shutdown) {
return -1;
}
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocate(int)}.
*
* @since 4.0
*/
public class HeapByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocate(size);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Allocates {@link ByteBuffer} instances using
* {@link ByteBuffer#allocateDirect(int)}.
*
* @since 4.0
*/
public class DirectByteBufferAllocator implements ByteBufferAllocator {
public ByteBuffer allocate(int size) {
return ByteBuffer.allocateDirect(size);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
/**
* Abstract interface to allocate {@link ByteBuffer} instances.
*
* @since 4.0
*/
public interface ByteBufferAllocator {
/**
* Allocates {@link ByteBuffer} of the given size.
*
* @param size the size of the buffer.
* @return byte buffer.
*/
ByteBuffer allocate(int size);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import org.apache.http.nio.ContentEncoder;
/**
* Basic implementation of the {@link ContentOutputBuffer} interface.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
public class SimpleOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private boolean endOfStream;
public SimpleOutputBuffer(int buffersize, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
this.endOfStream = false;
}
public int produceContent(final ContentEncoder encoder) throws IOException {
setOutputMode();
int bytesWritten = encoder.write(this.buffer);
if (!hasData() && this.endOfStream) {
encoder.complete();
}
return bytesWritten;
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.buffer.position() + len);
this.buffer.put(b, off, len);
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
if (this.endOfStream) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.endOfStream) {
return;
}
setInputMode();
ensureCapacity(this.capacity() + 1);
this.buffer.put((byte)b);
}
public void reset() {
super.clear();
this.endOfStream = false;
}
public void flush() {
}
public void writeCompleted() {
this.endOfStream = true;
}
public void shutdown() {
this.endOfStream = true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
/**
* Basic buffer properties.
*
* @since 4.0
*
* @deprecated Use {@link org.apache.http.io.BufferInfo}
*/
@Deprecated
public interface BufferInfo {
int length();
int capacity();
int available();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* Implementation of the {@link ContentOutputBuffer} interface that can be
* shared by multiple threads, usually the I/O dispatch of an I/O reactor and
* a worker thread.
* <p>
* The I/O dispatch thread is expected to transfer data from the buffer to
* {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}.
* <p>
* The worker thread is expected to write data to the buffer by calling
* {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()}
* <p>
* In case of an abnormal situation or when no longer needed the buffer must be
* shut down using {@link #shutdown()} method.
*
* @since 4.0
*/
public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer {
private final IOControl ioctrl;
private final ReentrantLock lock;
private final Condition condition;
private volatile boolean shutdown = false;
private volatile boolean endOfStream = false;
public SharedOutputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) {
super(buffersize, allocator);
if (ioctrl == null) {
throw new IllegalArgumentException("I/O content control may not be null");
}
this.ioctrl = ioctrl;
this.lock = new ReentrantLock();
this.condition = this.lock.newCondition();
}
public void reset() {
if (this.shutdown) {
return;
}
this.lock.lock();
try {
clear();
this.endOfStream = false;
} finally {
this.lock.unlock();
}
}
@Override
public boolean hasData() {
this.lock.lock();
try {
return super.hasData();
} finally {
this.lock.unlock();
}
}
@Override
public int available() {
this.lock.lock();
try {
return super.available();
} finally {
this.lock.unlock();
}
}
@Override
public int capacity() {
this.lock.lock();
try {
return super.capacity();
} finally {
this.lock.unlock();
}
}
@Override
public int length() {
this.lock.lock();
try {
return super.length();
} finally {
this.lock.unlock();
}
}
public int produceContent(final ContentEncoder encoder) throws IOException {
if (this.shutdown) {
return -1;
}
this.lock.lock();
try {
setOutputMode();
int bytesWritten = 0;
if (super.hasData()) {
bytesWritten = encoder.write(this.buffer);
if (encoder.isCompleted()) {
this.endOfStream = true;
}
}
if (!super.hasData()) {
// No more buffered content
// If at the end of the stream, terminate
if (this.endOfStream && !encoder.isCompleted()) {
encoder.complete();
}
if (!this.endOfStream) {
// suspend output events
this.ioctrl.suspendOutput();
}
}
this.condition.signalAll();
return bytesWritten;
} finally {
this.lock.unlock();
}
}
public void close() {
shutdown();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
this.lock.lock();
try {
this.condition.signalAll();
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
int remaining = len;
while (remaining > 0) {
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
int chunk = Math.min(remaining, this.buffer.remaining());
this.buffer.put(b, off, chunk);
remaining -= chunk;
off += chunk;
}
} finally {
this.lock.unlock();
}
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
this.lock.lock();
try {
if (this.shutdown || this.endOfStream) {
throw new IllegalStateException("Buffer already closed for writing");
}
setInputMode();
if (!this.buffer.hasRemaining()) {
flushContent();
setInputMode();
}
this.buffer.put((byte)b);
} finally {
this.lock.unlock();
}
}
public void flush() throws IOException {
}
private void flushContent() throws IOException {
this.lock.lock();
try {
try {
while (super.hasData()) {
if (this.shutdown) {
throw new InterruptedIOException("Output operation aborted");
}
this.ioctrl.requestOutput();
this.condition.await();
}
} catch (InterruptedException ex) {
throw new IOException("Interrupted while flushing the content buffer");
}
} finally {
this.lock.unlock();
}
}
public void writeCompleted() throws IOException {
this.lock.lock();
try {
if (this.endOfStream) {
return;
}
this.endOfStream = true;
this.ioctrl.requestOutput();
} finally {
this.lock.unlock();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.util;
import java.nio.ByteBuffer;
import org.apache.http.io.BufferInfo;
/**
* A buffer that expand its capacity on demand using {@link ByteBufferAllocator}
* interface. Internally, this class is backed by an instance of
* {@link ByteBuffer}.
* <p>
* This class is not thread safe.
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
public class ExpandableBuffer implements BufferInfo, org.apache.http.nio.util.BufferInfo {
public final static int INPUT_MODE = 0;
public final static int OUTPUT_MODE = 1;
private int mode;
protected ByteBuffer buffer = null;
private final ByteBufferAllocator allocator;
/**
* Allocates buffer of the given size using the given allocator.
*
* @param buffersize the buffer size.
* @param allocator allocator to be used to allocate {@link ByteBuffer}s.
*/
public ExpandableBuffer(int buffersize, final ByteBufferAllocator allocator) {
super();
if (allocator == null) {
throw new IllegalArgumentException("ByteBuffer allocator may not be null");
}
this.allocator = allocator;
this.buffer = allocator.allocate(buffersize);
this.mode = INPUT_MODE;
}
/**
* Returns the current mode:
* <p>
* {@link #INPUT_MODE}: the buffer is in the input mode.
* <p>
* {@link #OUTPUT_MODE}: the buffer is in the output mode.
*
* @return current input/output mode.
*/
protected int getMode() {
return this.mode;
}
/**
* Sets output mode. The buffer can now be read from.
*/
protected void setOutputMode() {
if (this.mode != OUTPUT_MODE) {
this.buffer.flip();
this.mode = OUTPUT_MODE;
}
}
/**
* Sets input mode. The buffer can now be written into.
*/
protected void setInputMode() {
if (this.mode != INPUT_MODE) {
if (this.buffer.hasRemaining()) {
this.buffer.compact();
} else {
this.buffer.clear();
}
this.mode = INPUT_MODE;
}
}
private void expandCapacity(int capacity) {
ByteBuffer oldbuffer = this.buffer;
this.buffer = allocator.allocate(capacity);
oldbuffer.flip();
this.buffer.put(oldbuffer);
}
/**
* Expands buffer's capacity.
*/
protected void expand() {
int newcapacity = (this.buffer.capacity() + 1) << 1;
if (newcapacity < 0) {
newcapacity = Integer.MAX_VALUE;
}
expandCapacity(newcapacity);
}
/**
* Ensures the buffer can accommodate the required capacity.
*
* @param requiredCapacity
*/
protected void ensureCapacity(int requiredCapacity) {
if (requiredCapacity > this.buffer.capacity()) {
expandCapacity(requiredCapacity);
}
}
/**
* Returns the total capacity of this buffer.
*
* @return total capacity.
*/
public int capacity() {
return this.buffer.capacity();
}
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
public boolean hasData() {
setOutputMode();
return this.buffer.hasRemaining();
}
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
public int length() {
setOutputMode();
return this.buffer.remaining();
}
/**
* Returns available capacity of this buffer.
*
* @return buffer length.
*/
public int available() {
setInputMode();
return this.buffer.remaining();
}
/**
* Clears buffer.
*/
protected void clear() {
this.buffer.clear();
this.mode = INPUT_MODE;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("[mode=");
int mode = getMode();
if (mode == INPUT_MODE) {
sb.append("in");
} else {
sb.append("out");
}
sb.append(" pos=");
sb.append(this.buffer.position());
sb.append(" lim=");
sb.append(this.buffer.limit());
sb.append(" cap=");
sb.append(this.buffer.capacity());
sb.append("]");
return sb.toString();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.