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.examples.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request via SOCKS proxy using {@link HttpClient}.
*
* @since 4.1
*/
public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter("socks.host", "mysockshost");
httpclient.getParams().setParameter("socks.port", 1234);
httpclient.getConnectionManager().getSchemeRegistry().register(
new Scheme("http", 80, new MySchemeSocketFactory()));
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy");
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
static class MySchemeSocketFactory implements SchemeSocketFactory {
public Socket createSocket(final HttpParams params) throws IOException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String proxyHost = (String) params.getParameter("socks.host");
Integer proxyPort = (Integer) params.getParameter("socks.port");
InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
public Socket connectSocket(
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Socket sock;
if (socket != null) {
sock = socket;
} else {
sock = createSocket(params);
}
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
int timeout = HttpConnectionParams.getConnectionTimeout(params);
try {
sock.connect(remoteAddress, timeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
return sock;
}
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
return false;
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// Create local execution context
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget, localContext);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScope authScope = authState.getAuthScope();
System.out.println("Please provide credentials");
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
System.out.println(" Realm: " + authScope.getRealm());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
trying = true;
} else {
trying = false;
}
} else {
trying = false;
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.BasicScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using BASIC scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.DigestScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local
// auth cache
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
authCache.put(targetHost, digestAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.BasicCookieStore;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
*/
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.client.entity.UrlEncodedFormEntity;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.EntityUtils;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
/**
* Some X509 certificates to test against.
* <p/>
* Note: some of these certificates have Japanese Kanji in the "subjectAlt"
* field (UTF8). Not sure how realistic that is since international characters
* in DNS names usually get translated into ASCII using "xn--" style DNS
* entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to
* find 花子.co.jp. So would the CN in the certificate contain
* "xn--i8s592g.co.jp" in ASCII, or "花子.co.jp" in UTF8? (Both?)
*
* @since 11-Dec-2006
*/
public class CertificatesToPlayWith {
/**
* CN=foo.com
*/
public final static byte[] X509_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
"hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
"FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
"yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" +
"fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" +
"c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" +
"815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" +
"HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" +
"SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=花子.co.jp
*/
public final static byte[] X509_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" +
"FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" +
"MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" +
"g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" +
"wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" +
"7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" +
"AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" +
"qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" +
"CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" +
"HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" +
"rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" +
"ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" +
"spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" +
"a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" +
"9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" +
"UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, subjectAlt=bar.com
*/
public final static byte[] X509_FOO_BAR = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" +
"dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" +
"zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" +
"3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" +
"88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" +
"2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" +
"VbWx/uETImUu+NZg22ewEw==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, subjectAlt=bar.com, subjectAlt=花子.co.jp
* (hanako.co.jp in kanji)
*/
public final static byte[] X509_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" +
"SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" +
"++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" +
"PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" +
"12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" +
"sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" +
"j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.foo.com
*/
public final static byte[] X509_WILD_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
"dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
"CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
"jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
"ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
"JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
"q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
"qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" +
"N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" +
"A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" +
"yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" +
"G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" +
"l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.co.jp
*/
public final static byte[] X509_WILD_CO_JP = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
"hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
"FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
"yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" +
"CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" +
"1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" +
"S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" +
"UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" +
"EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.花子.co.jp
* (*.hanako.co.jp in kanji)
*/
public final static byte[] X509_WILD_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
"dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
"CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
"jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
"ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
"JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
"q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
"qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" +
"YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" +
"DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" +
"27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" +
"MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" +
"DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" +
"WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" +
"hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" +
"qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" +
"pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, CN=bar.com, CN=花子.co.jp
*/
public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" +
"MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" +
"loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" +
"bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" +
"Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" +
"h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" +
"TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" +
"3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" +
"Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" +
"tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" +
"DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" +
"y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" +
"uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" +
"EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" +
"SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" +
"VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* subjectAlt=foo.com
*/
public final static byte[] X509_NO_CNS_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" +
"bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" +
"fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" +
"xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" +
"Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" +
"ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" +
"jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" +
"5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" +
"IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" +
"0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" +
"CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" +
"tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" +
"Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" +
"yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" +
"qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" +
"n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Intermediate CA for all of these.
*/
public final static byte[] X509_INTERMEDIATE_CA = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
"BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
"hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" +
"WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" +
"EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" +
"BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" +
"MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" +
"hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" +
"XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" +
"Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" +
"KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" +
"qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" +
"9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" +
"6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" +
"rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" +
"VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" +
"c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" +
"KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" +
"Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" +
"e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" +
"1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" +
"XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" +
"aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Root CA for all of these.
*/
public final static byte[] X509_ROOT_CA = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
"BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
"hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" +
"WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" +
"FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" +
"A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" +
"Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" +
"79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" +
"w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" +
"mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" +
"jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" +
"JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" +
"EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" +
"9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" +
"hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" +
"Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" +
"MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" +
"rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" +
"S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" +
"VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" +
"lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" +
"hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" +
"Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" +
"2dDk0g==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Below is the private key for all the server certificates above (but
* not the intermediate CA or the root CA). All of those server certs
* came from the same private key.
*/
public final static String RSA_PUBLIC_MODULUS =
"00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" +
"8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" +
"41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" +
"f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" +
"9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" +
"56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" +
"713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" +
"cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" +
"4caab29bddf085893dde5de87047b9e5cd";
public final static String RSA_PUBLIC_EXPONENT = "65537";
public final static String RSA_PRIVATE_EXPONENT =
"577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" +
"7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" +
"8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" +
"f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" +
"a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" +
"d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" +
"a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" +
"c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" +
"44e6b355c1df581f50997175166eef39";
public final static String RSA_PRIME1 =
"00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" +
"a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" +
"b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" +
"350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" +
"fef7d8b532608d2513";
public final static String RSA_PRIME2 =
"00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" +
"db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" +
"af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" +
"529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" +
"c18d320510d79f859f";
public final static String RSA_EXPONENT1 =
"029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" +
"47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" +
"6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" +
"c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" +
"106467da112ce389";
public final static String RSA_EXPONENT2 =
"00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" +
"7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" +
"4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" +
"9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" +
"e997f079b0f6314eb7";
public final static String RSA_COEFFICIENT =
"00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" +
"1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" +
"a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" +
"001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" +
"2b8a9c7d91c7d175ae";
/**
* subjectAlt=IP Address:127.0.0.1, email:oleg@ural.ru, DNS:localhost.localdomain
*/
public final static byte[] X509_MULTIPLE_SUBJECT_ALT = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIDcTCCAtqgAwIBAgIBATANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJDSDEL\n" +
"MAkGA1UECBMCWkgxDzANBgNVBAcTBlp1cmljaDETMBEGA1UEAxMKTXkgVGVzdCBD\n" +
"QTAeFw0wODEwMzExMTU3NDVaFw0wOTEwMzExMTU3NDVaMGkxCzAJBgNVBAYTAkNI\n" +
"MRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYDVQQKEwdV\n" +
"bmtub3duMRAwDgYDVQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2NhbGhvc3QwggG4\n" +
"MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/\n" +
"gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" +
"IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZ\n" +
"ndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5\n" +
"eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbh\n" +
"PBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8G\n" +
"kotmXoB7VSVkAUw7/s9JKgOBhQACgYEA6ogAb/YLM1Rz9AoXKW4LA70VtFf7Mqqp\n" +
"divdu9f72WQc1vMKo1YMf3dQadkMfBYRvAAa1IXDnoiFCHhXnVRkWkoUBJyNebLB\n" +
"N92CZc0RVFZiMFgQMEh8UldnvAIi4cBk0/YuN3BGl4MzmquVIGrFovdWGqeaveOu\n" +
"Xcu4lKGJNiqjODA2MDQGA1UdEQQtMCuHBH8AAAGBDG9sZWdAdXJhbC5ydYIVbG9j\n" +
"YWxob3N0LmxvY2FsZG9tYWluMA0GCSqGSIb3DQEBBQUAA4GBAIgEwIoCSRkU3O7K\n" +
"USYaOYyfJB9hsvs6YpClvYXiQ/5kPGARP60pM62v4wC7wI9shEizokIAxY2+O3cC\n" +
"vwuJhNYaa2FJMELIwRN3XES8X8R6JHWbPaRjaAAPhczuEd8SZYy8yiVLmJTgw0gH\n" +
"BSW775NHlkjsscFVgXkNf0PobqJ9\n" +
"-----END CERTIFICATE-----").getBytes();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Local HTTP server for tests that require one.
* Based on the <code>ElementalHttpServer</code> example in HttpCore.
*/
public class LocalTestServer {
/**
* The local address to bind to.
* The host is an IP number rather than "localhost" to avoid surprises
* on hosts that map "localhost" to an IPv6 address or something else.
* The port is 0 to let the system pick one.
*/
public final static InetSocketAddress TEST_SERVER_ADDR =
new InetSocketAddress("127.0.0.1", 0);
/** The request handler registry. */
private final HttpRequestHandlerRegistry handlerRegistry;
private final HttpService httpservice;
/** Optional SSL context */
private final SSLContext sslcontext;
/** The server socket, while being served. */
private volatile ServerSocket servicedSocket;
/** The request listening thread, while listening. */
private volatile ListenerThread listenerThread;
/** Set of active worker threads */
private final Set<Worker> workers;
/** The number of connections this accepted. */
private final AtomicInteger acceptedConnections = new AtomicInteger(0);
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param reuseStrat the connection reuse strategy to be used by the
* server, or <code>null</code> to use
* {@link #newConnectionReuseStrategy() default}
* strategy.
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
* @param sslcontext optional SSL context if the server is to leverage
* SSL/TLS transport security
*/
public LocalTestServer(
final BasicHttpProcessor proc,
final ConnectionReuseStrategy reuseStrat,
final HttpResponseFactory responseFactory,
final HttpExpectationVerifier expectationVerifier,
final HttpParams params,
final SSLContext sslcontext) {
super();
this.handlerRegistry = new HttpRequestHandlerRegistry();
this.workers = Collections.synchronizedSet(new HashSet<Worker>());
this.httpservice = new HttpService(
proc != null ? proc : newProcessor(),
reuseStrat != null ? reuseStrat: newConnectionReuseStrategy(),
responseFactory != null ? responseFactory: newHttpResponseFactory(),
handlerRegistry,
expectationVerifier,
params != null ? params : newDefaultParams());
this.sslcontext = sslcontext;
}
/**
* Creates a new test server with SSL/TLS encryption.
*
* @param sslcontext SSL context
*/
public LocalTestServer(final SSLContext sslcontext) {
this(null, null, null, null, null, sslcontext);
}
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
*/
public LocalTestServer(
BasicHttpProcessor proc,
HttpParams params) {
this(proc, null, null, null, params, null);
}
/**
* Obtains an HTTP protocol processor with default interceptors.
*
* @return a protocol processor for server-side use
*/
protected HttpProcessor newProcessor() {
return new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
}
/**
* Obtains a set of reasonable default parameters for a server.
*
* @return default parameters
*/
protected HttpParams newDefaultParams() {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
"LocalTestServer/1.1");
return params;
}
protected ConnectionReuseStrategy newConnectionReuseStrategy() {
return new DefaultConnectionReuseStrategy();
}
protected HttpResponseFactory newHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Returns the number of connections this test server has accepted.
*/
public int getAcceptedConnectionCount() {
return acceptedConnections.get();
}
/**
* {@link #register Registers} a set of default request handlers.
* <pre>
* URI pattern Handler
* ----------- -------
* /echo/* {@link EchoHandler EchoHandler}
* /random/* {@link RandomHandler RandomHandler}
* </pre>
*/
public void registerDefaultHandlers() {
handlerRegistry.register("/echo/*", new EchoHandler());
handlerRegistry.register("/random/*", new RandomHandler());
}
/**
* Registers a handler with the local registry.
*
* @param pattern the URL pattern to match
* @param handler the handler to apply
*/
public void register(String pattern, HttpRequestHandler handler) {
handlerRegistry.register(pattern, handler);
}
/**
* Unregisters a handler from the local registry.
*
* @param pattern the URL pattern
*/
public void unregister(String pattern) {
handlerRegistry.unregister(pattern);
}
/**
* Starts this test server.
*/
public void start() throws Exception {
if (servicedSocket != null) {
throw new IllegalStateException(this.toString() + " already running");
}
ServerSocket ssock;
if (sslcontext != null) {
SSLServerSocketFactory sf = sslcontext.getServerSocketFactory();
ssock = sf.createServerSocket();
} else {
ssock = new ServerSocket();
}
ssock.setReuseAddress(true); // probably pointless for port '0'
ssock.bind(TEST_SERVER_ADDR);
servicedSocket = ssock;
listenerThread = new ListenerThread();
listenerThread.setDaemon(false);
listenerThread.start();
}
/**
* Stops this test server.
*/
public void stop() throws Exception {
if (servicedSocket == null) {
return; // not running
}
ListenerThread t = listenerThread;
if (t != null) {
t.shutdown();
}
synchronized (workers) {
for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
Worker worker = it.next();
worker.shutdown();
}
}
}
public void awaitTermination(long timeMs) throws InterruptedException {
if (listenerThread != null) {
listenerThread.join(timeMs);
}
}
@Override
public String toString() {
ServerSocket ssock = servicedSocket; // avoid synchronization
StringBuilder sb = new StringBuilder(80);
sb.append("LocalTestServer/");
if (ssock == null)
sb.append("stopped");
else
sb.append(ssock.getLocalSocketAddress());
return sb.toString();
}
/**
* Obtains the local address the server is listening on
*
* @return the service address
*/
public InetSocketAddress getServiceAddress() {
ServerSocket ssock = servicedSocket; // avoid synchronization
if (ssock == null) {
throw new IllegalStateException("not running");
}
return (InetSocketAddress) ssock.getLocalSocketAddress();
}
/**
* The request listener.
* Accepts incoming connections and launches a service thread.
*/
class ListenerThread extends Thread {
private volatile Exception exception;
ListenerThread() {
super();
}
@Override
public void run() {
try {
while (!interrupted()) {
Socket socket = servicedSocket.accept();
acceptedConnections.incrementAndGet();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, httpservice.getParams());
// Start worker thread
Worker worker = new Worker(conn);
workers.add(worker);
worker.setDaemon(true);
worker.start();
}
} catch (Exception ex) {
this.exception = ex;
} finally {
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
class Worker extends Thread {
private final HttpServerConnection conn;
private volatile Exception exception;
public Worker(final HttpServerConnection conn) {
this.conn = conn;
}
@Override
public void run() {
HttpContext context = new BasicHttpContext();
try {
while (this.conn.isOpen() && !Thread.interrupted()) {
httpservice.handleRequest(this.conn, context);
}
} catch (Exception ex) {
this.exception = ex;
} finally {
workers.remove(this);
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.util.Locale;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.util.EntityUtils;
/**
* A handler that echos the incoming request entity.
*
*
*
* <!-- empty lines to avoid 'svn diff' problems -->
*/
public class EchoHandler
implements HttpRequestHandler {
// public default constructor
/**
* Handles a request by echoing the incoming request entity.
* If there is no request entity, an empty document is returned.
*
* @param request the request
* @param response the response
* @param context the context
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
public void handle(final HttpRequest request,
final HttpResponse response,
final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!"GET".equals(method) &&
!"POST".equals(method) &&
!"PUT".equals(method)
) {
throw new MethodNotSupportedException
(method + " not supported by " + getClass().getName());
}
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest)
entity = ((HttpEntityEnclosingRequest)request).getEntity();
// For some reason, just putting the incoming entity into
// the response will not work. We have to buffer the message.
byte[] data;
if (entity == null) {
data = new byte [0];
} else {
data = EntityUtils.toByteArray(entity);
}
ByteArrayEntity bae = new ByteArrayEntity(data);
if (entity != null) {
bae.setContentType(entity.getContentType());
}
entity = bae;
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(entity);
} // handle
} // class EchoHandler
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetSocketAddress;
import org.apache.ogt.http.HttpHost;
import org.junit.After;
/**
* Base class for tests using {@link LocalTestServer}. The server will not be started
* per default.
*/
public abstract class BasicServerTestBase {
/** The local server for testing. */
protected LocalTestServer localServer;
@After
public void tearDown() throws Exception {
if (localServer != null) {
localServer.stop();
}
}
/**
* Obtains the address of the local test server.
*
* @return the test server host, with a scheme name of "http"
*/
protected HttpHost getServerHttp() {
InetSocketAddress address = localServer.getServiceAddress();
return new HttpHost(
address.getHostName(),
address.getPort(),
"http");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.protocol.HttpContext;
public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
response.addHeader(AUTH.WWW_AUTH, "Basic realm=\"test realm\"");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.AbstractHttpEntity;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpRequestHandler;
/**
* A handler that generates random data.
*
*
*
* <!-- empty lines to avoid 'svn diff' problems -->
*/
public class RandomHandler
implements HttpRequestHandler {
// public default constructor
/**
* Handles a request by generating random data.
* The length of the response can be specified in the request URI
* as a number after the last /. For example /random/whatever/20
* will generate 20 random bytes in the printable ASCII range.
* If the request URI ends with /, a random number of random bytes
* is generated, but at least one.
*
* @param request the request
* @param response the response
* @param context the context
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
public void handle(final HttpRequest request,
final HttpResponse response,
final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!"GET".equals(method) && !"HEAD".equals(method)) {
throw new MethodNotSupportedException
(method + " not supported by " + getClass().getName());
}
String uri = request.getRequestLine().getUri();
int slash = uri.lastIndexOf('/');
int length = -1;
if (slash < uri.length()-1) {
try {
// no more than Integer, 2 GB ought to be enough for anybody
length = Integer.parseInt(uri.substring(slash+1));
if (length < 0) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setReasonPhrase("LENGTH " + length);
}
} catch (NumberFormatException nfx) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setReasonPhrase(nfx.toString());
}
} else {
// random length, but make sure at least something is sent
length = 1 + (int)(Math.random() * 79.0);
}
if (length >= 0) {
response.setStatusCode(HttpStatus.SC_OK);
if (!"HEAD".equals(method)) {
RandomEntity entity = new RandomEntity(length);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
} else {
response.setHeader("Content-Type",
"text/plain; charset=US-ASCII");
response.setHeader("Content-Length",
String.valueOf(length));
}
}
} // handle
/**
* An entity that generates random data.
* This is an outgoing entity, it supports {@link #writeTo writeTo}
* but not {@link #getContent getContent}.
*/
public static class RandomEntity extends AbstractHttpEntity {
/** The range from which to generate random data. */
private final static byte[] RANGE;
static {
byte[] range = null;
try {
range = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
).getBytes("US-ASCII");
} catch (UnsupportedEncodingException uex) {
// never, US-ASCII is guaranteed
}
RANGE = range;
}
/** The length of the random data to generate. */
protected final long length;
/**
* Creates a new entity generating the given amount of data.
*
* @param len the number of random bytes to generate,
* 0 to maxint
*/
public RandomEntity(long len) {
if (len < 0L)
throw new IllegalArgumentException
("Length must not be negative");
if (len > Integer.MAX_VALUE)
throw new IllegalArgumentException
("Length must not exceed Integer.MAX_VALUE");
length = len;
}
/**
* Tells that this entity is not streaming.
*
* @return false
*/
public final boolean isStreaming() {
return false;
}
/**
* Tells that this entity is repeatable, in a way.
* Repetitions will generate different random data,
* unless perchance the same random data is generated twice.
*
* @return <code>true</code>
*/
public boolean isRepeatable() {
return true;
}
/**
* Obtains the size of the random data.
*
* @return the number of random bytes to generate
*/
public long getContentLength() {
return length;
}
/**
* Not supported.
* This method throws an exception.
*
* @return never anything
*/
public InputStream getContent() {
throw new UnsupportedOperationException();
}
/**
* Generates the random content.
*
* @param out where to write the content to
*/
public void writeTo(OutputStream out) throws IOException {
final int blocksize = 2048;
int remaining = (int) length; // range checked in constructor
byte[] data = new byte[Math.min(remaining, blocksize)];
while (remaining > 0) {
final int end = Math.min(remaining, data.length);
double value = 0.0;
for (int i = 0; i < end; i++) {
// we get 5 random characters out of one random value
if (i%5 == 0) {
value = Math.random();
}
value = value * RANGE.length;
int d = (int) value;
value = value - d;
data[i] = RANGE[d];
}
out.write(data, 0, end);
out.flush();
remaining = remaining - end;
}
out.close();
} // writeTo
} // class RandomEntity
} // class RandomHandler
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.junit.Before;
/**
* Base class for tests using {@link LocalTestServer LocalTestServer}.
* Note that the test server will be {@link #setUp set up} before each
* individual tests and {@link #tearDown teared down} afterwards.
* Use this base class <i>exclusively</i> for tests that require the
* server. If you have some tests that require the server and others
* that don't, split them in two different classes.
*/
public abstract class ServerTestBase extends BasicServerTestBase {
/** The available schemes. */
protected SchemeRegistry supportedSchemes;
/** The default parameters for the client side. */
protected HttpParams defaultParams;
/** The HTTP processor for the client side. */
protected BasicHttpProcessor httpProcessor;
/** The default context for the client side. */
protected BasicHttpContext httpContext;
/** The request executor for the client side. */
protected HttpRequestExecutor httpExecutor;
/**
* Prepares the local server for testing.
* Derived classes that override this method MUST call
* the implementation here. That SHOULD be done at the
* beginning of the overriding method.
* <br/>
* Derived methods can modify for example the default parameters
* being set up, or the interceptors.
* <p>
* This method will re-use the helper objects from a previous run
* if they are still available. For example, the local test server
* will be re-started rather than re-created.
* {@link #httpContext httpContext} will always be re-created.
* Tests that modify the other helper objects should afterwards
* set the respective attributes to <code>null</code> in a
* <code>finally{}</code> block to force re-creation for
* subsequent tests.
* Of course that shouldn't be done with the test server,
* or only after shutting that down.
*
* @throws Exception in case of a problem
*/
@Before
public void setUp() throws Exception {
if (defaultParams == null) {
defaultParams = new SyncBasicHttpParams();
HttpProtocolParams.setVersion
(defaultParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset
(defaultParams, "UTF-8");
HttpProtocolParams.setUserAgent
(defaultParams, "TestAgent/1.1");
HttpProtocolParams.setUseExpectContinue
(defaultParams, false);
}
if (supportedSchemes == null) {
supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
}
if (httpProcessor == null) {
httpProcessor = new BasicHttpProcessor();
httpProcessor.addInterceptor(new RequestContent());
httpProcessor.addInterceptor(new RequestConnControl()); // optional
}
// the context is created each time, it may get modified by test cases
httpContext = new BasicHttpContext(null);
if (httpExecutor == null) {
httpExecutor = new HttpRequestExecutor();
}
if (localServer == null) {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
}
localServer.start();
} // setUp
/**
* Opens a connection to the given target using
* {@link #defaultParams default parameters}.
* Maps to {@link #connectTo(HttpHost,HttpParams)
* connectTo(target,defaultParams)}.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target)
throws Exception {
return connectTo(target, defaultParams);
}
/**
* Opens a connection to the given target using the given parameters.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target,
HttpParams params)
throws Exception {
Scheme schm = supportedSchemes.get(target.getSchemeName());
int port = schm.resolvePort(target.getPort());
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
InetSocketAddress address = new InetSocketAddress(
InetAddress.getByName(target.getHostName()), port);
Socket sock = schm.getSchemeSocketFactory().connectSocket(null, address, null, params);
conn.bind(sock, params);
return 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.ogt.http.localserver;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.protocol.HttpContext;
public class RequestBasicAuth implements HttpRequestInterceptor {
private final BasicAuthTokenExtractor authTokenExtractor;
public RequestBasicAuth() {
super();
this.authTokenExtractor = new BasicAuthTokenExtractor();
}
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
context.setAttribute("creds", this.authTokenExtractor.extract(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.ogt.http.localserver;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.util.EncodingUtils;
public class BasicAuthTokenExtractor {
public String extract(final HttpRequest request) throws HttpException {
String auth = null;
Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
if (h != null) {
String s = h.getValue();
if (s != null) {
auth = s.trim();
}
}
if (auth != null) {
int i = auth.indexOf(' ');
if (i == -1) {
throw new ProtocolException("Invalid Authorization header: " + auth);
}
String authscheme = auth.substring(0, i);
if (authscheme.equalsIgnoreCase("basic")) {
String s = auth.substring(i + 1).trim();
try {
byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
BinaryDecoder codec = new Base64();
auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
} catch (DecoderException ex) {
throw new ProtocolException("Malformed BASIC credentials");
}
}
}
return auth;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation.
*/
public class SessionInputBufferMockup extends AbstractSessionInputBuffer {
public static final int BUFFER_SIZE = 16;
public SessionInputBufferMockup(
final InputStream instream,
int buffersize,
final HttpParams params) {
super();
init(instream, buffersize, params);
}
public SessionInputBufferMockup(
final InputStream instream,
int buffersize) {
this(instream, buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
final HttpParams params) {
this(bytes, BUFFER_SIZE, params);
}
public SessionInputBufferMockup(
final byte[] bytes) {
this(bytes, BUFFER_SIZE, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize,
final HttpParams params) {
this(new ByteArrayInputStream(bytes), buffersize, params);
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize) {
this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, params);
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), params);
}
public SessionInputBufferMockup(
final String s,
final String charset)
throws UnsupportedEncodingException {
this(s.getBytes(charset), new BasicHttpParams());
}
public boolean isDataAvailable(int timeout) throws IOException {
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.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
/**
* {@link HttpConnection} mockup implementation.
*
*/
public class HttpConnectionMockup implements HttpConnection {
private boolean open = true;
public HttpConnectionMockup() {
super();
}
public void close() throws IOException {
this.open = false;
}
public void shutdown() throws IOException {
this.open = false;
}
public int getSocketTimeout() {
return 0;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public void setSocketTimeout(int timeout) {
}
public HttpConnectionMetrics getMetrics() {
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.mockup;
import java.net.Socket;
import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory;
/**
* {@link LayeredSchemeSocketFactory} mockup implementation.
*/
public class SecureSocketFactoryMockup extends SocketFactoryMockup
implements LayeredSchemeSocketFactory {
/* A default instance of this mockup. */
public final static LayeredSchemeSocketFactory INSTANCE = new SecureSocketFactoryMockup("INSTANCE");
public SecureSocketFactoryMockup(String name) {
super(name);
}
// don't implement equals and hashcode, all instances are different!
@Override
public String toString() {
return "SecureSocketFactoryMockup." + mockup_name;
}
public Socket createLayeredSocket(Socket socket, String host, int port,
boolean autoClose) {
throw new UnsupportedOperationException("I'm 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SchemeSocketFactory} mockup implementation.
*/
public class SocketFactoryMockup implements SchemeSocketFactory {
/* A default instance of this mockup. */
public final static SchemeSocketFactory INSTANCE = new SocketFactoryMockup("INSTANCE");
/** The name of this mockup socket factory. */
protected final String mockup_name;
public SocketFactoryMockup(String name) {
mockup_name = (name != null) ? name : String.valueOf(hashCode());
}
// don't implement equals and hashcode, all instances are different!
@Override
public String toString() {
return "SocketFactoryMockup." + mockup_name;
}
public Socket createSocket(final HttpParams params) {
throw new UnsupportedOperationException("I'm a mockup!");
}
public Socket connectSocket(
Socket sock,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
throw new UnsupportedOperationException("I'm a mockup!");
}
public boolean isSecure(Socket sock) {
// no way that the argument is from *this* factory...
throw new IllegalArgumentException("I'm 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.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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.